diff --git a/README.md b/README.md index 8b27a150..a0d8a3a4 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Web-basiertes CRM-System für Kundenverwaltung mit Verträgen (Energie, Telekomm - **Email-Provisionierung**: Automatische E-Mail-Weiterleitung bei Plesk/cPanel/DirectAdmin - **Berechtigungssystem**: Admin, Mitarbeiter, Nur-Lesen, Kundenportal - **Verschlüsselte Zugangsdaten**: Portal-Passwörter AES-256-GCM verschlüsselt +- **DSGVO-Compliance**: Audit-Logging, Einwilligungsverwaltung, Datenexport, Löschanfragen - **Developer-Tools**: Datenbank-Browser und interaktives ER-Diagramm ## Tech Stack @@ -207,7 +208,7 @@ npm run build # Produktions-Build erstellen npm run preview # Build-Vorschau ``` -### Docker +### Docker (Entwicklung) ```bash docker-compose up -d # Container starten @@ -216,6 +217,40 @@ docker-compose down -v # Container stoppen + Daten löschen docker-compose logs -f # Logs anzeigen ``` +### Docker (Produktion) + +Im `docker/` Verzeichnis liegt ein komplettes Produktions-Setup: + +```bash +cd docker + +# Image bauen +docker-compose build + +# Container starten +docker-compose up -d + +# Logs anzeigen +docker-compose logs -f app +``` + +**Komponenten:** +- **MariaDB 10.11**: Datenbank +- **App**: Backend + Frontend in einem Container +- **Caddy**: Reverse-Proxy mit automatischem SSL + +**Umgebungsvariablen (`docker/.env`):** +```env +MYSQL_ROOT_PASSWORD=sicheres-root-passwort +MYSQL_DATABASE=opencrm +MYSQL_USER=opencrm +MYSQL_PASSWORD=sicheres-passwort +JWT_SECRET=sehr-langer-zufaelliger-string +ENCRYPTION_KEY=64-zeichen-hex-string +DOMAIN=crm.example.com +RUN_SEED=true # Nur beim ersten Start +``` + ## Projektstruktur ``` @@ -223,9 +258,20 @@ opencrm/ ├── backend/ │ ├── src/ │ │ ├── controllers/ # Request-Handler +│ │ │ ├── auditLog.controller.ts # Audit-Log API +│ │ │ └── gdpr.controller.ts # DSGVO API │ │ ├── middleware/ # Auth, Validation +│ │ │ ├── audit.ts # Automatisches API-Logging +│ │ │ └── auditContext.ts # Before/After Context │ │ ├── routes/ # API-Endpunkte +│ │ │ ├── auditLog.routes.ts # Audit-Log Routes +│ │ │ └── gdpr.routes.ts # DSGVO Routes │ │ ├── services/ # Business-Logik +│ │ │ ├── audit.service.ts # Hash-Kette, Logging +│ │ │ ├── consent.service.ts # Einwilligungen +│ │ │ └── gdpr.service.ts # Export, Löschung +│ │ ├── lib/ +│ │ │ └── prisma.ts # Prisma mit Audit-Middleware │ │ ├── types/ # TypeScript-Typen │ │ └── index.ts # Server-Einstiegspunkt │ ├── prisma/ @@ -235,6 +281,7 @@ opencrm/ │ │ ├── bank-cards/ # Bankkarten-Dokumente │ │ ├── documents/ # Ausweis-Scans │ │ ├── invoices/ # Rechnungsdokumente (Strom/Gas) +│ │ ├── gdpr/ # DSGVO-Löschnachweise │ │ ├── business-registrations/ # Gewerbeanmeldungen │ │ ├── commercial-registers/ # Handelsregisterauszüge │ │ ├── privacy-policies/ # Datenschutzerklärungen @@ -246,23 +293,31 @@ opencrm/ │ ├── src/ │ │ ├── components/ # UI-Komponenten │ │ ├── pages/ # Seiten +│ │ │ └── settings/ +│ │ │ ├── AuditLogs.tsx # Audit-Protokoll +│ │ │ └── GDPRDashboard.tsx # DSGVO-Dashboard │ │ ├── hooks/ # Custom Hooks │ │ ├── services/ # API-Client │ │ ├── types/ # TypeScript-Typen │ │ └── App.tsx # Haupt-Komponente │ └── package.json -├── docker-compose.yml # MariaDB-Container +├── docker/ # Docker-Deployment +│ ├── Dockerfile # Multi-Stage Build +│ ├── docker-compose.yml # Produktion (MariaDB, App, Caddy) +│ ├── Caddyfile # Reverse-Proxy mit SSL +│ └── entrypoint.sh # Container-Startup +├── docker-compose.yml # MariaDB-Container (Entwicklung) └── README.md ``` ## Berechtigungen -| Rolle | Kunden | Verträge | Benutzer | Plattformen | Developer | -|-------|--------|----------|----------|-------------|-----------| -| Admin | CRUD | CRUD | CRUD | CRUD | Optional | -| Mitarbeiter | CRUD | CRUD | - | Lesen | - | -| Mitarbeiter (Lesen) | Lesen | Lesen | - | Lesen | - | -| Kunde | Eigene | Eigene | - | - | - | +| Rolle | Kunden | Verträge | Benutzer | Plattformen | Audit/DSGVO | Developer | +|-------|--------|----------|----------|-------------|-------------|-----------| +| Admin | CRUD | CRUD | CRUD | CRUD | Vollzugriff | Optional | +| Mitarbeiter | CRUD | CRUD | - | Lesen | Lesen | - | +| Mitarbeiter (Lesen) | Lesen | Lesen | - | Lesen | - | - | +| Kunde | Eigene | Eigene | - | - | - | - | ## Troubleshooting @@ -708,6 +763,159 @@ In der Kundendetailansicht werden Verträge als **Baumstruktur** mit Vorgänger- > **Hinweis:** In der Hauptvertragsliste (`/contracts`) wird weiterhin die flache Ansicht ohne Baumstruktur verwendet. +## DSGVO-Compliance & Audit-Logging + +Umfassendes Audit-Logging-System mit DSGVO-Compliance-Features. + +### Audit-Protokoll + +Automatische Protokollierung aller API-Zugriffe mit: + +| Feld | Beschreibung | +|------|--------------| +| **Benutzer** | User-ID, E-Mail, Rolle | +| **Aktion** | CREATE, READ, UPDATE, DELETE, EXPORT, ANONYMIZE, LOGIN, LOGOUT | +| **Ressource** | Tabelle + ID + lesbare Bezeichnung | +| **Kontext** | Endpoint, HTTP-Methode, IP-Adresse, User-Agent | +| **Änderungen** | Vorher/Nachher-Werte (bei Updates) | +| **Sensitivität** | LOW, MEDIUM, HIGH, CRITICAL | +| **Integrität** | SHA-256 Hash-Kette für Manipulationsschutz | + +#### Sensitivitätsstufen + +| Stufe | Ressourcen | +|-------|------------| +| **LOW** | Einstellungen, Plattformen, Tarife | +| **MEDIUM** | Verträge, Provider | +| **HIGH** | Kundendaten, Benutzerdaten | +| **CRITICAL** | Authentifizierung, Bankdaten, Ausweisdokumente | + +#### Zugriff + +- **Einstellungen** → **Audit-Protokoll** +- Filter nach: Datum, Benutzer, Aktion, Ressource, Sensitivität +- Detail-Ansicht mit Vorher/Nachher-Diff +- Export als JSON +- Integritätsprüfung (Hash-Kette verifizieren) + +### DSGVO-Dashboard + +Zentrale Verwaltung für DSGVO-Anfragen unter **Einstellungen** → **DSGVO-Dashboard**. + +#### Dashboard-Statistiken + +- Offene Löschanfragen +- Abgeschlossene Löschungen (letzte 30 Tage) +- Datenexporte (letzte 30 Tage) +- Aktive Einwilligungen + +#### Einwilligungsverwaltung (Consents) + +| Consent-Typ | Beschreibung | +|-------------|--------------| +| **DATA_PROCESSING** | Grundlegende Datenverarbeitung | +| **MARKETING_EMAIL** | E-Mail-Marketing | +| **MARKETING_PHONE** | Telefonmarketing | +| **DATA_SHARING_PARTNER** | Datenweitergabe an Partner | + +Einwilligungen können pro Kunde im Tab "Einwilligungen" verwaltet werden. + +#### Löschanfragen (Art. 17) + +Workflow für DSGVO-Löschanfragen: + +| Status | Beschreibung | +|--------|--------------| +| **PENDING** | Anfrage eingegangen | +| **IN_PROGRESS** | Wird bearbeitet | +| **COMPLETED** | Vollständig gelöscht/anonymisiert | +| **PARTIALLY_COMPLETED** | Teildaten behalten (z.B. aktive Verträge) | +| **REJECTED** | Abgelehnt mit Begründung | + +**Anonymisierung statt Löschung:** +- Kundendaten werden anonymisiert (nicht gelöscht) +- Aktive Verträge werden beibehalten +- PDF-Löschnachweis wird generiert + +#### Datenexport (Art. 15) + +Kunden können alle gespeicherten Daten als JSON exportieren: +- Stammdaten +- Adressen, Bankdaten, Ausweise +- Verträge mit Details +- Zähler und Ablesungen +- Einwilligungen +- Zugriffsprotokolle + +### API-Endpunkte + +``` +# Audit-Logs +GET /api/audit-logs # Logs mit Filtern +GET /api/audit-logs/:id # Einzelnes Log +GET /api/audit-logs/customer/:id # Logs für Kunde +GET /api/audit-logs/export # Export (JSON/CSV) +POST /api/audit-logs/verify # Hash-Kette prüfen +GET /api/audit-logs/retention-policies # Aufbewahrungsfristen +PUT /api/audit-logs/retention-policies/:id +POST /api/audit-logs/cleanup # Manuelle Bereinigung + +# DSGVO +GET /api/gdpr/dashboard # Dashboard-Statistiken +GET /api/gdpr/customer/:id/export # Kundendaten-Export +GET /api/gdpr/deletions # Löschanfragen +POST /api/gdpr/deletions # Löschanfrage erstellen +PUT /api/gdpr/deletions/:id/process # Löschanfrage bearbeiten +GET /api/gdpr/customer/:id/consents # Einwilligungen abrufen +PUT /api/gdpr/customer/:id/consents/:type # Einwilligung ändern +GET /api/gdpr/consents/overview # Consent-Übersicht +``` + +### Aufbewahrungsfristen + +| Ressource | Frist | Rechtsgrundlage | +|-----------|-------|-----------------| +| Standard | 10 Jahre | AO §147, HGB §257 | +| Authentifizierung | 2 Jahre | Sicherheit | +| Kundendaten (HIGH) | 10 Jahre | Steuerrecht | +| Verträge | 10 Jahre | Steuerrecht | +| Allgemein (LOW) | 3 Jahre | Verjährung | + +### Berechtigungen + +| Aktion | Berechtigung | +|--------|--------------| +| Audit-Logs lesen | `audit:read` | +| Audit-Logs exportieren | `audit:export` | +| Audit-Administration | `audit:admin` | +| DSGVO-Export | `gdpr:export` | +| Löschanfrage erstellen | `gdpr:delete` | +| DSGVO-Administration | `gdpr:admin` | + +### Technische Details + +#### Hash-Kette + +Jeder Audit-Log-Eintrag enthält einen SHA-256-Hash über: +- Alle Felder des Eintrags +- Hash des vorherigen Eintrags + +Dies ermöglicht die Erkennung von Manipulationen. + +#### Sensitive Daten + +Folgende Felder werden in Audit-Logs gefiltert: +- `password`, `passwordHash` +- `portalPasswordHash`, `portalPasswordEncrypted` +- `emailPasswordEncrypted`, `internetPasswordEncrypted` +- `sipPasswordEncrypted`, `pin`, `puk`, `apiKey` + +#### Performance + +- Logging erfolgt asynchron (`setImmediate`) +- API-Response wird nicht blockiert +- Before/After-Werte über Prisma Middleware + ## Lizenz MIT diff --git a/backend/dist/controllers/contract.controller.d.ts.map b/backend/dist/controllers/contract.controller.d.ts.map index 34a5ce51..31805b6d 100644 --- a/backend/dist/controllers/contract.controller.d.ts.map +++ b/backend/dist/controllers/contract.controller.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"contract.controller.d.ts","sourceRoot":"","sources":["../../src/controllers/contract.controller.ts"],"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C,CAUtF;AAED,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAUvF;AAED,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAUlF;AAID,wBAAsB,UAAU,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAW/E;AAID,wBAAsB,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAyC/E"} \ No newline at end of file diff --git a/backend/dist/controllers/contract.controller.js b/backend/dist/controllers/contract.controller.js index fee0983d..a7cc37b2 100644 --- a/backend/dist/controllers/contract.controller.js +++ b/backend/dist/controllers/contract.controller.js @@ -49,6 +49,7 @@ const client_1 = require("@prisma/client"); const contractService = __importStar(require("../services/contract.service.js")); const contractCockpitService = __importStar(require("../services/contractCockpit.service.js")); const contractHistoryService = __importStar(require("../services/contractHistory.service.js")); +const authorizationService = __importStar(require("../services/authorization.service.js")); const prisma = new client_1.PrismaClient(); async function getContracts(req, res) { try { @@ -59,11 +60,19 @@ async function getContracts(req, res) { res.json({ success: true, data: treeData }); return; } - // Für Kundenportal-Benutzer: nur eigene + vertretene Kunden-Verträge anzeigen + // Für Kundenportal-Benutzer: nur eigene + vertretene Kunden MIT Vollmacht let customerIds; if (req.user?.isCustomerPortal && req.user.customerId) { - // Eigene Customer-ID + alle vertretenen Kunden-IDs - customerIds = [req.user.customerId, ...(req.user.representedCustomerIds || [])]; + // Eigene Customer-ID immer + customerIds = [req.user.customerId]; + // Vertretene Kunden nur wenn Vollmacht erteilt + const representedIds = req.user.representedCustomerIds || []; + for (const repCustId of representedIds) { + const hasAuth = await authorizationService.hasAuthorization(repCustId, req.user.customerId); + if (hasAuth) { + customerIds.push(repCustId); + } + } } const result = await contractService.getAllContracts({ customerId: customerId ? parseInt(customerId) : undefined, @@ -97,9 +106,16 @@ async function getContract(req, res) { }); return; } - // Für Kundenportal-Benutzer: Zugriff nur auf eigene + vertretene Kunden-Verträge + // Für Kundenportal-Benutzer: Zugriff nur auf eigene + vertretene Kunden MIT Vollmacht if (req.user?.isCustomerPortal && req.user.customerId) { - const allowedCustomerIds = [req.user.customerId, ...(req.user.representedCustomerIds || [])]; + const allowedCustomerIds = [req.user.customerId]; + const representedIds = req.user.representedCustomerIds || []; + for (const repCustId of representedIds) { + const hasAuth = await authorizationService.hasAuthorization(repCustId, req.user.customerId); + if (hasAuth) { + allowedCustomerIds.push(repCustId); + } + } if (!allowedCustomerIds.includes(contract.customerId)) { res.status(403).json({ success: false, diff --git a/backend/dist/controllers/contract.controller.js.map b/backend/dist/controllers/contract.controller.js.map index 41224387..b0df7d78 100644 --- a/backend/dist/controllers/contract.controller.js.map +++ b/backend/dist/controllers/contract.controller.js.map @@ -1 +1 @@ -{"version":3,"file":"contract.controller.js","sourceRoot":"","sources":["../../src/controllers/contract.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,oCAwCC;AAED,kCA8BC;AAED,wCAUC;AAED,wCAUC;AAED,wCAUC;AAED,wCAuCC;AAED,kDAiBC;AAED,sDAUC;AAED,wDAUC;AAED,8CAUC;AAID,gCAWC;AAID,wCAyCC;AAhRD,2CAA8C;AAC9C,iFAAmE;AACnE,+FAAiF;AACjF,+FAAiF;AAGjF,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAE3B,KAAK,UAAU,YAAY,CAAC,GAAgB,EAAE,GAAa;IAChE,IAAI,CAAC;QACH,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;QAE1E,iCAAiC;QACjC,IAAI,IA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CAAC;QACD,4EAA4E;QAE5E,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;YAC3C,KAAK,EAAE,EAAE,EAAE,EAAE;YACb,IAAI,EAAE,EAAE,cAAc,EAAE,UAAU,EAAE;YACpC,MAAM,EAAE;gBACN,EAAE,EAAE,IAAI;gBACR,cAAc,EAAE,IAAI;gBACpB,cAAc,EAAE,IAAI;aACrB;SACF,CAAC,CAAC;QAEH,GAAG,CAAC,IAAI,CAAC;YACP,OAAO,EAAE,IAAI;YACb,IAAI,EAAE,OAAO;YACb,OAAO,EAAE,UAAU;gBACjB,CAAC,CAAC,8BAA8B,UAAU,CAAC,kBAAkB,CAAC,OAAO,CAAC,EAAE;gBACxE,CAAC,CAAC,2BAA2B;SACjB,CAAC,CAAC;IACpB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;QACtC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,wCAAwC;SACjC,CAAC,CAAC;IACpB,CAAC;AACH,CAAC"} \ No newline at end of file +{"version":3,"file":"contract.controller.js","sourceRoot":"","sources":["../../src/controllers/contract.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,oCAgDC;AAED,kCAqCC;AAED,wCAUC;AAED,wCAUC;AAED,wCAUC;AAED,wCAuCC;AAED,kDAiBC;AAED,sDAUC;AAED,wDAUC;AAED,8CAUC;AAID,gCAWC;AAID,wCAyCC;AAhSD,2CAA8C;AAC9C,iFAAmE;AACnE,+FAAiF;AACjF,+FAAiF;AACjF,2FAA6E;AAG7E,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAE3B,KAAK,UAAU,YAAY,CAAC,GAAgB,EAAE,GAAa;IAChE,IAAI,CAAC;QACH,M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AC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;QACtC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,wCAAwC;SACjC,CAAC,CAAC;IACpB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/backend/dist/controllers/customer.controller.d.ts b/backend/dist/controllers/customer.controller.d.ts index b8f78a6a..dcb510a4 100644 --- a/backend/dist/controllers/customer.controller.d.ts +++ b/backend/dist/controllers/customer.controller.d.ts @@ -1,4 +1,5 @@ import { Request, Response } from 'express'; +import { AuthRequest } from '../types/index.js'; export declare function getCustomers(req: Request, res: Response): Promise; export declare function getCustomer(req: Request, res: Response): Promise; export declare function createCustomer(req: Request, res: Response): Promise; @@ -24,6 +25,9 @@ export declare function getMeterReadings(req: Request, res: Response): Promise; export declare function updateMeterReading(req: Request, res: Response): Promise; export declare function deleteMeterReading(req: Request, res: Response): Promise; +export declare function reportMeterReading(req: AuthRequest, res: Response): Promise; +export declare function getMyMeters(req: AuthRequest, res: Response): Promise; +export declare function markReadingTransferred(req: AuthRequest, res: Response): Promise; export declare function getPortalSettings(req: Request, res: Response): Promise; export declare function updatePortalSettings(req: Request, res: Response): Promise; export declare function setPortalPassword(req: Request, res: Response): Promise; diff --git a/backend/dist/controllers/customer.controller.d.ts.map b/backend/dist/controllers/customer.controller.d.ts.map index ff70cd94..71ace7a7 100644 --- a/backend/dist/controllers/customer.controller.d.ts.map +++ b/backend/dist/controllers/customer.controller.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"customer.controller.d.ts","sourceRoot":"","sources":["../../src/controllers/customer.controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAM5C,wBAAsB,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ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AAC,IAAI,CAAC,CAcnF;AAED,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAanF;AAID,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBlF;AAED,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAcrF;AAED,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBlF;AAED,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAUlF;AAID,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAWnF;AAED,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAelF;AAED,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAarF;AAED,wBAAsB,uBAAuB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxF"} \ No newline at end of file +{"version":3,"file":"customer.controller.d.ts","sourceRoot":"","sources":["../../src/controllers/customer.controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAI5C,OAAO,EAAe,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAK7D,wBAAsB,YAAY,CAAC,GAA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C,IAAI,CAAC,CAarF;AAED,wBAAsB,uBAAuB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxF"} \ No newline at end of file diff --git a/backend/dist/controllers/customer.controller.js b/backend/dist/controllers/customer.controller.js index 259cd639..a4fa55bd 100644 --- a/backend/dist/controllers/customer.controller.js +++ b/backend/dist/controllers/customer.controller.js @@ -58,6 +58,9 @@ exports.getMeterReadings = getMeterReadings; exports.addMeterReading = addMeterReading; exports.updateMeterReading = updateMeterReading; exports.deleteMeterReading = deleteMeterReading; +exports.reportMeterReading = reportMeterReading; +exports.getMyMeters = getMyMeters; +exports.markReadingTransferred = markReadingTransferred; exports.getPortalSettings = getPortalSettings; exports.updatePortalSettings = updatePortalSettings; exports.setPortalPassword = setPortalPassword; @@ -66,8 +69,10 @@ exports.getRepresentatives = getRepresentatives; exports.addRepresentative = addRepresentative; exports.removeRepresentative = removeRepresentative; exports.searchForRepresentative = searchForRepresentative; +const client_1 = require("@prisma/client"); const customerService = __importStar(require("../services/customer.service.js")); const authService = __importStar(require("../services/auth.service.js")); +const prisma = new client_1.PrismaClient(); // Customer CRUD async function getCustomers(req, res) { try { @@ -380,6 +385,88 @@ async function deleteMeterReading(req, res) { }); } } +// ==================== PORTAL: ZÄHLERSTAND MELDEN ==================== +async function reportMeterReading(req, res) { + try { + const user = req.user; + if (!user?.isCustomerPortal || !user?.customerId) { + res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + return; + } + const meterId = parseInt(req.params.meterId); + const { value, readingDate, notes } = req.body; + // Prüfe ob der Zähler zum Kunden gehört + const meter = await prisma.meter.findUnique({ + where: { id: meterId }, + select: { customerId: true }, + }); + if (!meter || meter.customerId !== user.customerId) { + res.status(403).json({ success: false, error: 'Kein Zugriff auf diesen Zähler' }); + return; + } + const reading = await prisma.meterReading.create({ + data: { + meterId, + value: parseFloat(value), + readingDate: readingDate ? new Date(readingDate) : new Date(), + notes, + reportedBy: user.email, + status: 'REPORTED', + }, + }); + res.status(201).json({ success: true, data: reading }); + } + catch (error) { + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Melden des Zählerstands', + }); + } +} +async function getMyMeters(req, res) { + try { + const user = req.user; + if (!user?.isCustomerPortal || !user?.customerId) { + res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + return; + } + const meters = await prisma.meter.findMany({ + where: { customerId: user.customerId, isActive: true }, + include: { + readings: { + orderBy: { readingDate: 'desc' }, + take: 5, + }, + }, + orderBy: { createdAt: 'asc' }, + }); + res.json({ success: true, data: meters }); + } + catch (error) { + res.status(500).json({ success: false, error: 'Fehler beim Laden der Zähler' }); + } +} +async function markReadingTransferred(req, res) { + try { + const meterId = parseInt(req.params.meterId); + const readingId = parseInt(req.params.readingId); + const reading = await prisma.meterReading.update({ + where: { id: readingId }, + data: { + status: 'TRANSFERRED', + transferredAt: new Date(), + transferredBy: req.user?.email, + }, + }); + res.json({ success: true, data: reading }); + } + catch (error) { + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Aktualisieren', + }); + } +} // ==================== PORTAL SETTINGS ==================== async function getPortalSettings(req, res) { try { diff --git a/backend/dist/controllers/customer.controller.js.map b/backend/dist/controllers/customer.controller.js.map index 32a21e19..c41144bd 100644 --- a/backend/dist/controllers/customer.controller.js.map +++ b/backend/dist/controllers/customer.controller.js.map @@ -1 +1 @@ -{"version":3,"file":"customer.controller.js","sourceRoot":"","sources":["../../src/controllers/customer.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,oCAgBC;AAED,kCAWC;AAED,wCAeC;AAED,wCAgBC;AAED,wCAUC;AAGD,oCAOC;AAED,sCAUC;AAED,sCAUC;AAED,sCAUC;AAGD,oCAWC;AAED,wCAUC;AAED,wCAUC;AAED,wCAUC;AAGD,oCAWC;AAED,wCAUC;AAED,wCAUC;AAED,wCAUC;AA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C,CAAC,sCAAsC;SACxE,CAAC,CAAC;IACpB,CAAC;AACH,CAAC;AAEM,KAAK,UAAU,uBAAuB,CAAC,GAAY,EAAE,GAAa;IACvE,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;QAC7B,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/D,GAAG,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAiB,CAAC,CAAC;YACrD,OAAO;QACT,CAAC;QACD,MAAM,SAAS,GAAG,MAAM,eAAe,CAAC,gCAAgC,CACtE,MAAM,EACN,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAChC,CAAC;QACF,GAAG,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAiB,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,sBAAsB;SACf,CAAC,CAAC;IACpB,CAAC;AACH,CAAC"} \ No newline at end of file +{"version":3,"file":"customer.controller.js","sourceRoot":"","sources":["../../src/controllers/customer.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,oCAgBC;AAED,kCAWC;AAED,wCAeC;AAED,wCAgBC;AAED,wCAUC;AAGD,oCAOC;AAED,sCAUC;AAED,sCAUC;AAED,sCAUC;AAGD,oCAWC;AAED,wCAUC;AAED,wCAUC;AAED,wCAUC;AAGD,oCAWC;AAED,wCAUC;AAED,wCAUC;AAED,wCAUC;AAGD,8BAWC;AAED,kCAUC;AAED,kCAUC;AAED,kCAUC;AAGD,4CAOC;AAED,0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;IACvE,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC;QAC7B,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/D,GAAG,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAiB,CAAC,CAAC;YACrD,OAAO;QACT,CAAC;QACD,MAAM,SAAS,GAAG,MAAM,eAAe,CAAC,gCAAgC,CACtE,MAAM,EACN,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAChC,CAAC;QACF,GAAG,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAiB,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;YACnB,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,sBAAsB;SACf,CAAC,CAAC;IACpB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/backend/dist/index.js b/backend/dist/index.js index f0295f03..1b3ff33d 100644 --- a/backend/dist/index.js +++ b/backend/dist/index.js @@ -30,14 +30,25 @@ const emailProvider_routes_js_1 = __importDefault(require("./routes/emailProvide const cachedEmail_routes_js_1 = __importDefault(require("./routes/cachedEmail.routes.js")); const invoice_routes_js_1 = __importDefault(require("./routes/invoice.routes.js")); const contractHistory_routes_js_1 = __importDefault(require("./routes/contractHistory.routes.js")); +const auditLog_routes_js_1 = __importDefault(require("./routes/auditLog.routes.js")); +const gdpr_routes_js_1 = __importDefault(require("./routes/gdpr.routes.js")); +const consent_public_routes_js_1 = __importDefault(require("./routes/consent-public.routes.js")); +const emailLog_routes_js_1 = __importDefault(require("./routes/emailLog.routes.js")); +const auditContext_js_1 = require("./middleware/auditContext.js"); +const audit_js_1 = require("./middleware/audit.js"); dotenv_1.default.config(); const app = (0, express_1.default)(); const PORT = process.env.PORT || 3001; // Middleware app.use((0, cors_1.default)()); app.use(express_1.default.json()); +// Audit-Logging Middleware (DSGVO-konform) +app.use(auditContext_js_1.auditContextMiddleware); +app.use(audit_js_1.auditMiddleware); // Statische Dateien für Uploads app.use('/api/uploads', express_1.default.static(path_1.default.join(process.cwd(), 'uploads'))); +// Öffentliche Routes (OHNE Authentifizierung) +app.use('/api/public/consent', consent_public_routes_js_1.default); // Routes app.use('/api/auth', auth_routes_js_1.default); app.use('/api/customers', customer_routes_js_1.default); @@ -62,6 +73,9 @@ app.use('/api/email-providers', emailProvider_routes_js_1.default); app.use('/api', cachedEmail_routes_js_1.default); app.use('/api/energy-details', invoice_routes_js_1.default); app.use('/api', contractHistory_routes_js_1.default); +app.use('/api/audit-logs', auditLog_routes_js_1.default); +app.use('/api/gdpr', gdpr_routes_js_1.default); +app.use('/api/email-logs', emailLog_routes_js_1.default); // Health check app.get('/api/health', (req, res) => { res.json({ status: 'ok', timestamp: new Date().toISOString() }); diff --git a/backend/dist/index.js.map b/backend/dist/index.js.map index f625268c..9480416c 100644 --- a/backend/dist/index.js.map +++ b/backend/dist/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,sDAA8B;AAC9B,gDAAwB;AACxB,gDAAwB;AACxB,oDAA4B;AAE5B,6EAAiD;AACjD,qFAAyD;AACzD,mFAAuD;AACvD,qFAAyD;AACzD,qFAAyD;AACzD,+EAAmD;AACnD,mGAAuE;AACvE,qFAAyD;AACzD,qFAAyD;AACzD,2GAA8E;AAC9E,uGAA0E;AAC1E,qFAAyD;AACzD,iFAAqD;AACrD,6EAAiD;AACjD,iFAAqD;AACrD,uFAA2D;AAC3D,qGAAyE;AACzE,6FAAiE;AACjE,yFAA6D;AAC7D,+FAAmE;AACnE,2FAA+D;AAC/D,mFAAuD;AACvD,m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AC;AAEH,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE;IACpB,OAAO,CAAC,GAAG,CAAC,yBAAyB,IAAI,EAAE,CAAC,CAAC;AAC/C,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/backend/dist/middleware/auth.d.ts.map b/backend/dist/middleware/auth.d.ts.map index 5a506144..f7b1f307 100644 --- a/backend/dist/middleware/auth.d.ts.map +++ b/backend/dist/middleware/auth.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/middleware/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGjD,OAAO,EAAE,WAAW,EAAc,MAAM,mBAAmB,CAAC;AAI5D,wBAAsB,YAAY,CAChC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,IAAI,CAAC,CAuDf;AAED,wBAAgB,iBAAiB,CAAC,GAAG,mBAAmB,EAAE,MAAM,EAAE,IACxD,KAAK,WAAW,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,KAAG,IAAI,CAuBnE;AAGD,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,YAAY,GACjB,IAAI,CA4BN"} \ No newline at end of file +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/middleware/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGjD,OAAO,EAAE,WAAW,EAAc,MAAM,mBAAmB,CAAC;AAI5D,wBAAsB,YAAY,CAChC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,YAAY,GACjB,OAAO,CAAC,IAAI,CAAC,CAuDf;AAED,wBAAgB,iBAAiB,CAAC,GAAG,mBAAmB,EAAE,MAAM,EAAE,IACxD,KAAK,WAAW,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,KAAG,IAAI,CAuBnE;AAGD,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,YAAY,GACjB,IAAI,CAiCN"} \ No newline at end of file diff --git a/backend/dist/middleware/auth.js b/backend/dist/middleware/auth.js index 04d5739f..6dbe29e4 100644 --- a/backend/dist/middleware/auth.js +++ b/backend/dist/middleware/auth.js @@ -88,9 +88,13 @@ function requireCustomerAccess(req, res, next) { next(); return; } - // Customers can only access their own data + // Customers can only access their own data + represented customers const customerId = parseInt(req.params.customerId || req.params.id); - if (req.user.customerId && req.user.customerId === customerId) { + const allowedIds = [ + req.user.customerId, + ...(req.user.representedCustomerIds || []), + ].filter(Boolean); + if (allowedIds.includes(customerId)) { next(); return; } diff --git a/backend/dist/middleware/auth.js.map b/backend/dist/middleware/auth.js.map index b4058a31..fb5857b5 100644 --- a/backend/dist/middleware/auth.js.map +++ b/backend/dist/middleware/auth.js.map @@ -1 +1 @@ -{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/middleware/auth.ts"],"names":[],"mappings":";;;;;AAOA,oCA2DC;AAED,8CAwBC;AAGD,sDAgCC;AA9HD,gEAA+B;AAC/B,2CAA8C;AAG9C,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAE3B,KAAK,UAAU,YAAY,CAChC,GAAgB,EAChB,GAAa,EACb,IAAkB;IAElB,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC;IAE7C,wDAAwD;IACxD,IAAI,KAAK,GAAkB,IAAI,CAAC;IAEhC,IAAI,UAAU,IAAI,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QACnD,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACnC,CAAC;SAA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AChE,SAAgB,qBAAqB,CACnC,GAAgB,EAChB,GAAa,EACb,IAAkB;IAElB,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;QACd,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,uBAAuB,EAAE,CAAC,CAAC;QACzE,OAAO;IACT,CAAC;IAED,MAAM,eAAe,GAAG,GAAG,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC;IAEnD,gDAAgD;IAChD,IACE,eAAe,CAAC,QAAQ,CAAC,gBAAgB,CAAC;QAC1C,eAAe,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAC5C,CAAC;QACD,IAAI,EAAE,CAAC;QACP,OAAO;IACT,CAAC;IAED,2CAA2C;IAC3C,MAAM,UAAU,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,IAAI,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IACpE,IAAI,GAAG,CAAC,IAAI,CAAC,UAAU,IAAI,GAAG,CAAC,IAAI,CAAC,UAAU,KAAK,UAAU,EAAE,CAAC;QAC9D,IAAI,EAAE,CAAC;QACP,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnB,OAAO,EAAE,KAAK;QACd,KAAK,EAAE,oCAAoC;KAC5C,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/middleware/auth.ts"],"names":[],"mappings":";;;;;AAOA,oCA2DC;AAED,8CAwBC;AAGD,sDAqCC;AAnID,gEAA+B;AAC/B,2CAA8C;AAG9C,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAE3B,KAAK,UAAU,YAAY,CAChC,GAAgB,EAChB,GAAa,EACb,IAAkB;IAElB,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,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AAE,oCAAoC;KAC5C,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/backend/dist/routes/meter.routes.d.ts.map b/backend/dist/routes/meter.routes.d.ts.map index 652d03cd..46f24108 100644 --- a/backend/dist/routes/meter.routes.d.ts.map +++ b/backend/dist/routes/meter.routes.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"meter.routes.d.ts","sourceRoot":"","sources":["../../src/routes/meter.routes.ts"],"names":[],"mappings":"AAIA,QAAA,MAAM,MAAM,4CAAW,CAAC;AAWxB,eAAe,MAAM,CAAC"} \ No newline at end of file +{"version":3,"file":"meter.routes.d.ts","sourceRoot":"","sources":["../../src/routes/meter.routes.ts"],"names":[],"mappings":"AAIA,QAAA,MAAM,MAAM,4CAAW,CAAC;AAoBxB,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/backend/dist/routes/meter.routes.js b/backend/dist/routes/meter.routes.js index 02479947..3a850995 100644 --- a/backend/dist/routes/meter.routes.js +++ b/backend/dist/routes/meter.routes.js @@ -44,5 +44,11 @@ router.get('/:meterId/readings', auth_js_1.authenticate, customerController.getM router.post('/:meterId/readings', auth_js_1.authenticate, (0, auth_js_1.requirePermission)('customers:update'), customerController.addMeterReading); router.put('/:meterId/readings/:readingId', auth_js_1.authenticate, (0, auth_js_1.requirePermission)('customers:update'), customerController.updateMeterReading); router.delete('/:meterId/readings/:readingId', auth_js_1.authenticate, (0, auth_js_1.requirePermission)('customers:delete'), customerController.deleteMeterReading); +// Status-Update (Zählerstand als übertragen markieren) +router.patch('/:meterId/readings/:readingId/transfer', auth_js_1.authenticate, (0, auth_js_1.requirePermission)('customers:update'), customerController.markReadingTransferred); +// Portal: Zählerstand melden (Kunde) +router.post('/:meterId/readings/report', auth_js_1.authenticate, customerController.reportMeterReading); +// Portal: Eigene Zähler laden +router.get('/my-meters', auth_js_1.authenticate, customerController.getMyMeters); exports.default = router; //# sourceMappingURL=meter.routes.js.map \ No newline at end of file diff --git a/backend/dist/routes/meter.routes.js.map b/backend/dist/routes/meter.routes.js.map index 50739c6a..ac2dae55 100644 --- a/backend/dist/routes/meter.routes.js.map +++ b/backend/dist/routes/meter.routes.js.map @@ -1 +1 @@ -{"version":3,"file":"meter.routes.js","sourceRoot":"","sources":["../../src/routes/meter.routes.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAiC;AACjC,0FAA4E;AAC5E,mDAA+F;AAE/F,MAAM,MAAM,GAAG,IAAA,gBAAM,GAAE,CAAC;AAExB,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,sBAAY,EAAE,IAAA,2BAAiB,EAAC,kBAAkB,CAAC,EAAE,kBAAkB,CAAC,WAAW,CAAC,CAAC;AACxG,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,sBAAY,EAAE,IAAA,2BAAiB,EAAC,kBAAkB,CAAC,EAAE,kBAAkB,CAAC,WAAW,CAAC,CAAC;AAE3G,iBAAiB;AACjB,MAAM,CAAC,GAAG,CAAC,oBAAoB,EAAE,sBAAY,EAAE,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;AACpF,MAAM,CAAC,IAAI,CAAC,oBAAoB,EAAE,sBAAY,EAAE,IAAA,2BAAiB,EAAC,kBAAkB,CAAC,EAAE,kBAAkB,CAAC,eAAe,CAAC,CAAC;AAC3H,MAAM,CAAC,GAAG,CAAC,+BAA+B,EAAE,sBAAY,EAAE,IAAA,2BAAiB,EAAC,kBAAkB,CAAC,EAAE,kBAAkB,CAAC,kBAAkB,CAAC,CAAC;AACxI,MAAM,CAAC,MAAM,CAAC,+BAA+B,EAAE,sBAAY,EAAE,IAAA,2BAAiB,EAAC,kBAAkB,CAAC,EAAE,kBAAkB,CAAC,kBAAkB,CAAC,CAAC;AAE3I,kBAAe,MAAM,CAAC"} \ No newline at end of file +{"version":3,"file":"meter.routes.js","sourceRoot":"","sources":["../../src/routes/meter.routes.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAEvE,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/backend/dist/services/appSetting.service.d.ts.map b/backend/dist/services/appSetting.service.d.ts.map index 9f1e347b..9baafe38 100644 --- a/backend/dist/services/appSetting.service.d.ts.map +++ b/backend/dist/services/appSetting.service.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"appSetting.service.d.ts","sourceRoot":"","sources":["../../src/services/appSetting.service.ts"],"names":[],"mappings":"AAaA,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAWpE;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAGlE;AAED,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM1E;AAED,wBAAsB,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAWtE;AAED,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAazE"} \ No newline at end of file +{"version":3,"file":"appSetting.service.d.ts","sourceRoot":"","sources":["../../src/services/appSetting.service.ts"],"names":[],"mappings":"AAgBA,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAWpE;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAGlE;AAED,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM1E;AAED,wBAAsB,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAWtE;AAED,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAazE"} \ No newline at end of file diff --git a/backend/dist/services/appSetting.service.js b/backend/dist/services/appSetting.service.js index 5e23aa16..e503436d 100644 --- a/backend/dist/services/appSetting.service.js +++ b/backend/dist/services/appSetting.service.js @@ -14,6 +14,9 @@ const DEFAULT_SETTINGS = { deadlineCriticalDays: '14', // Rot: Kritisch deadlineWarningDays: '42', // Gelb: Warnung (6 Wochen) deadlineOkDays: '90', // Grün: OK (3 Monate) + // Ausweis-Ablauf: Fristenschwellen (in Tagen) + documentExpiryCriticalDays: '30', // Rot: Kritisch (Standard 30 Tage) + documentExpiryWarningDays: '90', // Gelb: Warnung (Standard 90 Tage) }; async function getSetting(key) { const setting = await prisma.appSetting.findUnique({ diff --git a/backend/dist/services/appSetting.service.js.map b/backend/dist/services/appSetting.service.js.map index fda34b26..288459ad 100644 --- a/backend/dist/services/appSetting.service.js.map +++ b/backend/dist/services/appSetting.service.js.map @@ -1 +1 @@ -{"version":3,"file":"appSetting.service.js","sourceRoot":"","sources":["../../src/services/appSetting.service.ts"],"names":[],"mappings":";;AAaA,gCAWC;AAED,wCAGC;AAED,gCAMC;AAED,wCAWC;AAED,8CAaC;AAjED,2CAA8C;AAE9C,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAElC,mBAAmB;AACnB,MAAM,gBAAgB,GAA2B;IAC/C,6BAA6B,EAAE,OAAO;IACtC,gDAAgD;IAChD,oBAAoB,EAAE,IAAI,EAAO,gBAAgB;IACjD,mBAAmB,EAAE,IAAI,EAAQ,2BAA2B;IAC5D,cAAc,EAAE,IAAI,EAAa,sBAAsB;CACxD,CAAC;AAEK,KAAK,UAAU,UAAU,CAAC,GAAW;IAC1C,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC;QACjD,KAAK,EAAE,EAAE,GAAG,EAAE;KACf,CAAC,CAAC;IAEH,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,OAAO,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ChB,CAAC"} \ No newline at end of file +{"version":3,"file":"appSetting.service.js","sourceRoot":"","sources":["../../src/services/appSetting.service.ts"],"names":[],"mappings":";;AAgBA,gCAWC;AAED,wCAGC;AAED,gCAMC;AAED,wCAWC;AAED,8CAaC;AApED,2CAA8C;AAE9C,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAElC,mBAAmB;AACnB,MAAM,gBAAgB,GAA2B;IAC/C,6BAA6B,EAAE,OAAO;IACtC,gDAAgD;IAChD,oBAAoB,EAAE,IAAI,EAAO,gBAAgB;IACjD,mBAAmB,EAAE,IAAI,EAAQ,2BAA2B;IAC5D,cAAc,EAAE,IAAI,EAAa,sBAAsB;IACvD,8CAA8C;IAC9C,0BAA0B,EAAE,IAAI,EAAE,mCAAmC;IACrE,yBAAyB,EAAE,IAAI,EAAG,mCAAmC;CACtE,CAAC;AAEK,KAAK,UAAU,UAAU,CAAC,GAAW;IAC1C,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC;QACjD,KAAK,EAAE,EAAE,GAAG,EAAE;KACf,CAAC,CAAC;IAEH,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,OAAO,CAAC,KAAK,CAAC;IACvB,CAAC;IAED,2BAA2B;IAC3B,OAAO,gBAAgB,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;AACvC,CAAC;AAEM,KAAK,UAAU,cAAc,CAAC,GAAW;IAC9C,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,KAAK,KAAK,MAAM,CAAC;AAC1B,CAAC;AAEM,KAAK,UAAU,UAAU,CAAC,GAAW,EAAE,KAAa;IACzD,MAAM,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC;QAC7B,KAAK,EAAE,EAAE,GAAG,EAAE;QACd,MAAM,EAAE,EAAE,KAAK,EAAE;QACjB,MAAM,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE;KACvB,CAAC,CAAC;AACL,CAAC;AAEM,KAAK,UAAU,cAAc;IAClC,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;IAEpD,wDAAwD;IACxD,MAAM,MAAM,GAAG,EAAE,GAAG,gBAAgB,EAAE,CAAC;IAEvC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC;IACtC,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAEM,KAAK,UAAU,iBAAiB;IACrC,qFAAqF;IACrF,MAAM,UAAU,GAAG,CAAC,+BAA+B,CAAC,CAAC;IACrD,MAAM,WAAW,GAAG,MAAM,cAAc,EAAE,CAAC;IAE3C,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAC7B,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC;YACvB,MAAM,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"} \ No newline at end of file diff --git a/backend/dist/services/auth.service.d.ts b/backend/dist/services/auth.service.d.ts index 3e146ab8..1fc51e25 100644 --- a/backend/dist/services/auth.service.d.ts +++ b/backend/dist/services/auth.service.d.ts @@ -53,6 +53,9 @@ export declare function getUserById(id: number): Promise<{ lastName: string; isActive: boolean; customerId: number | null; + whatsappNumber: string | null; + telegramUsername: string | null; + signalNumber: string | null; roles: string[]; permissions: string[]; isCustomerPortal: boolean; diff --git a/backend/dist/services/auth.service.d.ts.map b/backend/dist/services/auth.service.d.ts.map index a9543c22..60025e70 100644 --- a/backend/dist/services/auth.service.d.ts.map +++ b/backend/dist/services/auth.service.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"auth.service.d.ts","sourceRoot":"","sources":["../../src/services/auth.service.ts"],"names":[],"mappings":"AASA,wBAAsB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;;;;;;;;;;;GA+D1D;AAGD,wBAAsB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;GAwFlE;AAGD,wBAAsB,yBAAyB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,iBAiBnF;AAGD,wBAAsB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgB1F;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;;;;;;GA8BA;AAED,wBAAsB,WAAW,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;UA8C3C;AAGD,wBAAsB,qBAAqB,CAAC,UAAU,EAAE,MAAM;;;;;;;;;;;;;;;;;UA+C7D"} \ No newline at end of file +{"version":3,"file":"auth.service.d.ts","sourceRoot":"","sources":["../../src/services/auth.service.ts"],"names":[],"mappings":"AASA,wBAAsB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;;;;;;;;;;;GA+D1D;AAGD,wBAAsB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;GAwFlE;AAGD,wBAAsB,yBAAyB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,iBAiBnF;AAGD,wBAAsB,yBAAyB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAgB1F;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;;;;;;GA8BA;AAED,wBAAsB,WAAW,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;UAiD3C;AAGD,wBAAsB,qBAAqB,CAAC,UAAU,EAAE,MAAM;;;;;;;;;;;;;;;;;UA+C7D"} \ No newline at end of file diff --git a/backend/dist/services/auth.service.js b/backend/dist/services/auth.service.js index c86602e9..99efbca6 100644 --- a/backend/dist/services/auth.service.js +++ b/backend/dist/services/auth.service.js @@ -246,6 +246,9 @@ async function getUserById(id) { lastName: user.lastName, isActive: user.isActive, customerId: user.customerId, + whatsappNumber: user.whatsappNumber, + telegramUsername: user.telegramUsername, + signalNumber: user.signalNumber, roles: user.roles.map((ur) => ur.role.name), permissions: Array.from(permissions), isCustomerPortal: false, diff --git a/backend/dist/services/auth.service.js.map b/backend/dist/services/auth.service.js.map index 3e279219..c5427192 100644 --- a/backend/dist/services/auth.service.js.map +++ b/backend/dist/services/auth.service.js.map @@ -1 +1 @@ -{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../src/services/auth.service.ts"],"names":[],"mappings":";;;;;AASA,sBA+DC;AAGD,sCAwFC;AAGD,8DAiBC;AAGD,8DAgBC;AAED,gCAqCC;AAED,kCA8CC;AAGD,sDA+CC;AAnVD,2CAA8C;AAC9C,wDAA8B;AAC9B,gEAA+B;AAE/B,0DAA0D;AAE1D,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAElC,oBAAoB;AACb,KAAK,UAAU,KAAK,CAAC,KAAa,EAAE,QAAgB;IACzD,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC;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7094a74a..edffbd98 100644 --- a/backend/dist/services/contract.service.d.ts +++ b/backend/dist/services/contract.service.d.ts @@ -157,6 +157,7 @@ export declare function getContractById(id: number, decryptPassword?: boolean): createdAt: Date; updatedAt: Date; customerNumber: string; + consentHash: string | null; portalEmail: string | null; type: import(".prisma/client").$Enums.CustomerType; salutation: string | null; @@ -235,6 +236,10 @@ export declare function getContractById(id: number, decryptPassword?: boolean): readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }[]; } & { @@ -424,6 +429,10 @@ export declare function getContractById(id: number, decryptPassword?: boolean): readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }[]; } & { @@ -742,6 +751,7 @@ export declare function createContract(data: ContractCreateData): Promise<{ createdAt: Date; updatedAt: Date; customerNumber: string; + consentHash: string | null; portalEmail: string | null; type: import(".prisma/client").$Enums.CustomerType; salutation: string | null; @@ -934,6 +944,7 @@ export declare function updateContract(id: number, data: Partial + const grantedConsentsMap = new Map(); + for (const c of allConsents) { + if (!grantedConsentsMap.has(c.customerId)) { + grantedConsentsMap.set(c.customerId, new Set()); + } + grantedConsentsMap.get(c.customerId).add(c.consentType); + } + // Widerrufene Consents laden + const withdrawnConsents = await prisma.customerConsent.findMany({ + where: { status: 'WITHDRAWN' }, + select: { customerId: true, consentType: true }, + }); + const withdrawnConsentsMap = new Map(); + for (const c of withdrawnConsents) { + if (!withdrawnConsentsMap.has(c.customerId)) { + withdrawnConsentsMap.set(c.customerId, new Set()); + } + withdrawnConsentsMap.get(c.customerId).add(c.consentType); + } + // Track welche Kunden bereits eine Consent-Warnung bekommen haben (nur einmal pro Kunde) + const customerConsentWarned = new Set(); for (const contract of contracts) { const issues = []; // SNOOZE-LOGIK: Prüfen ob Snooze aktiv ist (für Fristen-Unterdrückung) @@ -349,16 +379,41 @@ async function getCockpitData() { }); summary.byCategory.missingData++; } - // 7b. KEIN AUSWEIS (für DSL, FIBER, CABLE, MOBILE ist dies ein kritisches Problem) - if (!contract.identityDocumentId) { + // 7b. KEIN AUSWEIS (nur für Telekommunikationsprodukte relevant) + const requiresIdentityDocument = ['DSL', 'FIBER', 'CABLE', 'MOBILE'].includes(contract.type); + if (requiresIdentityDocument && !contract.identityDocumentId) { issues.push({ type: 'missing_identity_document', label: 'Ausweis fehlt', - urgency: requiresBankAndId ? 'critical' : 'warning', + urgency: 'critical', details: 'Kein Ausweisdokument verknüpft', }); summary.byCategory.missingData++; } + // 7c. AUSWEIS LÄUFT AB (nur aktive Ausweise prüfen) + if (contract.identityDocument && contract.identityDocument.isActive && contract.identityDocument.expiryDate) { + const expiryDate = new Date(contract.identityDocument.expiryDate); + const today = new Date(); + const daysUntilExpiry = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); + if (daysUntilExpiry < 0) { + issues.push({ + type: 'identity_document_expired', + label: 'Ausweis abgelaufen', + urgency: 'critical', + details: `Ausweis seit ${Math.abs(daysUntilExpiry)} Tagen abgelaufen (${expiryDate.toLocaleDateString('de-DE')})`, + }); + summary.byCategory.missingData++; + } + else if (daysUntilExpiry <= docExpiryWarningDays) { + issues.push({ + type: 'identity_document_expiring', + label: 'Ausweis läuft ab', + urgency: daysUntilExpiry <= docExpiryCriticalDays ? 'critical' : 'warning', + details: `Ausweis läuft in ${daysUntilExpiry} Tagen ab (${expiryDate.toLocaleDateString('de-DE')})`, + }); + summary.byCategory.cancellationDeadlines++; + } + } // 8. ENERGIE-SPEZIFISCH: KEIN ZÄHLER if (['ELECTRICITY', 'GAS'].includes(contract.type) && contract.energyDetails) { if (!contract.energyDetails.meterId) { @@ -475,6 +530,35 @@ async function getCockpitData() { } } } + // #14 - Consent-Prüfung (nur für aktive Verträge, einmal pro Kunde) + if (['ACTIVE', 'PENDING', 'DRAFT'].includes(contract.status) && !customerConsentWarned.has(contract.customer.id)) { + const granted = grantedConsentsMap.get(contract.customer.id); + const withdrawn = withdrawnConsentsMap.get(contract.customer.id); + const requiredTypes = ['DATA_PROCESSING', 'MARKETING_EMAIL', 'MARKETING_PHONE', 'DATA_SHARING_PARTNER']; + if (withdrawn && withdrawn.size > 0) { + // Mindestens eine Einwilligung widerrufen + issues.push({ + type: 'consent_withdrawn', + label: 'Einwilligung widerrufen', + urgency: 'critical', + details: `${withdrawn.size} Einwilligung(en) widerrufen`, + }); + summary.byCategory.missingConsents++; + customerConsentWarned.add(contract.customer.id); + } + else if (!granted || granted.size < requiredTypes.length) { + // Nicht alle 4 Einwilligungen erteilt + const missing = requiredTypes.length - (granted?.size || 0); + issues.push({ + type: 'missing_consents', + label: 'Fehlende Einwilligungen', + urgency: 'critical', + details: `${missing} von ${requiredTypes.length} Einwilligungen fehlen`, + }); + summary.byCategory.missingConsents++; + customerConsentWarned.add(contract.customer.id); + } + } // Nur Verträge mit Issues hinzufügen if (issues.length > 0) { const highestUrgency = getHighestUrgency(issues); @@ -523,8 +607,14 @@ async function getCockpitData() { }; return urgencyOrder[a.highestUrgency] - urgencyOrder[b.highestUrgency]; }); + // Vertragsunabhängige Ausweis-Warnungen + const documentAlerts = await getDocumentExpiryAlerts(docExpiryCriticalDays, docExpiryWarningDays); + // Gemeldete Zählerstände (REPORTED Status) + const reportedReadings = await getReportedMeterReadings(); return { contracts: cockpitContracts, + documentAlerts, + reportedReadings, summary, thresholds: { criticalDays, @@ -533,4 +623,106 @@ async function getCockpitData() { }, }; } +/** + * Alle aktiven Ausweise die ablaufen oder abgelaufen sind (vertragsunabhängig) + */ +async function getDocumentExpiryAlerts(criticalDays, warningDays) { + const now = new Date(); + const inWarningDays = new Date(now.getTime() + warningDays * 24 * 60 * 60 * 1000); + const documents = await prisma.identityDocument.findMany({ + where: { + isActive: true, + expiryDate: { lte: inWarningDays }, + }, + include: { + customer: { + select: { id: true, customerNumber: true, firstName: true, lastName: true }, + }, + }, + orderBy: { expiryDate: 'asc' }, + }); + return documents.map((doc) => { + const expiryDate = new Date(doc.expiryDate); + const daysUntilExpiry = Math.ceil((expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)); + let urgency = 'warning'; + if (daysUntilExpiry < 0) + urgency = 'critical'; + else if (daysUntilExpiry <= criticalDays) + urgency = 'critical'; + return { + id: doc.id, + type: doc.type, + documentNumber: doc.documentNumber, + expiryDate: expiryDate.toISOString(), + daysUntilExpiry, + urgency, + customer: { + id: doc.customer.id, + customerNumber: doc.customer.customerNumber, + name: `${doc.customer.firstName} ${doc.customer.lastName}`, + }, + }; + }); +} +/** + * Vom Kunden gemeldete Zählerstände die noch nicht übertragen wurden + */ +async function getReportedMeterReadings() { + const readings = await prisma.meterReading.findMany({ + where: { status: 'REPORTED' }, + include: { + meter: { + include: { + customer: { + select: { id: true, customerNumber: true, firstName: true, lastName: true }, + }, + // Energie-Verträge für diesen Zähler (um Provider-Portal-Daten zu bekommen) + energyDetails: { + include: { + contract: { + select: { + id: true, + portalUsername: true, + provider: { + select: { id: true, name: true, portalUrl: true }, + }, + }, + }, + }, + take: 1, + }, + }, + }, + }, + orderBy: { createdAt: 'asc' }, + }); + return readings.map((r) => { + const contract = r.meter.energyDetails?.[0]?.contract; + const provider = contract?.provider; + return { + id: r.id, + readingDate: r.readingDate.toISOString(), + value: r.value, + unit: r.unit, + notes: r.notes ?? undefined, + reportedBy: r.reportedBy ?? undefined, + createdAt: r.createdAt.toISOString(), + meter: { + id: r.meter.id, + meterNumber: r.meter.meterNumber, + type: r.meter.type, + }, + customer: { + id: r.meter.customer.id, + customerNumber: r.meter.customer.customerNumber, + name: `${r.meter.customer.firstName} ${r.meter.customer.lastName}`, + }, + providerPortal: provider?.portalUrl ? { + providerName: provider.name, + portalUrl: provider.portalUrl, + portalUsername: contract?.portalUsername ?? undefined, + } : undefined, + }; + }); +} //# sourceMappingURL=contractCockpit.service.js.map \ No newline at end of file diff --git a/backend/dist/services/contractCockpit.service.js.map b/backend/dist/services/contractCockpit.service.js.map index 66c42ae8..8161230d 100644 --- a/backend/dist/services/contractCockpit.service.js.map +++ b/backend/dist/services/contractCockpit.service.js.map @@ -1 +1 @@ -{"version":3,"file":"contractCockpit.service.js","sourceRoot":"","sources":["../../src/services/contractCockpit.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA,wCAodC;AA/lBD,2CACwB;AACxB,2EAA6D;AAE7D,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAgElC,mDAAmD;AACnD,SAAS,SAAS,CAAC,IAA6B;IAC9C,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IACvB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACzB,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC5B,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC;IAC9C,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAED,uDAAuD;AACvD,SAAS,gBAAgB,CACvB,aAA4B,EAC5B,YAAoB,EACpB,WAAmB,EACnB,MAAc;IAEd,IAAI,aAAa,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAC1C,IAAI,aAAa,GAAG,CAAC;QAAE,OAAO,UAAU,CAAC,CAAC,qBAAqB;IAC/D,IAAI,aAAa,IAAI,YAAY;QAAE,OAAO,UAAU,CAAC;IACrD,IAAI,aAAa,IAAI,WAAW;QAAE,OAAO,SAAS,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ACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"contractCockpit.service.js","sourceRoot":"","sources":["../../src/services/contractCockpit.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsLA,wCAsjBC;AA5uBD,2CACwB;AACxB,2EAA6D;AAE7D,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AA2GlC,mDAAmD;AACnD,SAAS,SAAS,CAAC,IAA6B;IAC9C,IAAI,CAAC,IAAI;QAAE,OAAO,IAAI,CAAC;IACvB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACzB,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC5B,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC;IAC9C,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAED,uDAAuD;AACvD,SAAS,gBAAgB,CACvB,aAA4B,EAC5B,YAAoB,EACpB,WAAmB,EACnB,MAAc;IAEd,IAAI,aAAa,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAC1C,IAAI,aAAa,GAAG,CAAC;QAAE,OAAO,UAAU,CAAC,CAAC,qBAAqB;IAC/D,IAAI,aAAa,IAAI,YAAY;QAAE,OAAO,UAAU,CAAC;IACrD,IAAI,aAAa,IAAI,WAAW;QAAE,OAAO,SAAS,CAAC;IACnD,IAAI,aAAa,IAAI,MAAM;QAAE,OAAO,IAAI,CAAC;IACzC,OAAO,MAAM,CAAC;AACh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AAC,KAAK,CAAC,IAAI;aACnB;YACD,QAAQ,EAAE;gBACR,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE;gBACvB,cAAc,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,cAAc;gBAC/C,IAAI,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,SAAS,IAAI,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE;aACnE;YACD,cAAc,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,CAAC;gBACpC,YAAY,EAAE,QAAQ,CAAC,IAAI;gBAC3B,SAAS,EAAE,QAAQ,CAAC,SAAS;gBAC7B,cAAc,EAAE,QAAQ,EAAE,cAAc,IAAI,SAAS;aACtD,CAAC,CAAC,CAAC,SAAS;SACd,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/backend/dist/services/contractTask.service.d.ts b/backend/dist/services/contractTask.service.d.ts index 9f4d920f..f62dfcd2 100644 --- a/backend/dist/services/contractTask.service.d.ts +++ b/backend/dist/services/contractTask.service.d.ts @@ -11,8 +11,8 @@ export declare function getTasksByContract(filters: ContractTaskFilters): Promis createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }[]; @@ -23,9 +23,9 @@ export declare function getTasksByContract(filters: ContractTaskFilters): Promis description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; })[]>; export declare function getTaskById(id: number): Promise<{ @@ -35,9 +35,9 @@ export declare function getTaskById(id: number): Promise<{ description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; } | null>; export declare function createTask(data: { @@ -53,9 +53,9 @@ export declare function createTask(data: { description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; }>; export declare function updateTask(id: number, data: { @@ -69,9 +69,9 @@ export declare function updateTask(id: number, data: { description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; }>; export declare function completeTask(id: number): Promise<{ @@ -81,9 +81,9 @@ export declare function completeTask(id: number): Promise<{ description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; }>; export declare function reopenTask(id: number): Promise<{ @@ -93,9 +93,9 @@ export declare function reopenTask(id: number): Promise<{ description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; }>; export declare function deleteTask(id: number): Promise<{ @@ -105,9 +105,9 @@ export declare function deleteTask(id: number): Promise<{ description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; }>; export declare function createSubtask(data: { @@ -119,8 +119,8 @@ export declare function createSubtask(data: { createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }>; @@ -131,8 +131,8 @@ export declare function updateSubtask(id: number, data: { createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }>; @@ -141,8 +141,8 @@ export declare function completeSubtask(id: number): Promise<{ createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }>; @@ -151,8 +151,8 @@ export declare function reopenSubtask(id: number): Promise<{ createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }>; @@ -161,8 +161,8 @@ export declare function deleteSubtask(id: number): Promise<{ createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }>; @@ -174,9 +174,9 @@ export declare function getSubtaskById(id: number): Promise<({ description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; }; } & { @@ -184,8 +184,8 @@ export declare function getSubtaskById(id: number): Promise<({ createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }) | null>; @@ -223,8 +223,8 @@ export declare function getAllTasks(filters: AllTasksFilters): Promise<({ createdAt: Date; updatedAt: Date; status: import(".prisma/client").$Enums.ContractTaskStatus; - title: string; createdBy: string | null; + title: string; completedAt: Date | null; taskId: number; }[]; @@ -235,9 +235,9 @@ export declare function getAllTasks(filters: AllTasksFilters): Promise<({ description: string | null; status: import(".prisma/client").$Enums.ContractTaskStatus; contractId: number; + createdBy: string | null; title: string; visibleInPortal: boolean; - createdBy: string | null; completedAt: Date | null; })[]>; export declare function getTaskStats(filters: AllTasksFilters): Promise<{ diff --git a/backend/dist/services/customer.service.d.ts b/backend/dist/services/customer.service.d.ts index 0a307746..b5e8ecd0 100644 --- a/backend/dist/services/customer.service.d.ts +++ b/backend/dist/services/customer.service.d.ts @@ -31,6 +31,7 @@ export declare function getAllCustomers(filters: CustomerFilters): Promise<{ createdAt: Date; updatedAt: Date; customerNumber: string; + consentHash: string | null; portalEmail: string | null; type: import(".prisma/client").$Enums.CustomerType; salutation: string | null; @@ -108,6 +109,10 @@ export declare function getCustomerById(id: number): Promise<({ readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }[]; } & { @@ -210,6 +215,7 @@ export declare function getCustomerById(id: number): Promise<({ createdAt: Date; updatedAt: Date; customerNumber: string; + consentHash: string | null; portalEmail: string | null; type: import(".prisma/client").$Enums.CustomerType; salutation: string | null; @@ -257,6 +263,7 @@ export declare function createCustomer(data: { createdAt: Date; updatedAt: Date; customerNumber: string; + consentHash: string | null; portalEmail: string | null; type: import(".prisma/client").$Enums.CustomerType; salutation: string | null; @@ -300,6 +307,7 @@ export declare function updateCustomer(id: number, data: { createdAt: Date; updatedAt: Date; customerNumber: string; + consentHash: string | null; portalEmail: string | null; type: import(".prisma/client").$Enums.CustomerType; salutation: string | null; @@ -328,6 +336,7 @@ export declare function deleteCustomer(id: number): Promise<{ createdAt: Date; updatedAt: Date; customerNumber: string; + consentHash: string | null; portalEmail: string | null; type: import(".prisma/client").$Enums.CustomerType; salutation: string | null; @@ -566,6 +575,10 @@ export declare function getCustomerMeters(customerId: number, showInactive?: boo readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }[]; } & { @@ -629,6 +642,10 @@ export declare function addMeterReading(meterId: number, data: { readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }>; export declare function getMeterReadings(meterId: number): Promise<{ @@ -638,6 +655,10 @@ export declare function getMeterReadings(meterId: number): Promise<{ readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }[]>; export declare function updateMeterReading(meterId: number, readingId: number, data: { @@ -652,6 +673,10 @@ export declare function updateMeterReading(meterId: number, readingId: number, d readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }>; export declare function deleteMeterReading(meterId: number, readingId: number): Promise<{ @@ -661,6 +686,10 @@ export declare function deleteMeterReading(meterId: number, readingId: number): readingDate: Date; value: number; unit: string; + reportedBy: string | null; + status: import(".prisma/client").$Enums.MeterReadingStatus; + transferredAt: Date | null; + transferredBy: string | null; meterId: number; }>; export declare function updatePortalSettings(customerId: number, data: { diff --git a/backend/dist/services/customer.service.d.ts.map b/backend/dist/services/customer.service.d.ts.map index f743077c..b53c38b6 100644 --- a/backend/dist/services/customer.service.d.ts.map +++ b/backend/dist/services/customer.service.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"customer.service.d.ts","sourceRoot":"","sources":["../../src/services/customer.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,YAAY,EAAkB,MAAM,gBAAgB,CAAC;AAoB5E,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,YAAY,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,eAAe,CAAC,OAAO,EAAE,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwC7D;AAED,wBAAsB,eAAe,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WA6B/C;AAED,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE;;;KAQpD;AAED,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,IAA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B,CACxC,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE;IACJ,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;;;;;GAgBF;AAED,wBAAsB,iBAAiB,CAAC,UAAU,EAAE,MAAM;;;;;;UAWzD;AAID,wBAAsB,0BAA0B,CAAC,UAAU,EAAE,MAAM;;;;;;;;;;;;;;;;;MAkBlE;AAED,wBAAsB,oBAAoB,CAAC,UAAU,EAAE,MAAM;;;;;;;;;;;;;;;;;MAkB5D;AAED,wBAAsB,iBAAiB,CACrC,UAAU,EAAE,MAAM,EAAE,sDAAsD;AAC1E,gBAAgB,EAAE,MAAM,EAAE,+BAA+B;AACzD,KAAK,CAAC,EAAE,MAAM;;;;;;;;;;;;;;;;;GAkDf;AAED,wBAAsB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM;;;;;;;;GAQtF;AAED,wBAAsB,gCAAgC,CAAC,MAAM,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM;;;;;;;KAwB/F"} \ No newline at end of file +{"version":3,"file":"customer.service.d.ts","sourceRoot":"","sources":["../../src/services/customer.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,YAAY,EAAkB,MAAM,gBAAgB,CAAC;AAoB5E,MAAM,WAAW,eAAe;IAC9B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,YAAY,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,eAAe,CAAC,OAAO,EAAE,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwC7D;AAED,wBAAsB,eAAe,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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EAAE;IACJ,WAAW,CAAC,EAAE,IAAI,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;;;;;;;;;;;;GAeF;AAED,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;;;;;;;;;;;;GAa1E;AAID,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE;IACJ,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;;;;;GAgBF;AAED,wBAAsB,iBAAiB,CAAC,UAAU,EAAE,MAAM;;;;;;UAWzD;AAID,wBAAsB,0BAA0B,CAAC,UAAU,EAAE,MAAM;;;;;;;;;;;;;;;;;MAkBlE;AAED,wBAAsB,oBAAoB,CAAC,UAAU,EAAE,MAAM;;;;;;;;;;;;;;;;;MAkB5D;AAED,wBAAsB,iBAAiB,CACrC,UAAU,EAAE,MAAM,EAAE,sDAAsD;AAC1E,gBAAgB,EAAE,MAAM,EAAE,+BAA+B;AACzD,KAAK,CAAC,EAAE,MAAM;;;;;;;;;;;;;;;;;GAkDf;AAED,wBAAsB,oBAAoB,CAAC,UAAU,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM;;;;;;;;GAQtF;AAED,wBAAsB,gCAAgC,CAAC,MAAM,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM;;;;;;;KAwB/F"} \ No newline at end of file diff --git a/backend/dist/services/emailProvider/emailProviderService.d.ts b/backend/dist/services/emailProvider/emailProviderService.d.ts index dfd43f1e..dea9a219 100644 --- a/backend/dist/services/emailProvider/emailProviderService.d.ts +++ b/backend/dist/services/emailProvider/emailProviderService.d.ts @@ -20,6 +20,8 @@ export declare function getAllProviderConfigs(): Promise<{ imapEncryption: import(".prisma/client").$Enums.MailEncryption; smtpEncryption: import(".prisma/client").$Enums.MailEncryption; allowSelfSignedCerts: boolean; + systemEmailAddress: string | null; + systemEmailPasswordEncrypted: string | null; }[]>; export declare function getProviderConfigById(id: number): Promise<{ id: number; @@ -42,6 +44,8 @@ export declare function getProviderConfigById(id: number): Promise<{ imapEncryption: import(".prisma/client").$Enums.MailEncryption; smtpEncryption: import(".prisma/client").$Enums.MailEncryption; allowSelfSignedCerts: boolean; + systemEmailAddress: string | null; + systemEmailPasswordEncrypted: string | null; } | null>; export declare function getDefaultProviderConfig(): Promise<{ id: number; @@ -64,6 +68,8 @@ export declare function getDefaultProviderConfig(): Promise<{ imapEncryption: import(".prisma/client").$Enums.MailEncryption; smtpEncryption: import(".prisma/client").$Enums.MailEncryption; allowSelfSignedCerts: boolean; + systemEmailAddress: string | null; + systemEmailPasswordEncrypted: string | null; } | null>; export declare function getActiveProviderConfig(): Promise<{ id: number; @@ -86,6 +92,8 @@ export declare function getActiveProviderConfig(): Promise<{ imapEncryption: import(".prisma/client").$Enums.MailEncryption; smtpEncryption: import(".prisma/client").$Enums.MailEncryption; allowSelfSignedCerts: boolean; + systemEmailAddress: string | null; + systemEmailPasswordEncrypted: string | null; } | null>; export interface CreateProviderConfigData { name: string; @@ -99,6 +107,8 @@ export interface CreateProviderConfigData { imapEncryption?: MailEncryption; smtpEncryption?: MailEncryption; allowSelfSignedCerts?: boolean; + systemEmailAddress?: string; + systemEmailPassword?: string; isActive?: boolean; isDefault?: boolean; } @@ -123,6 +133,8 @@ export declare function createProviderConfig(data: CreateProviderConfigData): Pr imapEncryption: import(".prisma/client").$Enums.MailEncryption; smtpEncryption: import(".prisma/client").$Enums.MailEncryption; allowSelfSignedCerts: boolean; + systemEmailAddress: string | null; + systemEmailPasswordEncrypted: string | null; }>; export declare function updateProviderConfig(id: number, data: Partial): Promise<{ id: number; @@ -145,6 +157,8 @@ export declare function updateProviderConfig(id: number, data: Partial; export declare function deleteProviderConfig(id: number): Promise<{ id: number; @@ -167,6 +181,8 @@ export declare function deleteProviderConfig(id: number): Promise<{ imapEncryption: import(".prisma/client").$Enums.MailEncryption; smtpEncryption: import(".prisma/client").$Enums.MailEncryption; allowSelfSignedCerts: boolean; + systemEmailAddress: string | null; + systemEmailPasswordEncrypted: string | null; }>; export declare function checkEmailExists(localPart: string): Promise; export declare function provisionEmail(localPart: string, customerEmail: string): Promise; @@ -200,4 +216,17 @@ export declare function testProviderConnection(options?: { domain: string; }; }): Promise; +export interface SystemEmailCredentials { + emailAddress: string; + password: string; + smtpServer: string; + smtpPort: number; + smtpEncryption: MailEncryption; + allowSelfSignedCerts: boolean; +} +/** + * System-E-Mail-Credentials vom aktiven Provider holen. + * Wird für automatisierten Versand (DSGVO, Benachrichtigungen etc.) verwendet. + */ +export declare function getSystemEmailCredentials(): Promise; //# sourceMappingURL=emailProviderService.d.ts.map \ No newline at end of file diff --git a/backend/dist/services/emailProvider/emailProviderService.d.ts.map b/backend/dist/services/emailProvider/emailProviderService.d.ts.map index 8163bbe3..e9d55492 100644 --- a/backend/dist/services/emailProvider/emailProviderService.d.ts.map +++ b/backend/dist/services/emailProvider/emailProviderService.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"emailProviderService.d.ts","sourceRoot":"","sources":["../../../src/services/emailProvider/emailProviderService.ts"],"names":[],"mappings":"AAIA,OAAO,EAGL,iBAAiB,EACjB,oBAAoB,EAEpB,cAAc,EACf,MAAM,YAAY,CAAC;AAuBpB,wBAAsB,qBAAqB;;;;;;;;;;;;;;;;;;;;;KAI1C;AAED,wBAAsB,qBAAqB,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;UAIrD;AAED,wBAAsB,wBAAwB;;;;;;;;;;;;;;;;;;;;;UAI7C;AAED,wBAAsB,uBAAuB;;;;;;;;;;;;;;;;;;;;;UAQ5C;AAED,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,aAAa,CAAC;IACzC,MA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AAM,GACf,OAAO,CAAC,oBAAoB,CAAC,CAiB/B;AAGD,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,cAAc,CAAC;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,cAAc,CAAC;IAC/B,oBAAoB,EAAE,OAAO,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CA0D5E;AAGD,wBAAsB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAWvF;AAGD,wBAAsB,sBAAsB,CAC1C,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,oBAAoB,CAAC,CAW/B;AAGD,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAGhE;AAqED,wBAAsB,sBAAsB,CAAC,OAAO,CAAC,EAAE;IACrD,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE;QACT,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,aAAa,CAAC;QACzC,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;CACH,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA6BhC"} \ No newline at end of file +{"version":3,"file":"emailProviderService.d.ts","sourceRoot":"","sources":["../../../src/services/emailProvider/emailProviderService.ts"],"names":[],"mappings":"AAIA,OAAO,EAGL,iBAAiB,EACjB,oBAAoB,EAEpB,cAAc,EACf,MAAM,YAAY,C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C,EAAE;QACT,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,aAAa,CAAC;QACzC,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;CACH,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA6BhC;AAID,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,cAAc,CAAC;IAC/B,oBAAoB,EAAE,OAAO,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC,CAyBxF"} \ No newline at end of file diff --git a/backend/dist/services/emailProvider/emailProviderService.js b/backend/dist/services/emailProvider/emailProviderService.js index 91c46ad0..03b8a9e1 100644 --- a/backend/dist/services/emailProvider/emailProviderService.js +++ b/backend/dist/services/emailProvider/emailProviderService.js @@ -18,6 +18,7 @@ exports.deprovisionEmail = deprovisionEmail; exports.renameProvisionedEmail = renameProvisionedEmail; exports.getProviderDomain = getProviderDomain; exports.testProviderConnection = testProviderConnection; +exports.getSystemEmailCredentials = getSystemEmailCredentials; const client_1 = require("@prisma/client"); const encryption_js_1 = require("../../utils/encryption.js"); const pleskProvider_js_1 = require("./pleskProvider.js"); @@ -70,9 +71,10 @@ async function createProviderConfig(data) { data: { isDefault: false }, }); } - // Passwort verschlüsseln falls vorhanden + // Passwörter verschlüsseln falls vorhanden const { encrypt } = await import('../../utils/encryption.js'); const passwordEncrypted = data.password ? encrypt(data.password) : null; + const systemEmailPasswordEncrypted = data.systemEmailPassword ? encrypt(data.systemEmailPassword) : null; return prisma.emailProviderConfig.create({ data: { name: data.name, @@ -86,6 +88,8 @@ async function createProviderConfig(data) { imapEncryption: data.imapEncryption ?? 'SSL', smtpEncryption: data.smtpEncryption ?? 'SSL', allowSelfSignedCerts: data.allowSelfSignedCerts ?? false, + systemEmailAddress: data.systemEmailAddress || null, + systemEmailPasswordEncrypted, isActive: data.isActive ?? true, isDefault: data.isDefault ?? false, }, @@ -120,21 +124,31 @@ async function updateProviderConfig(id, data) { updateData.smtpEncryption = data.smtpEncryption; if (data.allowSelfSignedCerts !== undefined) updateData.allowSelfSignedCerts = data.allowSelfSignedCerts; + if (data.systemEmailAddress !== undefined) + updateData.systemEmailAddress = data.systemEmailAddress || null; if (data.isActive !== undefined) updateData.isActive = data.isActive; if (data.isDefault !== undefined) updateData.isDefault = data.isDefault; + const { encrypt } = await import('../../utils/encryption.js'); // Passwort-Logik: // - Wenn neues Passwort übergeben → verschlüsseln und speichern // - Wenn Benutzername gelöscht wird → Passwort auch löschen (gehören zusammen) if (data.password) { - const { encrypt } = await import('../../utils/encryption.js'); updateData.passwordEncrypted = encrypt(data.password); } else if (data.username !== undefined && !data.username) { // Benutzername wird gelöscht → Passwort auch löschen updateData.passwordEncrypted = null; } + // System-E-Mail-Passwort + if (data.systemEmailPassword) { + updateData.systemEmailPasswordEncrypted = encrypt(data.systemEmailPassword); + } + else if (data.systemEmailAddress !== undefined && !data.systemEmailAddress) { + // System-E-Mail wird gelöscht → Passwort auch löschen + updateData.systemEmailPasswordEncrypted = null; + } return prisma.emailProviderConfig.update({ where: { id }, data: updateData, @@ -477,4 +491,33 @@ async function testProviderConnection(options) { }; } } +/** + * System-E-Mail-Credentials vom aktiven Provider holen. + * Wird für automatisierten Versand (DSGVO, Benachrichtigungen etc.) verwendet. + */ +async function getSystemEmailCredentials() { + const config = await getActiveProviderConfig(); + if (!config?.systemEmailAddress || !config?.systemEmailPasswordEncrypted) { + return null; + } + let password; + try { + password = (0, encryption_js_1.decrypt)(config.systemEmailPasswordEncrypted); + } + catch { + console.error('System-E-Mail-Passwort konnte nicht entschlüsselt werden'); + return null; + } + const settings = await getImapSmtpSettings(); + if (!settings) + return null; + return { + emailAddress: config.systemEmailAddress, + password, + smtpServer: settings.smtpServer, + smtpPort: settings.smtpPort, + smtpEncryption: settings.smtpEncryption, + allowSelfSignedCerts: settings.allowSelfSignedCerts, + }; +} //# sourceMappingURL=emailProviderService.js.map \ No newline at end of file diff --git a/backend/dist/services/emailProvider/emailProviderService.js.map b/backend/dist/services/emailProvider/emailProviderService.js.map index 2bf98cb5..81ab509b 100644 --- a/backend/dist/services/emailProvider/emailProviderService.js.map +++ b/backend/dist/services/emailProvider/emailProviderService.js.map @@ -1 +1 @@ -{"version":3,"file":"emailProviderService.js","sourceRoot":"","sources":["../../../src/services/emailProvider/emailProviderService.ts"],"names":[],"mappings":";AAAA,mEAAmE;;AAkCnE,sDAIC;AAED,sDAIC;AAED,4DAIC;AAED,0DAQC;AAmBD,oDA8BC;AAED,oDA2CC;AAED,oDAIC;AA+CD,4CAQC;AAGD,wCAuCC;AAGD,8DA0CC;AAGD,sEAoBC;AAGD,sDAoBC;AAcD,kDA0DC;AAGD,4CAWC;AAGD,wDAcC;AAGD,8CAGC;AAqED,wDAuCC;AAnjBD,2CAA8C;AAC9C,6DAAoD;AASpD,yDAAwD;AAExD,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAElC,0DAA0D;AAC1D,SAAS,cAAc,CAAC,MAA2B;IACjD,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,OAAO;YACV,OAAO,IAAI,qCAAkB,CAAC,MAAM,CAAC,CAAC;QACxC,KAAK,QAAQ;YACX,uCAAuC;YACvC,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;QAC9D,KAAK,aAAa;YAChB,4CAA4C;YAC5C,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACnE;YACE,MAAM,IAAI,KAAK,CAAC,6BAA6B,MAAM,CAAC,IAAI,EAAE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AAgC;QACzD,cAAc,EAAE,QAAQ,CAAC,cAAgC;QACzD,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB;QACnD,QAAQ,EAAE,QAAQ,CAAC,QAAQ;QAC3B,SAAS,EAAE,QAAQ,CAAC,SAAS;KAC9B,CAAC;IAEF,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC;AAED,2EAA2E;AACpE,KAAK,UAAU,sBAAsB,CAAC,OAU5C;IACC,IAAI,CAAC;QACH,IAAI,QAAwB,CAAC;QAE7B,IAAI,OAAO,EAAE,QAAQ,EAAE,CAAC;YACtB,gEAAgE;YAChE,QAAQ,GAAG,0BAA0B,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC1D,CAAC;aAAM,IAAI,OAAO,EAAE,EAAE,EAAE,CAAC;YACvB,uCAAuC;YACvC,QAAQ,GAAG,MAAM,uBAAuB,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACvD,CAAC;aAAM,CAAC;YACN,0BAA0B;YAC1B,QAAQ,GAAG,MAAM,mBAAmB,EAAE,CAAC;QACzC,CAAC;QAED,+DAA+D;QAC/D,MAAM,QAAQ,CAAC,cAAc,EAAE,CAAC;QAEhC,OAAO;YACL,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,2CAA2C;SACrD,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,YAAY,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC;QACnF,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,YAAY;SACpB,CAAC;IACJ,CAAC;AACH,CAAC"} \ No newline at end of file +{"version":3,"file":"emailProviderService.js","sourceRoot":"","sources":["../../../src/services/emailProvider/emailProviderService.ts"],"names":[],"mappings":";AAAA,mEAAmE;;AAkCnE,sDAIC;AAED,sDAIC;AAED,4DAIC;AAED,0DAQC;AAsBD,oD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/C,IAAI,CAAC,MAAM,EAAE,kBAAkB,IAAI,CAAC,MAAM,EAAE,4BAA4B,EAAE,CAAC;QACzE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,QAAgB,CAAC;IACrB,IAAI,CAAC;QACH,QAAQ,GAAG,IAAA,uBAAO,EAAC,MAAM,CAAC,4BAA4B,CAAC,CAAC;IAC1D,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAC;QAC1E,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,mBAAmB,EAAE,CAAC;IAC7C,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IAE3B,OAAO;QACL,YAAY,EAAE,MAAM,CAAC,kBAAkB;QACvC,QAAQ;QACR,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,QAAQ,EAAE,QAAQ,CAAC,QAAQ;QAC3B,cAAc,EAAE,QAAQ,CAAC,cAAc;QACvC,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB;KACpD,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/backend/dist/services/user.service.d.ts b/backend/dist/services/user.service.d.ts index ff92e3c9..bf03a6df 100644 --- a/backend/dist/services/user.service.d.ts +++ b/backend/dist/services/user.service.d.ts @@ -20,12 +20,16 @@ export declare function getAllUsers(filters: UserFilters): Promise<{ description: string | null; })[]; hasDeveloperAccess: boolean; + hasGdprAccess: boolean; id: number; email: string; customerId: number | null; firstName: string; lastName: string; isActive: boolean; + whatsappNumber: string | null; + telegramUsername: string | null; + signalNumber: string | null; createdAt: Date; }[]; pagination: { @@ -61,6 +65,9 @@ export declare function getUserById(id: number): Promise<{ firstName: string; lastName: string; isActive: boolean; + whatsappNumber: string | null; + telegramUsername: string | null; + signalNumber: string | null; createdAt: Date; updatedAt: Date; } | null>; @@ -72,6 +79,10 @@ export declare function createUser(data: { roleIds: number[]; customerId?: number; hasDeveloperAccess?: boolean; + hasGdprAccess?: boolean; + whatsappNumber?: string; + telegramUsername?: string; + signalNumber?: string; }): Promise<{ id: number; email: string; @@ -101,6 +112,10 @@ export declare function updateUser(id: number, data: { roleIds?: number[]; customerId?: number; hasDeveloperAccess?: boolean; + hasGdprAccess?: boolean; + whatsappNumber?: string; + telegramUsername?: string; + signalNumber?: string; }): Promise<{ roles: ({ permissions: ({ @@ -127,6 +142,9 @@ export declare function updateUser(id: number, data: { firstName: string; lastName: string; isActive: boolean; + whatsappNumber: string | null; + telegramUsername: string | null; + signalNumber: string | null; createdAt: Date; updatedAt: Date; } | null>; @@ -139,6 +157,9 @@ export declare function deleteUser(id: number): Promise<{ lastName: string; isActive: boolean; tokenInvalidatedAt: Date | null; + whatsappNumber: string | null; + telegramUsername: string | null; + signalNumber: string | null; createdAt: Date; updatedAt: Date; }>; diff --git a/backend/dist/services/user.service.d.ts.map b/backend/dist/services/user.service.d.ts.map index f4ceee54..0051738e 100644 --- a/backend/dist/services/user.service.d.ts.map +++ b/backend/dist/services/user.service.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"user.service.d.ts","sourceRoot":"","sources":["../../src/services/user.service.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,WAAW;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,WAAW,CAAC,OAAO,EAAE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqErD;AAED,wBAAsB,WAAW,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA0C3C;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM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iB;;;;KAItC"} \ No newline at end of file +{"version":3,"file":"user.service.d.ts","sourceRoot":"","sources":["../../src/services/user.service.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,WAAW;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAsB,WAAW,CAAC,OAAO,EAAE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4ErD;AAED,wBAAsB,WAAW,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA6C3C;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;;;;;;;;;;;;;;;;;;;GAyCA;AAED,wBAAsB,UAAU,CAC9B,EAAE,EAAE,MAAM,EACV,IAAI,EAAE;IACJ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA4IF;AA4GD,wBAAsB,UAAU,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;GA6D1C;AAGD,wBAAsB,WAAW;;;;;;;;;;;;;;;;;;;;MAYhC;AAED,wBAAsB,WAAW,CAAC,EAAE,EAAE,MAAM;;;;;;;;;;;;;;;;;WAS3C;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB;;;;;;;;;;;;;;;;;GAeA;AAED,wBAAsB,UAAU,CAC9B,EAAE,EAAE,MAAM,EACV,IAAI,EAAE;IACJ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;CAC1B;;;;;;;;;;;;;;;;;WAiBF;AAED,wBAAsB,UAAU,CAAC,EAAE,EAAE,MAAM;;;;;;GAU1C;AAGD,wBAAsB,iBAAiB;;;;KAItC"} \ No newline at end of file diff --git a/backend/dist/services/user.service.js b/backend/dist/services/user.service.js index 41f4ecd6..dae80d77 100644 --- a/backend/dist/services/user.service.js +++ b/backend/dist/services/user.service.js @@ -48,6 +48,9 @@ async function getAllUsers(filters) { lastName: true, isActive: true, customerId: true, + whatsappNumber: true, + telegramUsername: true, + signalNumber: true, createdAt: true, roles: { include: { @@ -62,20 +65,24 @@ async function getAllUsers(filters) { }), prisma.user.count({ where }), ]); - // Get Developer role ID - const developerRole = await prisma.role.findFirst({ - where: { name: 'Developer' }, - }); + // Get hidden role IDs + const [developerRole, gdprRole] = await Promise.all([ + prisma.role.findFirst({ where: { name: 'Developer' } }), + prisma.role.findFirst({ where: { name: 'DSGVO' } }), + ]); return { users: users.map((u) => { - // Check if user has developer role assigned const hasDeveloperAccess = developerRole ? u.roles.some((ur) => ur.roleId === developerRole.id) : false; + const hasGdprAccess = gdprRole + ? u.roles.some((ur) => ur.roleId === gdprRole.id) + : false; return { ...u, roles: u.roles.map((r) => r.role), hasDeveloperAccess, + hasGdprAccess, }; }), pagination: (0, helpers_js_1.buildPaginationResponse)(page, limit, total), @@ -91,6 +98,9 @@ async function getUserById(id) { lastName: true, isActive: true, customerId: true, + whatsappNumber: true, + telegramUsername: true, + signalNumber: true, createdAt: true, updatedAt: true, roles: { @@ -129,6 +139,9 @@ async function createUser(data) { firstName: data.firstName, lastName: data.lastName, customerId: data.customerId, + whatsappNumber: data.whatsappNumber || null, + telegramUsername: data.telegramUsername || null, + signalNumber: data.signalNumber || null, roles: { create: data.roleIds.map((roleId) => ({ roleId })), }, @@ -149,10 +162,14 @@ async function createUser(data) { if (data.hasDeveloperAccess) { await setUserDeveloperAccess(user.id, true); } + // DSGVO-Zugriff setzen falls aktiviert + if (data.hasGdprAccess) { + await setUserGdprAccess(user.id, true); + } return user; } async function updateUser(id, data) { - const { roleIds, password, hasDeveloperAccess, ...userData } = data; + const { roleIds, password, hasDeveloperAccess, hasGdprAccess, ...userData } = data; // Check if this would remove the last admin const isBeingDeactivated = userData.isActive === false; const rolesAreBeingChanged = roleIds !== undefined; @@ -259,15 +276,17 @@ async function updateUser(id, data) { }); } // Handle developer access - console.log('updateUser - hasDeveloperAccess:', hasDeveloperAccess); if (hasDeveloperAccess !== undefined) { await setUserDeveloperAccess(id, hasDeveloperAccess); } + // Handle GDPR access + if (hasGdprAccess !== undefined) { + await setUserGdprAccess(id, hasGdprAccess); + } return getUserById(id); } // Helper to set developer access for a user async function setUserDeveloperAccess(userId, enabled) { - console.log('setUserDeveloperAccess called - userId:', userId, 'enabled:', enabled); // Get or create developer:access permission let developerPerm = await prisma.permission.findFirst({ where: { resource: 'developer', action: 'access' }, @@ -296,10 +315,7 @@ async function setUserDeveloperAccess(userId, enabled) { const hasRole = await prisma.userRole.findFirst({ where: { userId, roleId: developerRole.id }, }); - console.log('setUserDeveloperAccess - developerRole.id:', developerRole.id, 'hasRole:', hasRole); if (enabled && !hasRole) { - // Add Developer role - console.log('Adding Developer role'); await prisma.userRole.create({ data: { userId, roleId: developerRole.id }, }); @@ -310,8 +326,6 @@ async function setUserDeveloperAccess(userId, enabled) { }); } else if (!enabled && hasRole) { - // Remove Developer role - console.log('Removing Developer role'); await prisma.userRole.delete({ where: { userId_roleId: { userId, roleId: developerRole.id } }, }); @@ -321,8 +335,51 @@ async function setUserDeveloperAccess(userId, enabled) { data: { tokenInvalidatedAt: new Date() }, }); } - else { - console.log('No action needed - enabled:', enabled, 'hasRole:', !!hasRole); +} +// Helper to set GDPR access for a user +async function setUserGdprAccess(userId, enabled) { + // Get or create DSGVO role + let gdprRole = await prisma.role.findFirst({ + where: { name: 'DSGVO' }, + }); + if (!gdprRole) { + // Create DSGVO role with all audit:* and gdpr:* permissions + const gdprPermissions = await prisma.permission.findMany({ + where: { + OR: [{ resource: 'audit' }, { resource: 'gdpr' }], + }, + }); + gdprRole = await prisma.role.create({ + data: { + name: 'DSGVO', + description: 'DSGVO-Zugriff: Audit-Logs und Datenschutz-Verwaltung', + permissions: { + create: gdprPermissions.map((p) => ({ permissionId: p.id })), + }, + }, + }); + } + // Check if user already has DSGVO role + const hasRole = await prisma.userRole.findFirst({ + where: { userId, roleId: gdprRole.id }, + }); + if (enabled && !hasRole) { + await prisma.userRole.create({ + data: { userId, roleId: gdprRole.id }, + }); + await prisma.user.update({ + where: { id: userId }, + data: { tokenInvalidatedAt: new Date() }, + }); + } + else if (!enabled && hasRole) { + await prisma.userRole.delete({ + where: { userId_roleId: { userId, roleId: gdprRole.id } }, + }); + await prisma.user.update({ + where: { id: userId }, + data: { tokenInvalidatedAt: new Date() }, + }); } } async function deleteUser(id) { diff --git a/backend/dist/services/user.service.js.map b/backend/dist/services/user.service.js.map index 1fc08ce7..b0aea6c1 100644 --- a/backend/dist/services/user.service.js.map +++ b/backend/dist/services/user.service.js.map @@ -1 +1 @@ -{"version":3,"file":"user.service.js","sourceRoot":"","sources":["../../src/services/user.service.ts"],"names":[],"mappings":";;;;;AAcA,kCAqEC;AAED,kCA0CC;AAED,gCAyCC;AAED,gCAmJC;AAoED,gCA6DC;AAGD,kCAYC;AAED,kCASC;AAED,gCAmBC;AAED,gCAuBC;AAED,gCAUC;AAGD,8CAIC;AA3hBD,2CAA8C;AAC9C,wDAA8B;AAC9B,oDAAwE;AAExE,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAU3B,KAAK,UAAU,WAAW,CAAC,OAAoB;IACpD,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,GAAG,CAAC,EAAE,KAAK,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC;IACnE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,IAAA,qBAAQ,EAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAE7C,MAAM,KAAK,GAA4B,EAAE,CAAC;IAE1C,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,IAAI,MAAM,EAAE,CAAC;QACX,KAAK,CAAC,KAAK,GAAG,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC;IACrC,CAAC;IAED,IAAI,MAAM,EAAE,CAAC;QACX,KAAK,CAAC,EAAE,GAAG;YACT,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE;YAC/B,EAAE,SAAS,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE;YACnC,EAAE,QAAQ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AK,EAAE,CAAC;KAClD,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file +{"version":3,"file":"user.service.js","sourceRoot":"","sources":["../../src/services/user.service.ts"],"names":[],"mappings":";;;;;AAcA,kCA4EC;AAED,kCA6CC;AAED,gCAqDC;AAED,gCA2JC;AA4GD,gCA6DC;AAGD,kCAYC;AAED,kCASC;AAED,gCAmBC;AAED,gCAuBC;AAED,gCAUC;AAGD,8CAIC;AAjmBD,2CAA8C;AAC9C,wDAA8B;AAC9B,oDAAwE;AAExE,MAAM,MAAM,GAAG,IAAI,qBAAY,EAAE,CAAC;AAU3B,KAAK,UAAU,WAAW,CAAC,OAAoB;IACpD,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,GAAG,CAAC,EAAE,KAAK,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC;IACnE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,IAAA,qBAAQ,EAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAE7C,MAAM,KAAK,GAA4B,EAAE,CAAC;IAE1C,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,IAAI,MAAM,EAAE,CAAC;QACX,KAAK,CAAC,KAAK,GAAG,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC;IACrC,CAAC;IAED,IAAI,MAAM,EAAE,CAAC;QACX,KAAK,CAAC,EAAE,GAAG;YACT,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE;YAC/B,EAAE,SAAS,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE;YACnC,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE;SACnC,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC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CAAC,UAAU,CAAC;YACrC,IAAI,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,YAAY,EAAE,CAAC,CAAC;SAC1E,CAAC,CAAC;IACL,CAAC;IAED,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC;AACzB,CAAC;AAEM,KAAK,UAAU,UAAU,CAAC,EAAU;IACzC,yCAAyC;IACzC,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;IACrE,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CACb,4CAA4C,KAAK,2BAA2B,CAC7E,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AAC/C,CAAC;AAED,wBAAwB;AACjB,KAAK,UAAU,iBAAiB;IACrC,OAAO,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC;QAChC,OAAO,EAAE,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;KAClD,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/backend/node_modules/.prisma/client/edge.js b/backend/node_modules/.prisma/client/edge.js index a2ea39a2..1856df2f 100644 --- a/backend/node_modules/.prisma/client/edge.js +++ b/backend/node_modules/.prisma/client/edge.js @@ -90,6 +90,25 @@ exports.Prisma.TransactionIsolationLevel = makeStrictEnum({ Serializable: 'Serializable' }); +exports.Prisma.EmailLogScalarFieldEnum = { + id: 'id', + fromAddress: 'fromAddress', + toAddress: 'toAddress', + subject: 'subject', + context: 'context', + customerId: 'customerId', + triggeredBy: 'triggeredBy', + smtpServer: 'smtpServer', + smtpPort: 'smtpPort', + smtpEncryption: 'smtpEncryption', + smtpUser: 'smtpUser', + success: 'success', + messageId: 'messageId', + errorMessage: 'errorMessage', + smtpResponse: 'smtpResponse', + sentAt: 'sentAt' +}; + exports.Prisma.AppSettingScalarFieldEnum = { id: 'id', key: 'key', @@ -106,6 +125,9 @@ exports.Prisma.UserScalarFieldEnum = { lastName: 'lastName', isActive: 'isActive', tokenInvalidatedAt: 'tokenInvalidatedAt', + whatsappNumber: 'whatsappNumber', + telegramUsername: 'telegramUsername', + signalNumber: 'signalNumber', customerId: 'customerId', createdAt: 'createdAt', updatedAt: 'updatedAt' @@ -154,6 +176,7 @@ exports.Prisma.CustomerScalarFieldEnum = { commercialRegisterPath: 'commercialRegisterPath', commercialRegisterNumber: 'commercialRegisterNumber', privacyPolicyPath: 'privacyPolicyPath', + consentHash: 'consentHash', notes: 'notes', portalEnabled: 'portalEnabled', portalEmail: 'portalEmail', @@ -174,6 +197,20 @@ exports.Prisma.CustomerRepresentativeScalarFieldEnum = { updatedAt: 'updatedAt' }; +exports.Prisma.RepresentativeAuthorizationScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + representativeId: 'representativeId', + isGranted: 'isGranted', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + notes: 'notes', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.AddressScalarFieldEnum = { id: 'id', customerId: 'customerId', @@ -235,6 +272,8 @@ exports.Prisma.EmailProviderConfigScalarFieldEnum = { imapEncryption: 'imapEncryption', smtpEncryption: 'smtpEncryption', allowSelfSignedCerts: 'allowSelfSignedCerts', + systemEmailAddress: 'systemEmailAddress', + systemEmailPasswordEncrypted: 'systemEmailPasswordEncrypted', isActive: 'isActive', isDefault: 'isDefault', createdAt: 'createdAt', @@ -303,6 +342,10 @@ exports.Prisma.MeterReadingScalarFieldEnum = { value: 'value', unit: 'unit', notes: 'notes', + reportedBy: 'reportedBy', + status: 'status', + transferredAt: 'transferredAt', + transferredBy: 'transferredBy', createdAt: 'createdAt' }; @@ -545,6 +588,80 @@ exports.Prisma.CarInsuranceDetailsScalarFieldEnum = { previousInsurer: 'previousInsurer' }; +exports.Prisma.AuditLogScalarFieldEnum = { + id: 'id', + userId: 'userId', + userEmail: 'userEmail', + userRole: 'userRole', + customerId: 'customerId', + isCustomerPortal: 'isCustomerPortal', + action: 'action', + sensitivity: 'sensitivity', + resourceType: 'resourceType', + resourceId: 'resourceId', + resourceLabel: 'resourceLabel', + endpoint: 'endpoint', + httpMethod: 'httpMethod', + ipAddress: 'ipAddress', + userAgent: 'userAgent', + changesBefore: 'changesBefore', + changesAfter: 'changesAfter', + changesEncrypted: 'changesEncrypted', + dataSubjectId: 'dataSubjectId', + legalBasis: 'legalBasis', + success: 'success', + errorMessage: 'errorMessage', + durationMs: 'durationMs', + createdAt: 'createdAt', + hash: 'hash', + previousHash: 'previousHash' +}; + +exports.Prisma.CustomerConsentScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + consentType: 'consentType', + status: 'status', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + version: 'version', + ipAddress: 'ipAddress', + createdBy: 'createdBy', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.DataDeletionRequestScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + status: 'status', + requestedAt: 'requestedAt', + requestSource: 'requestSource', + requestedBy: 'requestedBy', + processedAt: 'processedAt', + processedBy: 'processedBy', + deletedData: 'deletedData', + retainedData: 'retainedData', + retentionReason: 'retentionReason', + proofDocument: 'proofDocument', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.AuditRetentionPolicyScalarFieldEnum = { + id: 'id', + resourceType: 'resourceType', + sensitivity: 'sensitivity', + retentionDays: 'retentionDays', + description: 'description', + legalBasis: 'legalBasis', + isActive: 'isActive', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.SortOrder = { asc: 'asc', desc: 'desc' @@ -593,6 +710,12 @@ exports.MeterType = exports.$Enums.MeterType = { GAS: 'GAS' }; +exports.MeterReadingStatus = exports.$Enums.MeterReadingStatus = { + RECORDED: 'RECORDED', + REPORTED: 'REPORTED', + TRANSFERRED: 'TRANSFERRED' +}; + exports.ContractType = exports.$Enums.ContractType = { ELECTRICITY: 'ELECTRICITY', GAS: 'GAS', @@ -630,7 +753,48 @@ exports.InsuranceType = exports.$Enums.InsuranceType = { FULL: 'FULL' }; +exports.AuditAction = exports.$Enums.AuditAction = { + CREATE: 'CREATE', + READ: 'READ', + UPDATE: 'UPDATE', + DELETE: 'DELETE', + EXPORT: 'EXPORT', + ANONYMIZE: 'ANONYMIZE', + LOGIN: 'LOGIN', + LOGOUT: 'LOGOUT', + LOGIN_FAILED: 'LOGIN_FAILED' +}; + +exports.AuditSensitivity = exports.$Enums.AuditSensitivity = { + LOW: 'LOW', + MEDIUM: 'MEDIUM', + HIGH: 'HIGH', + CRITICAL: 'CRITICAL' +}; + +exports.ConsentType = exports.$Enums.ConsentType = { + DATA_PROCESSING: 'DATA_PROCESSING', + MARKETING_EMAIL: 'MARKETING_EMAIL', + MARKETING_PHONE: 'MARKETING_PHONE', + DATA_SHARING_PARTNER: 'DATA_SHARING_PARTNER' +}; + +exports.ConsentStatus = exports.$Enums.ConsentStatus = { + GRANTED: 'GRANTED', + WITHDRAWN: 'WITHDRAWN', + PENDING: 'PENDING' +}; + +exports.DeletionRequestStatus = exports.$Enums.DeletionRequestStatus = { + PENDING: 'PENDING', + IN_PROGRESS: 'IN_PROGRESS', + COMPLETED: 'COMPLETED', + PARTIALLY_COMPLETED: 'PARTIALLY_COMPLETED', + REJECTED: 'REJECTED' +}; + exports.Prisma.ModelName = { + EmailLog: 'EmailLog', AppSetting: 'AppSetting', User: 'User', Role: 'Role', @@ -639,6 +803,7 @@ exports.Prisma.ModelName = { UserRole: 'UserRole', Customer: 'Customer', CustomerRepresentative: 'CustomerRepresentative', + RepresentativeAuthorization: 'RepresentativeAuthorization', Address: 'Address', BankCard: 'BankCard', IdentityDocument: 'IdentityDocument', @@ -664,7 +829,11 @@ exports.Prisma.ModelName = { MobileContractDetails: 'MobileContractDetails', SimCard: 'SimCard', TvContractDetails: 'TvContractDetails', - CarInsuranceDetails: 'CarInsuranceDetails' + CarInsuranceDetails: 'CarInsuranceDetails', + AuditLog: 'AuditLog', + CustomerConsent: 'CustomerConsent', + DataDeletionRequest: 'DataDeletionRequest', + AuditRetentionPolicy: 'AuditRetentionPolicy' }; /** * Create the Client @@ -704,6 +873,7 @@ const config = { "db" ], "activeProvider": "mysql", + "postinstall": false, "inlineDatasources": { "db": { "url": { @@ -712,13 +882,13 @@ const config = { } } }, - "inlineSchema": "generator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ==================== APP SETTINGS ====================\n\nmodel AppSetting {\n id Int @id @default(autoincrement())\n key String @unique\n value String @db.Text\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== USERS & AUTH ====================\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n password String\n firstName String\n lastName String\n isActive Boolean @default(true)\n tokenInvalidatedAt DateTime? // Zeitpunkt ab dem alle Tokens ungültig sind (für Zwangslogout bei Rechteänderung)\n customerId Int? @unique\n customer Customer? @relation(fields: [customerId], references: [id])\n roles UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Role {\n id Int @id @default(autoincrement())\n name String @unique\n description String?\n permissions RolePermission[]\n users UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Permission {\n id Int @id @default(autoincrement())\n resource String\n action String\n roles RolePermission[]\n\n @@unique([resource, action])\n}\n\nmodel RolePermission {\n roleId Int\n permissionId Int\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)\n\n @@id([roleId, permissionId])\n}\n\nmodel UserRole {\n userId Int\n roleId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n\n @@id([userId, roleId])\n}\n\n// ==================== CUSTOMERS ====================\n\nenum CustomerType {\n PRIVATE\n BUSINESS\n}\n\nmodel Customer {\n id Int @id @default(autoincrement())\n customerNumber String @unique\n type CustomerType @default(PRIVATE)\n salutation String?\n firstName String\n lastName String\n companyName String?\n foundingDate DateTime? // Gründungsdatum (für Firmen)\n birthDate DateTime?\n birthPlace String?\n email String?\n phone String?\n mobile String?\n taxNumber String?\n businessRegistrationPath String? // PDF-Pfad zur Gewerbeanmeldung\n commercialRegisterPath String? // PDF-Pfad zum Handelsregisterauszug\n commercialRegisterNumber String? // Handelsregisternummer (Text)\n privacyPolicyPath String? // PDF-Pfad zur Datenschutzerklärung (für alle Kunden)\n notes String? @db.Text\n\n // ===== Portal-Zugangsdaten =====\n portalEnabled Boolean @default(false) // Portal aktiviert?\n portalEmail String? @unique // Portal-Login E-Mail\n portalPasswordHash String? // Gehashtes Passwort (für Login)\n portalPasswordEncrypted String? // Verschlüsseltes Passwort (für Anzeige)\n portalLastLogin DateTime? // Letzte Anmeldung\n\n user User?\n addresses Address[]\n bankCards BankCard[]\n identityDocuments IdentityDocument[]\n meters Meter[]\n stressfreiEmails StressfreiEmail[]\n contracts Contract[]\n\n // Vertreter-Beziehungen (Kunde kann für andere Kunden handeln)\n representingFor CustomerRepresentative[] @relation(\"RepresentativeCustomer\")\n representedBy CustomerRepresentative[] @relation(\"RepresentedCustomer\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CUSTOMER REPRESENTATIVES ====================\n// Vertretungsbeziehung: Ein Kunde kann die Verträge eines anderen Kunden einsehen\n// z.B. Sohn (representativeId) kann Verträge der Mutter (customerId) sehen\n\nmodel CustomerRepresentative {\n id Int @id @default(autoincrement())\n customerId Int // Der Kunde, dessen Verträge eingesehen werden (z.B. Mutter)\n customer Customer @relation(\"RepresentedCustomer\", fields: [customerId], references: [id], onDelete: Cascade)\n representativeId Int // Der Kunde, der einsehen darf (z.B. Sohn)\n representative Customer @relation(\"RepresentativeCustomer\", fields: [representativeId], references: [id], onDelete: Cascade)\n notes String? // Notizen zur Vertretung\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, representativeId]) // Keine doppelten Einträge\n}\n\n// ==================== ADDRESSES ====================\n\nenum AddressType {\n DELIVERY_RESIDENCE\n BILLING\n}\n\nmodel Address {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type AddressType @default(DELIVERY_RESIDENCE)\n street String\n houseNumber String\n postalCode String\n city String\n country String @default(\"Deutschland\")\n isDefault Boolean @default(false)\n contractsAsDelivery Contract[] @relation(\"DeliveryAddress\")\n contractsAsBilling Contract[] @relation(\"BillingAddress\")\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== BANK CARDS ====================\n\nmodel BankCard {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n accountHolder String\n iban String\n bic String?\n bankName String?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== IDENTITY DOCUMENTS ====================\n\nenum DocumentType {\n ID_CARD\n PASSPORT\n DRIVERS_LICENSE\n OTHER\n}\n\nmodel IdentityDocument {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type DocumentType @default(ID_CARD)\n documentNumber String\n issuingAuthority String?\n issueDate DateTime?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n // Führerschein-spezifische Felder\n licenseClasses String? // z.B. \"B, BE, AM, L\" - kommasepariert\n licenseIssueDate DateTime? // Datum des Führerscheinerwerbs (Klasse B)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== EMAIL PROVIDER CONFIG (Plesk, cPanel etc.) ====================\n\nenum EmailProviderType {\n PLESK\n CPANEL\n DIRECTADMIN\n}\n\n// Verschlüsselungstyp für E-Mail-Verbindungen\nenum MailEncryption {\n SSL // Implicit SSL/TLS (Ports 465/993) - Verschlüsselung von Anfang an\n STARTTLS // STARTTLS (Ports 587/143) - Startet unverschlüsselt, dann Upgrade\n NONE // Keine Verschlüsselung (Ports 25/143)\n}\n\nmodel EmailProviderConfig {\n id Int @id @default(autoincrement())\n name String @unique // z.B. \"Plesk Hauptserver\"\n type EmailProviderType\n apiUrl String // API-URL (z.B. https://server.de:8443)\n apiKey String? // API-Key (verschlüsselt)\n username String? // Benutzername für API\n passwordEncrypted String? // Passwort (verschlüsselt)\n domain String // Domain für E-Mails (z.B. stressfrei-wechseln.de)\n defaultForwardEmail String? // Standard-Weiterleitungsadresse (unsere eigene)\n\n // IMAP/SMTP-Server für E-Mail-Client (optional, default: mail.{domain})\n imapServer String? // z.B. \"mail.stressfrei-wechseln.de\"\n imapPort Int? @default(993)\n smtpServer String?\n smtpPort Int? @default(465)\n\n // Verschlüsselungs-Einstellungen\n imapEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n smtpEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n allowSelfSignedCerts Boolean @default(false) // Selbstsignierte Zertifikate erlauben\n\n isActive Boolean @default(true)\n isDefault Boolean @default(false) // Standard-Provider\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== STRESSFREI-WECHSELN EMAIL ADDRESSES ====================\n\nmodel StressfreiEmail {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n email String // Die Weiterleitungs-E-Mail-Adresse\n platform String? // Für welche Plattform (z.B. \"Freenet\", \"Klarmobil\")\n notes String? @db.Text // Optionale Notizen\n isActive Boolean @default(true)\n isProvisioned Boolean @default(false) // Wurde bei Provider angelegt?\n provisionedAt DateTime? // Wann wurde provisioniert?\n provisionError String? @db.Text // Fehlermeldung falls Provisionierung fehlschlug\n\n // Mailbox-Zugangsdaten (für IMAP/SMTP-Zugang)\n hasMailbox Boolean @default(false) // Hat echte Mailbox (nicht nur Weiterleitung)?\n emailPasswordEncrypted String? // Verschlüsseltes Mailbox-Passwort (AES-256-GCM)\n\n contracts Contract[] // Verträge die diese E-Mail als Benutzername verwenden\n cachedEmails CachedEmail[] // Gecachte E-Mails aus dieser Mailbox\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CACHED EMAILS (E-Mail-Client) ====================\n\nenum EmailFolder {\n INBOX\n SENT\n}\n\nmodel CachedEmail {\n id Int @id @default(autoincrement())\n stressfreiEmailId Int\n stressfreiEmail StressfreiEmail @relation(fields: [stressfreiEmailId], references: [id], onDelete: Cascade)\n\n // Ordner (Posteingang oder Gesendet)\n folder EmailFolder @default(INBOX)\n\n // IMAP-Identifikation\n messageId String // RFC 5322 Message-ID\n uid Int // IMAP UID (für Synchronisierung, bei SENT = 0)\n\n // E-Mail-Metadaten\n subject String?\n fromAddress String\n fromName String?\n toAddresses String @db.Text // JSON Array\n ccAddresses String? @db.Text // JSON Array\n receivedAt DateTime\n\n // Inhalt\n textBody String? @db.LongText\n htmlBody String? @db.LongText\n hasAttachments Boolean @default(false)\n attachmentNames String? @db.Text // JSON Array\n\n // Vertragszuordnung\n contractId Int?\n contract Contract? @relation(fields: [contractId], references: [id], onDelete: SetNull)\n assignedAt DateTime?\n assignedBy Int? // User ID der die Zuordnung gemacht hat\n isAutoAssigned Boolean @default(false) // true = automatisch beim Senden aus Vertrag\n\n // Flags\n isRead Boolean @default(false)\n isStarred Boolean @default(false)\n\n // Papierkorb\n isDeleted Boolean @default(false) // Im Papierkorb?\n deletedAt DateTime? // Wann gelöscht?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([stressfreiEmailId, messageId, folder]) // Folder hinzugefügt: gleiche MessageID kann in INBOX und SENT existieren\n @@index([contractId])\n @@index([stressfreiEmailId, folder, receivedAt])\n @@index([stressfreiEmailId, isDeleted]) // Für Papierkorb-Abfragen\n}\n\n// ==================== METERS (Energy) ====================\n\nenum MeterType {\n ELECTRICITY\n GAS\n}\n\nmodel Meter {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n meterNumber String\n type MeterType\n location String?\n isActive Boolean @default(true)\n readings MeterReading[]\n energyDetails EnergyContractDetails[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel MeterReading {\n id Int @id @default(autoincrement())\n meterId Int\n meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade)\n readingDate DateTime\n value Float\n unit String @default(\"kWh\")\n notes String?\n createdAt DateTime @default(now())\n}\n\n// ==================== SALES PLATFORMS ====================\n\nmodel SalesPlatform {\n id Int @id @default(autoincrement())\n name String @unique\n contactInfo String? @db.Text\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CANCELLATION PERIODS ====================\n\nmodel CancellationPeriod {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"14T\", \"1M\", \"3M\", \"12M\", \"1J\"\n description String // z.B. \"14 Tage\", \"1 Monat\", \"3 Monate\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT DURATIONS ====================\n\nmodel ContractDuration {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"12M\", \"24M\", \"1J\", \"2J\"\n description String // z.B. \"12 Monate\", \"24 Monate\", \"1 Jahr\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== PROVIDERS (Anbieter) ====================\n\nmodel Provider {\n id Int @id @default(autoincrement())\n name String @unique // Anbietername\n portalUrl String? // Kundenkontourl (Login-Seite)\n usernameFieldName String? // Benutzernamefeld (z.B. \"email\", \"username\")\n passwordFieldName String? // Kennwortfeld (z.B. \"password\", \"pwd\")\n isActive Boolean @default(true)\n tariffs Tariff[]\n contracts Contract[]\n previousContracts Contract[] @relation(\"PreviousProvider\") // Verträge wo dieser Provider Altanbieter ist\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TARIFFS (Tarife) ====================\n\nmodel Tariff {\n id Int @id @default(autoincrement())\n providerId Int\n provider Provider @relation(fields: [providerId], references: [id], onDelete: Cascade)\n name String // Tarifname\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([providerId, name]) // Eindeutiger Tarif pro Anbieter\n}\n\n// ==================== CONTRACT CATEGORIES ====================\n\nmodel ContractCategory {\n id Int @id @default(autoincrement())\n code String @unique // Technischer Code (z.B. ELECTRICITY, GAS)\n name String // Anzeigename (z.B. Strom, Gas)\n icon String? // Icon-Name für UI (z.B. \"Zap\", \"Flame\")\n color String? // Farbe für UI (z.B. \"#FFC107\")\n sortOrder Int @default(0)\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACTS ====================\n\n// Legacy Enum - wird durch ContractCategory ersetzt\nenum ContractType {\n ELECTRICITY\n GAS\n DSL\n CABLE\n FIBER\n MOBILE\n TV\n CAR_INSURANCE\n}\n\nenum ContractStatus {\n DRAFT\n PENDING\n ACTIVE\n CANCELLED\n EXPIRED\n DEACTIVATED\n}\n\nmodel Contract {\n id Int @id @default(autoincrement())\n contractNumber String @unique\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type ContractType\n status ContractStatus @default(DRAFT)\n\n // Neue konfigurierbare Kategorie (ersetzt langfristig das type-Enum)\n contractCategoryId Int?\n contractCategory ContractCategory? @relation(fields: [contractCategoryId], references: [id])\n\n // Lieferadresse\n addressId Int?\n address Address? @relation(\"DeliveryAddress\", fields: [addressId], references: [id])\n\n // Rechnungsadresse (falls leer, wird Lieferadresse verwendet)\n billingAddressId Int?\n billingAddress Address? @relation(\"BillingAddress\", fields: [billingAddressId], references: [id])\n\n bankCardId Int?\n bankCard BankCard? @relation(fields: [bankCardId], references: [id])\n\n identityDocumentId Int?\n identityDocument IdentityDocument? @relation(fields: [identityDocumentId], references: [id])\n\n salesPlatformId Int?\n salesPlatform SalesPlatform? @relation(fields: [salesPlatformId], references: [id])\n\n cancellationPeriodId Int?\n cancellationPeriod CancellationPeriod? @relation(fields: [cancellationPeriodId], references: [id])\n\n contractDurationId Int?\n contractDuration ContractDuration? @relation(fields: [contractDurationId], references: [id])\n\n previousContractId Int? @unique\n previousContract Contract? @relation(\"ContractHistory\", fields: [previousContractId], references: [id])\n followUpContract Contract? @relation(\"ContractHistory\")\n\n // Altanbieter-Daten (nur wenn kein Vorgängervertrag existiert)\n previousProviderId Int?\n previousProvider Provider? @relation(\"PreviousProvider\", fields: [previousProviderId], references: [id])\n previousCustomerNumber String? // Kundennummer beim Altanbieter\n previousContractNumber String? // Vertragsnummer beim Altanbieter\n\n // Anbieter & Tarif (neue Verknüpfung)\n providerId Int?\n provider Provider? @relation(fields: [providerId], references: [id])\n tariffId Int?\n tariff Tariff? @relation(fields: [tariffId], references: [id])\n\n // Legacy-Felder (für Abwärtskompatibilität)\n providerName String?\n tariffName String?\n customerNumberAtProvider String?\n contractNumberAtProvider String? // Vertragsnummer beim Anbieter\n priceFirst12Months String? // Preis erste 12 Monate\n priceFrom13Months String? // Preis ab 13. Monat\n priceAfter24Months String? // Preis nach 24 Monaten\n\n startDate DateTime?\n endDate DateTime? // Wird aus startDate + contractDuration berechnet\n commission Float?\n\n // Kündigungsdokumente\n cancellationLetterPath String? // Kündigungsschreiben PDF\n cancellationConfirmationPath String? // Kündigungsbestätigung PDF\n cancellationLetterOptionsPath String? // Kündigungsschreiben Optionen PDF\n cancellationConfirmationOptionsPath String? // Kündigungsbestätigung Optionen PDF\n\n // Kündigungsdaten\n cancellationConfirmationDate DateTime? // Kündigungsbestätigungsdatum\n cancellationConfirmationOptionsDate DateTime? // Kündigungsbestätigungsoptionendatum\n wasSpecialCancellation Boolean @default(false) // Wurde sondergekündigt?\n\n portalUsername String?\n portalPasswordEncrypted String?\n\n // Stressfrei-Wechseln E-Mail als Benutzername (Alternative zu portalUsername)\n stressfreiEmailId Int?\n stressfreiEmail StressfreiEmail? @relation(fields: [stressfreiEmailId], references: [id])\n\n // Snooze: Vertrag zurückstellen bis Datum (für Cockpit)\n nextReviewDate DateTime? // Erneute Prüfung am\n\n notes String? @db.Text\n\n energyDetails EnergyContractDetails?\n internetDetails InternetContractDetails?\n mobileDetails MobileContractDetails?\n tvDetails TvContractDetails?\n carInsuranceDetails CarInsuranceDetails?\n\n tasks ContractTask[]\n assignedEmails CachedEmail[] // Zugeordnete E-Mails aus dem E-Mail-Client\n historyEntries ContractHistoryEntry[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT HISTORY ====================\n\nmodel ContractHistoryEntry {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String // Kurzbeschreibung (z.B. \"Folgevertrag erstellt\", \"kWh auf 18000 erhöht\")\n description String? @db.Text // Längere Beschreibung (optional)\n isAutomatic Boolean @default(false) // true = automatisch erstellt, false = manuell\n createdBy String // E-Mail des Erstellers\n createdAt DateTime @default(now())\n}\n\n// ==================== CONTRACT TASKS ====================\n\nenum ContractTaskStatus {\n OPEN\n COMPLETED\n}\n\nmodel ContractTask {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String\n description String? @db.Text\n status ContractTaskStatus @default(OPEN)\n visibleInPortal Boolean @default(false)\n createdBy String? // Name des Erstellers\n completedAt DateTime?\n subtasks ContractTaskSubtask[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel ContractTaskSubtask {\n id Int @id @default(autoincrement())\n taskId Int\n task ContractTask @relation(fields: [taskId], references: [id], onDelete: Cascade)\n title String\n status ContractTaskStatus @default(OPEN)\n createdBy String?\n completedAt DateTime?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== ENERGY CONTRACT DETAILS ====================\n\nenum InvoiceType {\n INTERIM // Zwischenrechnung\n FINAL // Schlussrechnung\n NOT_AVAILABLE // Rechnung nicht mehr zu bekommen\n}\n\nmodel EnergyContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n meterId Int?\n meter Meter? @relation(fields: [meterId], references: [id])\n maloId String? // Marktlokations-ID\n annualConsumption Float? // kWh für Strom, m³ für Gas\n annualConsumptionKwh Float? // kWh für Gas (zusätzlich zu m³)\n basePrice Float? // €/Monat\n unitPrice Float? // €/kWh (Arbeitspreis)\n bonus Float?\n previousProviderName String?\n previousCustomerNumber String?\n invoices Invoice[] // Rechnungen\n}\n\nmodel Invoice {\n id Int @id @default(autoincrement())\n energyContractDetailsId Int\n energyContractDetails EnergyContractDetails @relation(fields: [energyContractDetailsId], references: [id], onDelete: Cascade)\n invoiceDate DateTime\n invoiceType InvoiceType\n documentPath String? // Pflicht, außer bei NOT_AVAILABLE\n notes String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([energyContractDetailsId])\n}\n\n// ==================== INTERNET CONTRACT DETAILS ====================\n\nmodel InternetContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n downloadSpeed Int?\n uploadSpeed Int?\n routerModel String?\n routerSerialNumber String?\n installationDate DateTime?\n // Internet-Zugangsdaten\n internetUsername String?\n internetPasswordEncrypted String? // Verschlüsselt gespeichert\n // Glasfaser-spezifisch\n homeId String?\n // Vodafone DSL/Kabel spezifisch\n activationCode String?\n phoneNumbers PhoneNumber[]\n}\n\nmodel PhoneNumber {\n id Int @id @default(autoincrement())\n internetContractDetailsId Int\n internetDetails InternetContractDetails @relation(fields: [internetContractDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String\n isMain Boolean @default(false)\n // SIP-Zugangsdaten\n sipUsername String?\n sipPasswordEncrypted String? // Verschlüsselt gespeichert\n sipServer String?\n}\n\n// ==================== MOBILE CONTRACT DETAILS ====================\n\nmodel MobileContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n requiresMultisim Boolean @default(false) // Multisim erforderlich?\n dataVolume Float?\n includedMinutes Int?\n includedSMS Int?\n deviceModel String?\n deviceImei String?\n simCards SimCard[]\n // Legacy-Felder (für Abwärtskompatibilität, werden durch simCards ersetzt)\n phoneNumber String?\n simCardNumber String?\n}\n\nmodel SimCard {\n id Int @id @default(autoincrement())\n mobileDetailsId Int\n mobileDetails MobileContractDetails @relation(fields: [mobileDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String? // Rufnummer\n simCardNumber String? // SIM-Kartennummer\n pin String? // PIN (verschlüsselt gespeichert)\n puk String? // PUK (verschlüsselt gespeichert)\n isMultisim Boolean @default(false) // Ist dies eine Multisim-Karte?\n isMain Boolean @default(false) // Ist dies die Hauptkarte?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TV CONTRACT DETAILS ====================\n\nmodel TvContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n receiverModel String?\n smartcardNumber String?\n package String?\n}\n\n// ==================== CAR INSURANCE DETAILS ====================\n\nenum InsuranceType {\n LIABILITY\n PARTIAL\n FULL\n}\n\nmodel CarInsuranceDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n licensePlate String?\n hsn String?\n tsn String?\n vin String?\n vehicleType String?\n firstRegistration DateTime?\n noClaimsClass String?\n insuranceType InsuranceType @default(LIABILITY)\n deductiblePartial Float?\n deductibleFull Float?\n policyNumber String?\n previousInsurer String?\n}\n", - "inlineSchemaHash": "78e1ffc1151c8ed5044757206fc5cc6883ede2dea13cc396805b105375e30f1c", + "inlineSchema": "generator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ==================== EMAIL LOG ====================\n\nmodel EmailLog {\n id Int @id @default(autoincrement())\n // Absender & Empfänger\n fromAddress String // Absender-E-Mail\n toAddress String // Empfänger-E-Mail\n subject String // Betreff\n // Versand-Kontext\n context String // z.B. \"consent-link\", \"authorization-request\", \"customer-email\"\n customerId Int? // Zugehöriger Kunde (falls vorhanden)\n triggeredBy String? // Wer hat den Versand ausgelöst (User-Email)\n // SMTP-Details\n smtpServer String // SMTP-Server\n smtpPort Int // SMTP-Port\n smtpEncryption String // SSL, STARTTLS, NONE\n smtpUser String // SMTP-Benutzername\n // Ergebnis\n success Boolean // Erfolgreich?\n messageId String? // Message-ID aus SMTP-Antwort\n errorMessage String? @db.Text // Fehlermeldung bei Fehler\n smtpResponse String? @db.Text // SMTP-Server-Antwort\n // Zeitstempel\n sentAt DateTime @default(now())\n\n @@index([sentAt])\n @@index([customerId])\n @@index([success])\n}\n\n// ==================== APP SETTINGS ====================\n\nmodel AppSetting {\n id Int @id @default(autoincrement())\n key String @unique\n value String @db.Text\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== USERS & AUTH ====================\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n password String\n firstName String\n lastName String\n isActive Boolean @default(true)\n tokenInvalidatedAt DateTime? // Zeitpunkt ab dem alle Tokens ungültig sind (für Zwangslogout bei Rechteänderung)\n\n // Messaging-Kanäle (für Datenschutz-Link-Versand)\n whatsappNumber String?\n telegramUsername String?\n signalNumber String?\n\n customerId Int? @unique\n customer Customer? @relation(fields: [customerId], references: [id])\n roles UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Role {\n id Int @id @default(autoincrement())\n name String @unique\n description String?\n permissions RolePermission[]\n users UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Permission {\n id Int @id @default(autoincrement())\n resource String\n action String\n roles RolePermission[]\n\n @@unique([resource, action])\n}\n\nmodel RolePermission {\n roleId Int\n permissionId Int\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)\n\n @@id([roleId, permissionId])\n}\n\nmodel UserRole {\n userId Int\n roleId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n\n @@id([userId, roleId])\n}\n\n// ==================== CUSTOMERS ====================\n\nenum CustomerType {\n PRIVATE\n BUSINESS\n}\n\nmodel Customer {\n id Int @id @default(autoincrement())\n customerNumber String @unique\n type CustomerType @default(PRIVATE)\n salutation String?\n firstName String\n lastName String\n companyName String?\n foundingDate DateTime? // Gründungsdatum (für Firmen)\n birthDate DateTime?\n birthPlace String?\n email String?\n phone String?\n mobile String?\n taxNumber String?\n businessRegistrationPath String? // PDF-Pfad zur Gewerbeanmeldung\n commercialRegisterPath String? // PDF-Pfad zum Handelsregisterauszug\n commercialRegisterNumber String? // Handelsregisternummer (Text)\n privacyPolicyPath String? // PDF-Pfad zur Datenschutzerklärung (für alle Kunden)\n consentHash String? @unique // Permanenter Hash für öffentlichen Einwilligungslink /datenschutz/\n notes String? @db.Text\n\n // ===== Portal-Zugangsdaten =====\n portalEnabled Boolean @default(false) // Portal aktiviert?\n portalEmail String? @unique // Portal-Login E-Mail\n portalPasswordHash String? // Gehashtes Passwort (für Login)\n portalPasswordEncrypted String? // Verschlüsseltes Passwort (für Anzeige)\n portalLastLogin DateTime? // Letzte Anmeldung\n\n user User?\n addresses Address[]\n bankCards BankCard[]\n identityDocuments IdentityDocument[]\n meters Meter[]\n stressfreiEmails StressfreiEmail[]\n contracts Contract[]\n\n // Vertreter-Beziehungen (Kunde kann für andere Kunden handeln)\n representingFor CustomerRepresentative[] @relation(\"RepresentativeCustomer\")\n representedBy CustomerRepresentative[] @relation(\"RepresentedCustomer\")\n\n // Vollmachten\n authorizationsGiven RepresentativeAuthorization[] @relation(\"AuthorizationCustomer\")\n authorizationsReceived RepresentativeAuthorization[] @relation(\"AuthorizationRepresentative\")\n\n // DSGVO: Einwilligungen\n consents CustomerConsent[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CUSTOMER REPRESENTATIVES ====================\n// Vertretungsbeziehung: Ein Kunde kann die Verträge eines anderen Kunden einsehen\n// z.B. Sohn (representativeId) kann Verträge der Mutter (customerId) sehen\n\nmodel CustomerRepresentative {\n id Int @id @default(autoincrement())\n customerId Int // Der Kunde, dessen Verträge eingesehen werden (z.B. Mutter)\n customer Customer @relation(\"RepresentedCustomer\", fields: [customerId], references: [id], onDelete: Cascade)\n representativeId Int // Der Kunde, der einsehen darf (z.B. Sohn)\n representative Customer @relation(\"RepresentativeCustomer\", fields: [representativeId], references: [id], onDelete: Cascade)\n notes String? // Notizen zur Vertretung\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, representativeId]) // Keine doppelten Einträge\n}\n\n// ==================== VOLLMACHTEN ====================\n// Vollmacht: Kunde B erteilt Kunde A die Vollmacht, seine Daten einzusehen\n// Ohne Vollmacht kann der Vertreter die Verträge des Kunden NICHT sehen\n\nmodel RepresentativeAuthorization {\n id Int @id @default(autoincrement())\n customerId Int // Der Kunde, der die Vollmacht erteilt (z.B. Mutter)\n customer Customer @relation(\"AuthorizationCustomer\", fields: [customerId], references: [id], onDelete: Cascade)\n representativeId Int // Der Vertreter, der Zugriff bekommt (z.B. Sohn)\n representative Customer @relation(\"AuthorizationRepresentative\", fields: [representativeId], references: [id], onDelete: Cascade)\n isGranted Boolean @default(false) // Vollmacht erteilt?\n grantedAt DateTime? // Wann erteilt\n withdrawnAt DateTime? // Wann widerrufen\n source String? // Quelle: 'portal', 'papier', 'crm-backend'\n documentPath String? // PDF-Upload der unterschriebenen Vollmacht\n notes String? @db.Text // Notizen\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, representativeId]) // Eine Vollmacht pro Paar\n}\n\n// ==================== ADDRESSES ====================\n\nenum AddressType {\n DELIVERY_RESIDENCE\n BILLING\n}\n\nmodel Address {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type AddressType @default(DELIVERY_RESIDENCE)\n street String\n houseNumber String\n postalCode String\n city String\n country String @default(\"Deutschland\")\n isDefault Boolean @default(false)\n contractsAsDelivery Contract[] @relation(\"DeliveryAddress\")\n contractsAsBilling Contract[] @relation(\"BillingAddress\")\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== BANK CARDS ====================\n\nmodel BankCard {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n accountHolder String\n iban String\n bic String?\n bankName String?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== IDENTITY DOCUMENTS ====================\n\nenum DocumentType {\n ID_CARD\n PASSPORT\n DRIVERS_LICENSE\n OTHER\n}\n\nmodel IdentityDocument {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type DocumentType @default(ID_CARD)\n documentNumber String\n issuingAuthority String?\n issueDate DateTime?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n // Führerschein-spezifische Felder\n licenseClasses String? // z.B. \"B, BE, AM, L\" - kommasepariert\n licenseIssueDate DateTime? // Datum des Führerscheinerwerbs (Klasse B)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== EMAIL PROVIDER CONFIG (Plesk, cPanel etc.) ====================\n\nenum EmailProviderType {\n PLESK\n CPANEL\n DIRECTADMIN\n}\n\n// Verschlüsselungstyp für E-Mail-Verbindungen\nenum MailEncryption {\n SSL // Implicit SSL/TLS (Ports 465/993) - Verschlüsselung von Anfang an\n STARTTLS // STARTTLS (Ports 587/143) - Startet unverschlüsselt, dann Upgrade\n NONE // Keine Verschlüsselung (Ports 25/143)\n}\n\nmodel EmailProviderConfig {\n id Int @id @default(autoincrement())\n name String @unique // z.B. \"Plesk Hauptserver\"\n type EmailProviderType\n apiUrl String // API-URL (z.B. https://server.de:8443)\n apiKey String? // API-Key (verschlüsselt)\n username String? // Benutzername für API\n passwordEncrypted String? // Passwort (verschlüsselt)\n domain String // Domain für E-Mails (z.B. stressfrei-wechseln.de)\n defaultForwardEmail String? // Standard-Weiterleitungsadresse (unsere eigene)\n\n // IMAP/SMTP-Server für E-Mail-Client (optional, default: mail.{domain})\n imapServer String? // z.B. \"mail.stressfrei-wechseln.de\"\n imapPort Int? @default(993)\n smtpServer String?\n smtpPort Int? @default(465)\n\n // Verschlüsselungs-Einstellungen\n imapEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n smtpEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n allowSelfSignedCerts Boolean @default(false) // Selbstsignierte Zertifikate erlauben\n\n // System-E-Mail für automatisierte Nachrichten (z.B. DSGVO Consent-Links)\n systemEmailAddress String? // z.B. \"info@stressfrei-wechseln.de\"\n systemEmailPasswordEncrypted String? // Passwort (verschlüsselt)\n\n isActive Boolean @default(true)\n isDefault Boolean @default(false) // Standard-Provider\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== STRESSFREI-WECHSELN EMAIL ADDRESSES ====================\n\nmodel StressfreiEmail {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n email String // Die Weiterleitungs-E-Mail-Adresse\n platform String? // Für welche Plattform (z.B. \"Freenet\", \"Klarmobil\")\n notes String? @db.Text // Optionale Notizen\n isActive Boolean @default(true)\n isProvisioned Boolean @default(false) // Wurde bei Provider angelegt?\n provisionedAt DateTime? // Wann wurde provisioniert?\n provisionError String? @db.Text // Fehlermeldung falls Provisionierung fehlschlug\n\n // Mailbox-Zugangsdaten (für IMAP/SMTP-Zugang)\n hasMailbox Boolean @default(false) // Hat echte Mailbox (nicht nur Weiterleitung)?\n emailPasswordEncrypted String? // Verschlüsseltes Mailbox-Passwort (AES-256-GCM)\n\n contracts Contract[] // Verträge die diese E-Mail als Benutzername verwenden\n cachedEmails CachedEmail[] // Gecachte E-Mails aus dieser Mailbox\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CACHED EMAILS (E-Mail-Client) ====================\n\nenum EmailFolder {\n INBOX\n SENT\n}\n\nmodel CachedEmail {\n id Int @id @default(autoincrement())\n stressfreiEmailId Int\n stressfreiEmail StressfreiEmail @relation(fields: [stressfreiEmailId], references: [id], onDelete: Cascade)\n\n // Ordner (Posteingang oder Gesendet)\n folder EmailFolder @default(INBOX)\n\n // IMAP-Identifikation\n messageId String // RFC 5322 Message-ID\n uid Int // IMAP UID (für Synchronisierung, bei SENT = 0)\n\n // E-Mail-Metadaten\n subject String?\n fromAddress String\n fromName String?\n toAddresses String @db.Text // JSON Array\n ccAddresses String? @db.Text // JSON Array\n receivedAt DateTime\n\n // Inhalt\n textBody String? @db.LongText\n htmlBody String? @db.LongText\n hasAttachments Boolean @default(false)\n attachmentNames String? @db.Text // JSON Array\n\n // Vertragszuordnung\n contractId Int?\n contract Contract? @relation(fields: [contractId], references: [id], onDelete: SetNull)\n assignedAt DateTime?\n assignedBy Int? // User ID der die Zuordnung gemacht hat\n isAutoAssigned Boolean @default(false) // true = automatisch beim Senden aus Vertrag\n\n // Flags\n isRead Boolean @default(false)\n isStarred Boolean @default(false)\n\n // Papierkorb\n isDeleted Boolean @default(false) // Im Papierkorb?\n deletedAt DateTime? // Wann gelöscht?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([stressfreiEmailId, messageId, folder]) // Folder hinzugefügt: gleiche MessageID kann in INBOX und SENT existieren\n @@index([contractId])\n @@index([stressfreiEmailId, folder, receivedAt])\n @@index([stressfreiEmailId, isDeleted]) // Für Papierkorb-Abfragen\n}\n\n// ==================== METERS (Energy) ====================\n\nenum MeterType {\n ELECTRICITY\n GAS\n}\n\nmodel Meter {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n meterNumber String\n type MeterType\n location String?\n isActive Boolean @default(true)\n readings MeterReading[]\n energyDetails EnergyContractDetails[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel MeterReading {\n id Int @id @default(autoincrement())\n meterId Int\n meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade)\n readingDate DateTime\n value Float\n unit String @default(\"kWh\")\n notes String?\n // Meldung & Übertragung\n reportedBy String? // Wer hat gemeldet? (E-Mail des Portal-Kunden oder Mitarbeiter)\n status MeterReadingStatus @default(RECORDED)\n transferredAt DateTime? // Wann wurde der Stand an den Anbieter übertragen?\n transferredBy String? // Wer hat übertragen?\n createdAt DateTime @default(now())\n}\n\nenum MeterReadingStatus {\n RECORDED // Erfasst (vom Mitarbeiter)\n REPORTED // Vom Kunden gemeldet (Portal)\n TRANSFERRED // An Anbieter übertragen\n}\n\n// ==================== SALES PLATFORMS ====================\n\nmodel SalesPlatform {\n id Int @id @default(autoincrement())\n name String @unique\n contactInfo String? @db.Text\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CANCELLATION PERIODS ====================\n\nmodel CancellationPeriod {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"14T\", \"1M\", \"3M\", \"12M\", \"1J\"\n description String // z.B. \"14 Tage\", \"1 Monat\", \"3 Monate\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT DURATIONS ====================\n\nmodel ContractDuration {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"12M\", \"24M\", \"1J\", \"2J\"\n description String // z.B. \"12 Monate\", \"24 Monate\", \"1 Jahr\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== PROVIDERS (Anbieter) ====================\n\nmodel Provider {\n id Int @id @default(autoincrement())\n name String @unique // Anbietername\n portalUrl String? // Kundenkontourl (Login-Seite)\n usernameFieldName String? // Benutzernamefeld (z.B. \"email\", \"username\")\n passwordFieldName String? // Kennwortfeld (z.B. \"password\", \"pwd\")\n isActive Boolean @default(true)\n tariffs Tariff[]\n contracts Contract[]\n previousContracts Contract[] @relation(\"PreviousProvider\") // Verträge wo dieser Provider Altanbieter ist\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TARIFFS (Tarife) ====================\n\nmodel Tariff {\n id Int @id @default(autoincrement())\n providerId Int\n provider Provider @relation(fields: [providerId], references: [id], onDelete: Cascade)\n name String // Tarifname\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([providerId, name]) // Eindeutiger Tarif pro Anbieter\n}\n\n// ==================== CONTRACT CATEGORIES ====================\n\nmodel ContractCategory {\n id Int @id @default(autoincrement())\n code String @unique // Technischer Code (z.B. ELECTRICITY, GAS)\n name String // Anzeigename (z.B. Strom, Gas)\n icon String? // Icon-Name für UI (z.B. \"Zap\", \"Flame\")\n color String? // Farbe für UI (z.B. \"#FFC107\")\n sortOrder Int @default(0)\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACTS ====================\n\n// Legacy Enum - wird durch ContractCategory ersetzt\nenum ContractType {\n ELECTRICITY\n GAS\n DSL\n CABLE\n FIBER\n MOBILE\n TV\n CAR_INSURANCE\n}\n\nenum ContractStatus {\n DRAFT\n PENDING\n ACTIVE\n CANCELLED\n EXPIRED\n DEACTIVATED\n}\n\nmodel Contract {\n id Int @id @default(autoincrement())\n contractNumber String @unique\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type ContractType\n status ContractStatus @default(DRAFT)\n\n // Neue konfigurierbare Kategorie (ersetzt langfristig das type-Enum)\n contractCategoryId Int?\n contractCategory ContractCategory? @relation(fields: [contractCategoryId], references: [id])\n\n // Lieferadresse\n addressId Int?\n address Address? @relation(\"DeliveryAddress\", fields: [addressId], references: [id])\n\n // Rechnungsadresse (falls leer, wird Lieferadresse verwendet)\n billingAddressId Int?\n billingAddress Address? @relation(\"BillingAddress\", fields: [billingAddressId], references: [id])\n\n bankCardId Int?\n bankCard BankCard? @relation(fields: [bankCardId], references: [id])\n\n identityDocumentId Int?\n identityDocument IdentityDocument? @relation(fields: [identityDocumentId], references: [id])\n\n salesPlatformId Int?\n salesPlatform SalesPlatform? @relation(fields: [salesPlatformId], references: [id])\n\n cancellationPeriodId Int?\n cancellationPeriod CancellationPeriod? @relation(fields: [cancellationPeriodId], references: [id])\n\n contractDurationId Int?\n contractDuration ContractDuration? @relation(fields: [contractDurationId], references: [id])\n\n previousContractId Int? @unique\n previousContract Contract? @relation(\"ContractHistory\", fields: [previousContractId], references: [id])\n followUpContract Contract? @relation(\"ContractHistory\")\n\n // Altanbieter-Daten (nur wenn kein Vorgängervertrag existiert)\n previousProviderId Int?\n previousProvider Provider? @relation(\"PreviousProvider\", fields: [previousProviderId], references: [id])\n previousCustomerNumber String? // Kundennummer beim Altanbieter\n previousContractNumber String? // Vertragsnummer beim Altanbieter\n\n // Anbieter & Tarif (neue Verknüpfung)\n providerId Int?\n provider Provider? @relation(fields: [providerId], references: [id])\n tariffId Int?\n tariff Tariff? @relation(fields: [tariffId], references: [id])\n\n // Legacy-Felder (für Abwärtskompatibilität)\n providerName String?\n tariffName String?\n customerNumberAtProvider String?\n contractNumberAtProvider String? // Vertragsnummer beim Anbieter\n priceFirst12Months String? // Preis erste 12 Monate\n priceFrom13Months String? // Preis ab 13. Monat\n priceAfter24Months String? // Preis nach 24 Monaten\n\n startDate DateTime?\n endDate DateTime? // Wird aus startDate + contractDuration berechnet\n commission Float?\n\n // Kündigungsdokumente\n cancellationLetterPath String? // Kündigungsschreiben PDF\n cancellationConfirmationPath String? // Kündigungsbestätigung PDF\n cancellationLetterOptionsPath String? // Kündigungsschreiben Optionen PDF\n cancellationConfirmationOptionsPath String? // Kündigungsbestätigung Optionen PDF\n\n // Kündigungsdaten\n cancellationConfirmationDate DateTime? // Kündigungsbestätigungsdatum\n cancellationConfirmationOptionsDate DateTime? // Kündigungsbestätigungsoptionendatum\n wasSpecialCancellation Boolean @default(false) // Wurde sondergekündigt?\n\n portalUsername String?\n portalPasswordEncrypted String?\n\n // Stressfrei-Wechseln E-Mail als Benutzername (Alternative zu portalUsername)\n stressfreiEmailId Int?\n stressfreiEmail StressfreiEmail? @relation(fields: [stressfreiEmailId], references: [id])\n\n // Snooze: Vertrag zurückstellen bis Datum (für Cockpit)\n nextReviewDate DateTime? // Erneute Prüfung am\n\n notes String? @db.Text\n\n energyDetails EnergyContractDetails?\n internetDetails InternetContractDetails?\n mobileDetails MobileContractDetails?\n tvDetails TvContractDetails?\n carInsuranceDetails CarInsuranceDetails?\n\n tasks ContractTask[]\n assignedEmails CachedEmail[] // Zugeordnete E-Mails aus dem E-Mail-Client\n historyEntries ContractHistoryEntry[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT HISTORY ====================\n\nmodel ContractHistoryEntry {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String // Kurzbeschreibung (z.B. \"Folgevertrag erstellt\", \"kWh auf 18000 erhöht\")\n description String? @db.Text // Längere Beschreibung (optional)\n isAutomatic Boolean @default(false) // true = automatisch erstellt, false = manuell\n createdBy String // E-Mail des Erstellers\n createdAt DateTime @default(now())\n}\n\n// ==================== CONTRACT TASKS ====================\n\nenum ContractTaskStatus {\n OPEN\n COMPLETED\n}\n\nmodel ContractTask {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String\n description String? @db.Text\n status ContractTaskStatus @default(OPEN)\n visibleInPortal Boolean @default(false)\n createdBy String? // Name des Erstellers\n completedAt DateTime?\n subtasks ContractTaskSubtask[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel ContractTaskSubtask {\n id Int @id @default(autoincrement())\n taskId Int\n task ContractTask @relation(fields: [taskId], references: [id], onDelete: Cascade)\n title String\n status ContractTaskStatus @default(OPEN)\n createdBy String?\n completedAt DateTime?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== ENERGY CONTRACT DETAILS ====================\n\nenum InvoiceType {\n INTERIM // Zwischenrechnung\n FINAL // Schlussrechnung\n NOT_AVAILABLE // Rechnung nicht mehr zu bekommen\n}\n\nmodel EnergyContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n meterId Int?\n meter Meter? @relation(fields: [meterId], references: [id])\n maloId String? // Marktlokations-ID\n annualConsumption Float? // kWh für Strom, m³ für Gas\n annualConsumptionKwh Float? // kWh für Gas (zusätzlich zu m³)\n basePrice Float? // €/Monat\n unitPrice Float? // €/kWh (Arbeitspreis)\n bonus Float?\n previousProviderName String?\n previousCustomerNumber String?\n invoices Invoice[] // Rechnungen\n}\n\nmodel Invoice {\n id Int @id @default(autoincrement())\n energyContractDetailsId Int\n energyContractDetails EnergyContractDetails @relation(fields: [energyContractDetailsId], references: [id], onDelete: Cascade)\n invoiceDate DateTime\n invoiceType InvoiceType\n documentPath String? // Pflicht, außer bei NOT_AVAILABLE\n notes String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([energyContractDetailsId])\n}\n\n// ==================== INTERNET CONTRACT DETAILS ====================\n\nmodel InternetContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n downloadSpeed Int?\n uploadSpeed Int?\n routerModel String?\n routerSerialNumber String?\n installationDate DateTime?\n // Internet-Zugangsdaten\n internetUsername String?\n internetPasswordEncrypted String? // Verschlüsselt gespeichert\n // Glasfaser-spezifisch\n homeId String?\n // Vodafone DSL/Kabel spezifisch\n activationCode String?\n phoneNumbers PhoneNumber[]\n}\n\nmodel PhoneNumber {\n id Int @id @default(autoincrement())\n internetContractDetailsId Int\n internetDetails InternetContractDetails @relation(fields: [internetContractDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String\n isMain Boolean @default(false)\n // SIP-Zugangsdaten\n sipUsername String?\n sipPasswordEncrypted String? // Verschlüsselt gespeichert\n sipServer String?\n}\n\n// ==================== MOBILE CONTRACT DETAILS ====================\n\nmodel MobileContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n requiresMultisim Boolean @default(false) // Multisim erforderlich?\n dataVolume Float?\n includedMinutes Int?\n includedSMS Int?\n deviceModel String?\n deviceImei String?\n simCards SimCard[]\n // Legacy-Felder (für Abwärtskompatibilität, werden durch simCards ersetzt)\n phoneNumber String?\n simCardNumber String?\n}\n\nmodel SimCard {\n id Int @id @default(autoincrement())\n mobileDetailsId Int\n mobileDetails MobileContractDetails @relation(fields: [mobileDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String? // Rufnummer\n simCardNumber String? // SIM-Kartennummer\n pin String? // PIN (verschlüsselt gespeichert)\n puk String? // PUK (verschlüsselt gespeichert)\n isMultisim Boolean @default(false) // Ist dies eine Multisim-Karte?\n isMain Boolean @default(false) // Ist dies die Hauptkarte?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TV CONTRACT DETAILS ====================\n\nmodel TvContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n receiverModel String?\n smartcardNumber String?\n package String?\n}\n\n// ==================== CAR INSURANCE DETAILS ====================\n\nenum InsuranceType {\n LIABILITY\n PARTIAL\n FULL\n}\n\nmodel CarInsuranceDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n licensePlate String?\n hsn String?\n tsn String?\n vin String?\n vehicleType String?\n firstRegistration DateTime?\n noClaimsClass String?\n insuranceType InsuranceType @default(LIABILITY)\n deductiblePartial Float?\n deductibleFull Float?\n policyNumber String?\n previousInsurer String?\n}\n\n// ==================== AUDIT LOGGING (DSGVO) ====================\n\nenum AuditAction {\n CREATE\n READ\n UPDATE\n DELETE\n EXPORT // DSGVO-Datenexport\n ANONYMIZE // Recht auf Vergessenwerden\n LOGIN\n LOGOUT\n LOGIN_FAILED\n}\n\nenum AuditSensitivity {\n LOW // Einstellungen, Plattformen\n MEDIUM // Verträge, Tarife\n HIGH // Kundendaten, Bankdaten\n CRITICAL // Authentifizierung, Ausweisdokumente\n}\n\nmodel AuditLog {\n id Int @id @default(autoincrement())\n\n // Wer\n userId Int? // Staff User (null bei Kundenportal/System)\n userEmail String\n userRole String? @db.Text // Rolle zum Zeitpunkt der Aktion\n customerId Int? // Bei Kundenportal-Zugriff\n isCustomerPortal Boolean @default(false)\n\n // Was\n action AuditAction\n sensitivity AuditSensitivity @default(MEDIUM)\n\n // Welche Ressource\n resourceType String // Prisma Model Name\n resourceId String? // ID des Datensatzes\n resourceLabel String? // Lesbare Bezeichnung\n\n // Kontext\n endpoint String // API-Pfad\n httpMethod String // GET, POST, PUT, DELETE\n ipAddress String\n userAgent String? @db.Text\n\n // Änderungen (JSON, bei sensiblen Daten verschlüsselt)\n changesBefore String? @db.LongText\n changesAfter String? @db.LongText\n changesEncrypted Boolean @default(false)\n\n // DSGVO\n dataSubjectId Int? // Betroffene Person (für Reports)\n legalBasis String? // Rechtsgrundlage\n\n // Status\n success Boolean @default(true)\n errorMessage String? @db.Text\n durationMs Int?\n\n // Unveränderlichkeit (Hash-Kette)\n createdAt DateTime @default(now())\n hash String? // SHA-256 Hash des Eintrags\n previousHash String? // Hash des vorherigen Eintrags\n\n @@index([userId])\n @@index([customerId])\n @@index([resourceType, resourceId])\n @@index([dataSubjectId])\n @@index([action])\n @@index([createdAt])\n @@index([sensitivity])\n}\n\n// ==================== CONSENT MANAGEMENT (DSGVO) ====================\n\nenum ConsentType {\n DATA_PROCESSING // Grundlegende Datenverarbeitung\n MARKETING_EMAIL // E-Mail-Marketing\n MARKETING_PHONE // Telefon-Marketing\n DATA_SHARING_PARTNER // Weitergabe an Partner\n}\n\nenum ConsentStatus {\n GRANTED\n WITHDRAWN\n PENDING\n}\n\nmodel CustomerConsent {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n\n consentType ConsentType\n status ConsentStatus @default(PENDING)\n\n grantedAt DateTime?\n withdrawnAt DateTime?\n source String? // \"portal\", \"telefon\", \"papier\", \"email\"\n documentPath String? // Unterschriebenes Dokument\n version String? // Version der Datenschutzerklärung\n ipAddress String?\n\n createdBy String // User der die Einwilligung erfasst hat\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, consentType])\n @@index([customerId])\n @@index([consentType])\n @@index([status])\n}\n\n// ==================== DATA DELETION REQUESTS (DSGVO) ====================\n\nenum DeletionRequestStatus {\n PENDING // Anfrage eingegangen\n IN_PROGRESS // Wird bearbeitet\n COMPLETED // Abgeschlossen\n PARTIALLY_COMPLETED // Teildaten behalten (rechtliche Gründe)\n REJECTED // Abgelehnt\n}\n\nmodel DataDeletionRequest {\n id Int @id @default(autoincrement())\n customerId Int\n\n status DeletionRequestStatus @default(PENDING)\n requestedAt DateTime @default(now())\n requestSource String // \"email\", \"portal\", \"brief\"\n requestedBy String // Wer hat angefragt\n\n processedAt DateTime?\n processedBy String? // Mitarbeiter der bearbeitet hat\n\n deletedData String? @db.LongText // JSON: Was wurde gelöscht\n retainedData String? @db.LongText // JSON: Was wurde behalten + Grund\n retentionReason String? @db.Text // Begründung für Aufbewahrung\n\n proofDocument String? // Pfad zum Löschnachweis-PDF\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([customerId])\n @@index([status])\n @@index([requestedAt])\n}\n\n// ==================== AUDIT RETENTION POLICIES ====================\n\nmodel AuditRetentionPolicy {\n id Int @id @default(autoincrement())\n resourceType String // \"*\" für Standard, oder spezifischer Model-Name\n sensitivity AuditSensitivity?\n retentionDays Int // Aufbewahrungsfrist in Tagen (z.B. 3650 = 10 Jahre)\n description String?\n legalBasis String? // Gesetzliche Grundlage (z.B. \"AO §147\", \"HGB §257\")\n isActive Boolean @default(true)\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([resourceType, sensitivity])\n}\n", + "inlineSchemaHash": "63bbf34a125be87986e47fb5fb85acd2762dfb44da1ec90d4d1c15dc2c2a2083", "copyEngine": true } config.dirname = '/' -config.runtimeDataModel = JSON.parse("{\"models\":{\"AppSetting\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"key\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"User\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"password\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tokenInvalidatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Role\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissions\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"users\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Permission\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resource\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"action\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[[\"resource\",\"action\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"resource\",\"action\"]}],\"isGenerated\":false},\"RolePermission\":{\"dbName\":null,\"fields\":[{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissionId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permission\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Permission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[\"permissionId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"roleId\",\"permissionId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"UserRole\":{\"dbName\":null,\"fields\":[{\"name\":\"userId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[\"userId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"userId\",\"roleId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Customer\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"CustomerType\",\"default\":\"PRIVATE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salutation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"companyName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"foundingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthPlace\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phone\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobile\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taxNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"businessRegistrationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"privacyPolicyPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEnabled\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalLastLogin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addresses\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocuments\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meters\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representingFor\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representedBy\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CustomerRepresentative\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representativeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representative\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[\"representativeId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"representativeId\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"representativeId\"]}],\"isGenerated\":false},\"Address\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"AddressType\",\"default\":\"DELIVERY_RESIDENCE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"street\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"houseNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"postalCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"city\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"country\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"Deutschland\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsDelivery\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsBilling\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"BankCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"accountHolder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"iban\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"IdentityDocument\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DocumentType\",\"default\":\"ID_CARD\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issuingAuthority\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseClasses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseIssueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EmailProviderConfig\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EmailProviderType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"username\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"domain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"defaultForwardEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":993,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":465,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"allowSelfSignedCerts\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"StressfreiEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"platform\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isProvisioned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionError\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasMailbox\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"emailPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cachedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CachedEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"folder\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"EmailFolder\",\"default\":\"INBOX\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"messageId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uid\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subject\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"toAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ccAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receivedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"textBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"htmlBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasAttachments\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"attachmentNames\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"SetNull\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutoAssigned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isRead\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isStarred\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDeleted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deletedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"stressfreiEmailId\",\"messageId\",\"folder\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"stressfreiEmailId\",\"messageId\",\"folder\"]}],\"isGenerated\":false},\"Meter\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"location\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readings\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterReading\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MeterReading\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unit\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"kWh\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SalesPlatform\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contactInfo\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CancellationPeriod\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractDuration\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Provider\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"usernameFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffs\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Tariff\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"providerId\",\"name\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"providerId\",\"name\"]}],\"isGenerated\":false},\"ContractCategory\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"icon\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"color\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":0,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Contract\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractStatus\",\"default\":\"DRAFT\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategoryId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategory\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractCategory\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[\"contractCategoryId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"address\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[\"addressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddress\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[\"billingAddressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCardId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCard\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[\"bankCardId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocumentId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocument\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[\"identityDocumentId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatformId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatform\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SalesPlatform\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[\"salesPlatformId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriodId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriod\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CancellationPeriod\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[\"cancellationPeriodId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDurationId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDuration\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractDuration\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[\"contractDurationId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[\"previousContractId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"followUpContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProvider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[\"previousProviderId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariff\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[\"tariffId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFirst12Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFrom13Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceAfter24Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"startDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"endDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commission\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"wasSpecialCancellation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"nextReviewDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tvDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"TvContractDetails\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"carInsuranceDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CarInsuranceDetails\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"historyEntries\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractHistoryEntry\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractHistoryEntry\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutomatic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"visibleInPortal\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subtasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTaskSubtask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTaskSubtask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taskId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"task\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[\"taskId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EnergyContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"maloId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumption\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumptionKwh\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"basePrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unitPrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bonus\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoices\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Invoice\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Invoice\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[\"energyContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InvoiceType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"InternetContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"downloadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uploadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerSerialNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"installationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"homeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"activationCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumbers\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"PhoneNumber\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"PhoneNumber\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[\"internetContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MobileContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requiresMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"dataVolume\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedMinutes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedSMS\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceImei\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SimCard\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SimCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[\"mobileDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"pin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"puk\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"TvContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receiverModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smartcardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"package\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CarInsuranceDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licensePlate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vehicleType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstRegistration\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"noClaimsClass\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"insuranceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"InsuranceType\",\"default\":\"LIABILITY\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductiblePartial\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductibleFull\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"policyNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousInsurer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false}},\"enums\":{\"CustomerType\":{\"values\":[{\"name\":\"PRIVATE\",\"dbName\":null},{\"name\":\"BUSINESS\",\"dbName\":null}],\"dbName\":null},\"AddressType\":{\"values\":[{\"name\":\"DELIVERY_RESIDENCE\",\"dbName\":null},{\"name\":\"BILLING\",\"dbName\":null}],\"dbName\":null},\"DocumentType\":{\"values\":[{\"name\":\"ID_CARD\",\"dbName\":null},{\"name\":\"PASSPORT\",\"dbName\":null},{\"name\":\"DRIVERS_LICENSE\",\"dbName\":null},{\"name\":\"OTHER\",\"dbName\":null}],\"dbName\":null},\"EmailProviderType\":{\"values\":[{\"name\":\"PLESK\",\"dbName\":null},{\"name\":\"CPANEL\",\"dbName\":null},{\"name\":\"DIRECTADMIN\",\"dbName\":null}],\"dbName\":null},\"MailEncryption\":{\"values\":[{\"name\":\"SSL\",\"dbName\":null},{\"name\":\"STARTTLS\",\"dbName\":null},{\"name\":\"NONE\",\"dbName\":null}],\"dbName\":null},\"EmailFolder\":{\"values\":[{\"name\":\"INBOX\",\"dbName\":null},{\"name\":\"SENT\",\"dbName\":null}],\"dbName\":null},\"MeterType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null}],\"dbName\":null},\"ContractType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null},{\"name\":\"DSL\",\"dbName\":null},{\"name\":\"CABLE\",\"dbName\":null},{\"name\":\"FIBER\",\"dbName\":null},{\"name\":\"MOBILE\",\"dbName\":null},{\"name\":\"TV\",\"dbName\":null},{\"name\":\"CAR_INSURANCE\",\"dbName\":null}],\"dbName\":null},\"ContractStatus\":{\"values\":[{\"name\":\"DRAFT\",\"dbName\":null},{\"name\":\"PENDING\",\"dbName\":null},{\"name\":\"ACTIVE\",\"dbName\":null},{\"name\":\"CANCELLED\",\"dbName\":null},{\"name\":\"EXPIRED\",\"dbName\":null},{\"name\":\"DEACTIVATED\",\"dbName\":null}],\"dbName\":null},\"ContractTaskStatus\":{\"values\":[{\"name\":\"OPEN\",\"dbName\":null},{\"name\":\"COMPLETED\",\"dbName\":null}],\"dbName\":null},\"InvoiceType\":{\"values\":[{\"name\":\"INTERIM\",\"dbName\":null},{\"name\":\"FINAL\",\"dbName\":null},{\"name\":\"NOT_AVAILABLE\",\"dbName\":null}],\"dbName\":null},\"InsuranceType\":{\"values\":[{\"name\":\"LIABILITY\",\"dbName\":null},{\"name\":\"PARTIAL\",\"dbName\":null},{\"name\":\"FULL\",\"dbName\":null}],\"dbName\":null}},\"types\":{}}") +config.runtimeDataModel = JSON.parse("{\"models\":{\"EmailLog\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"toAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subject\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"context\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"triggeredBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpEncryption\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpUser\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"success\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Boolean\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"messageId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"errorMessage\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpResponse\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sentAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"AppSetting\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"key\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"User\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"password\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tokenInvalidatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"whatsappNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"telegramUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"signalNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Role\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissions\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"users\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Permission\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resource\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"action\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[[\"resource\",\"action\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"resource\",\"action\"]}],\"isGenerated\":false},\"RolePermission\":{\"dbName\":null,\"fields\":[{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissionId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permission\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Permission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[\"permissionId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"roleId\",\"permissionId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"UserRole\":{\"dbName\":null,\"fields\":[{\"name\":\"userId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[\"userId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"userId\",\"roleId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Customer\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"CustomerType\",\"default\":\"PRIVATE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salutation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"companyName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"foundingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthPlace\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phone\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobile\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taxNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"businessRegistrationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"privacyPolicyPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"consentHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEnabled\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalLastLogin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addresses\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocuments\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meters\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representingFor\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representedBy\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"authorizationsGiven\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RepresentativeAuthorization\",\"relationName\":\"AuthorizationCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"authorizationsReceived\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RepresentativeAuthorization\",\"relationName\":\"AuthorizationRepresentative\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"consents\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerConsent\",\"relationName\":\"CustomerToCustomerConsent\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CustomerRepresentative\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representativeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representative\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[\"representativeId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"representativeId\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"representativeId\"]}],\"isGenerated\":false},\"RepresentativeAuthorization\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AuthorizationCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representativeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representative\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AuthorizationRepresentative\",\"relationFromFields\":[\"representativeId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isGranted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"grantedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"withdrawnAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"source\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"representativeId\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"representativeId\"]}],\"isGenerated\":false},\"Address\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"AddressType\",\"default\":\"DELIVERY_RESIDENCE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"street\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"houseNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"postalCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"city\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"country\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"Deutschland\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsDelivery\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsBilling\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"BankCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"accountHolder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"iban\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"IdentityDocument\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DocumentType\",\"default\":\"ID_CARD\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issuingAuthority\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseClasses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseIssueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EmailProviderConfig\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EmailProviderType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"username\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"domain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"defaultForwardEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":993,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":465,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"allowSelfSignedCerts\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"systemEmailAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"systemEmailPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"StressfreiEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"platform\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isProvisioned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionError\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasMailbox\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"emailPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cachedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CachedEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"folder\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"EmailFolder\",\"default\":\"INBOX\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"messageId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uid\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subject\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"toAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ccAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receivedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"textBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"htmlBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasAttachments\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"attachmentNames\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"SetNull\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutoAssigned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isRead\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isStarred\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDeleted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deletedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"stressfreiEmailId\",\"messageId\",\"folder\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"stressfreiEmailId\",\"messageId\",\"folder\"]}],\"isGenerated\":false},\"Meter\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"location\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readings\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterReading\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MeterReading\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unit\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"kWh\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"reportedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MeterReadingStatus\",\"default\":\"RECORDED\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"transferredAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"transferredBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SalesPlatform\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contactInfo\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CancellationPeriod\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractDuration\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Provider\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"usernameFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffs\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Tariff\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"providerId\",\"name\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"providerId\",\"name\"]}],\"isGenerated\":false},\"ContractCategory\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"icon\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"color\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":0,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Contract\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractStatus\",\"default\":\"DRAFT\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategoryId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategory\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractCategory\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[\"contractCategoryId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"address\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[\"addressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddress\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[\"billingAddressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCardId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCard\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[\"bankCardId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocumentId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocument\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[\"identityDocumentId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatformId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatform\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SalesPlatform\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[\"salesPlatformId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriodId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriod\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CancellationPeriod\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[\"cancellationPeriodId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDurationId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDuration\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractDuration\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[\"contractDurationId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[\"previousContractId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"followUpContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProvider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[\"previousProviderId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariff\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[\"tariffId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFirst12Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFrom13Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceAfter24Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"startDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"endDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commission\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"wasSpecialCancellation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"nextReviewDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tvDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"TvContractDetails\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"carInsuranceDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CarInsuranceDetails\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"historyEntries\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractHistoryEntry\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractHistoryEntry\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutomatic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"visibleInPortal\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subtasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTaskSubtask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTaskSubtask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taskId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"task\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[\"taskId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EnergyContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"maloId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumption\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumptionKwh\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"basePrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unitPrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bonus\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoices\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Invoice\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Invoice\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[\"energyContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InvoiceType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"InternetContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"downloadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uploadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerSerialNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"installationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"homeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"activationCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumbers\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"PhoneNumber\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"PhoneNumber\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[\"internetContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MobileContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requiresMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"dataVolume\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedMinutes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedSMS\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceImei\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SimCard\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SimCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[\"mobileDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"pin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"puk\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"TvContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receiverModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smartcardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"package\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CarInsuranceDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licensePlate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vehicleType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstRegistration\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"noClaimsClass\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"insuranceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"InsuranceType\",\"default\":\"LIABILITY\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductiblePartial\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductibleFull\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"policyNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousInsurer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"AuditLog\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userRole\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isCustomerPortal\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"action\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"AuditAction\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sensitivity\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"AuditSensitivity\",\"default\":\"MEDIUM\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceLabel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"endpoint\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"httpMethod\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ipAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userAgent\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"changesBefore\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"changesAfter\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"changesEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"dataSubjectId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"legalBasis\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"success\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"errorMessage\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"durationMs\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CustomerConsent\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToCustomerConsent\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"consentType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ConsentType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ConsentStatus\",\"default\":\"PENDING\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"grantedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"withdrawnAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"source\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"version\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ipAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"consentType\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"consentType\"]}],\"isGenerated\":false},\"DataDeletionRequest\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DeletionRequestStatus\",\"default\":\"PENDING\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requestedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requestSource\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requestedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"processedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"processedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deletedData\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"retainedData\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"retentionReason\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"proofDocument\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"AuditRetentionPolicy\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sensitivity\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"AuditSensitivity\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"retentionDays\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"legalBasis\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"resourceType\",\"sensitivity\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"resourceType\",\"sensitivity\"]}],\"isGenerated\":false}},\"enums\":{\"CustomerType\":{\"values\":[{\"name\":\"PRIVATE\",\"dbName\":null},{\"name\":\"BUSINESS\",\"dbName\":null}],\"dbName\":null},\"AddressType\":{\"values\":[{\"name\":\"DELIVERY_RESIDENCE\",\"dbName\":null},{\"name\":\"BILLING\",\"dbName\":null}],\"dbName\":null},\"DocumentType\":{\"values\":[{\"name\":\"ID_CARD\",\"dbName\":null},{\"name\":\"PASSPORT\",\"dbName\":null},{\"name\":\"DRIVERS_LICENSE\",\"dbName\":null},{\"name\":\"OTHER\",\"dbName\":null}],\"dbName\":null},\"EmailProviderType\":{\"values\":[{\"name\":\"PLESK\",\"dbName\":null},{\"name\":\"CPANEL\",\"dbName\":null},{\"name\":\"DIRECTADMIN\",\"dbName\":null}],\"dbName\":null},\"MailEncryption\":{\"values\":[{\"name\":\"SSL\",\"dbName\":null},{\"name\":\"STARTTLS\",\"dbName\":null},{\"name\":\"NONE\",\"dbName\":null}],\"dbName\":null},\"EmailFolder\":{\"values\":[{\"name\":\"INBOX\",\"dbName\":null},{\"name\":\"SENT\",\"dbName\":null}],\"dbName\":null},\"MeterType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null}],\"dbName\":null},\"MeterReadingStatus\":{\"values\":[{\"name\":\"RECORDED\",\"dbName\":null},{\"name\":\"REPORTED\",\"dbName\":null},{\"name\":\"TRANSFERRED\",\"dbName\":null}],\"dbName\":null},\"ContractType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null},{\"name\":\"DSL\",\"dbName\":null},{\"name\":\"CABLE\",\"dbName\":null},{\"name\":\"FIBER\",\"dbName\":null},{\"name\":\"MOBILE\",\"dbName\":null},{\"name\":\"TV\",\"dbName\":null},{\"name\":\"CAR_INSURANCE\",\"dbName\":null}],\"dbName\":null},\"ContractStatus\":{\"values\":[{\"name\":\"DRAFT\",\"dbName\":null},{\"name\":\"PENDING\",\"dbName\":null},{\"name\":\"ACTIVE\",\"dbName\":null},{\"name\":\"CANCELLED\",\"dbName\":null},{\"name\":\"EXPIRED\",\"dbName\":null},{\"name\":\"DEACTIVATED\",\"dbName\":null}],\"dbName\":null},\"ContractTaskStatus\":{\"values\":[{\"name\":\"OPEN\",\"dbName\":null},{\"name\":\"COMPLETED\",\"dbName\":null}],\"dbName\":null},\"InvoiceType\":{\"values\":[{\"name\":\"INTERIM\",\"dbName\":null},{\"name\":\"FINAL\",\"dbName\":null},{\"name\":\"NOT_AVAILABLE\",\"dbName\":null}],\"dbName\":null},\"InsuranceType\":{\"values\":[{\"name\":\"LIABILITY\",\"dbName\":null},{\"name\":\"PARTIAL\",\"dbName\":null},{\"name\":\"FULL\",\"dbName\":null}],\"dbName\":null},\"AuditAction\":{\"values\":[{\"name\":\"CREATE\",\"dbName\":null},{\"name\":\"READ\",\"dbName\":null},{\"name\":\"UPDATE\",\"dbName\":null},{\"name\":\"DELETE\",\"dbName\":null},{\"name\":\"EXPORT\",\"dbName\":null},{\"name\":\"ANONYMIZE\",\"dbName\":null},{\"name\":\"LOGIN\",\"dbName\":null},{\"name\":\"LOGOUT\",\"dbName\":null},{\"name\":\"LOGIN_FAILED\",\"dbName\":null}],\"dbName\":null},\"AuditSensitivity\":{\"values\":[{\"name\":\"LOW\",\"dbName\":null},{\"name\":\"MEDIUM\",\"dbName\":null},{\"name\":\"HIGH\",\"dbName\":null},{\"name\":\"CRITICAL\",\"dbName\":null}],\"dbName\":null},\"ConsentType\":{\"values\":[{\"name\":\"DATA_PROCESSING\",\"dbName\":null},{\"name\":\"MARKETING_EMAIL\",\"dbName\":null},{\"name\":\"MARKETING_PHONE\",\"dbName\":null},{\"name\":\"DATA_SHARING_PARTNER\",\"dbName\":null}],\"dbName\":null},\"ConsentStatus\":{\"values\":[{\"name\":\"GRANTED\",\"dbName\":null},{\"name\":\"WITHDRAWN\",\"dbName\":null},{\"name\":\"PENDING\",\"dbName\":null}],\"dbName\":null},\"DeletionRequestStatus\":{\"values\":[{\"name\":\"PENDING\",\"dbName\":null},{\"name\":\"IN_PROGRESS\",\"dbName\":null},{\"name\":\"COMPLETED\",\"dbName\":null},{\"name\":\"PARTIALLY_COMPLETED\",\"dbName\":null},{\"name\":\"REJECTED\",\"dbName\":null}],\"dbName\":null}},\"types\":{}}") defineDmmfProperty(exports.Prisma, config.runtimeDataModel) config.engineWasm = undefined diff --git a/backend/node_modules/.prisma/client/index-browser.js b/backend/node_modules/.prisma/client/index-browser.js index 5dc32177..20470a77 100644 --- a/backend/node_modules/.prisma/client/index-browser.js +++ b/backend/node_modules/.prisma/client/index-browser.js @@ -122,6 +122,25 @@ exports.Prisma.TransactionIsolationLevel = makeStrictEnum({ Serializable: 'Serializable' }); +exports.Prisma.EmailLogScalarFieldEnum = { + id: 'id', + fromAddress: 'fromAddress', + toAddress: 'toAddress', + subject: 'subject', + context: 'context', + customerId: 'customerId', + triggeredBy: 'triggeredBy', + smtpServer: 'smtpServer', + smtpPort: 'smtpPort', + smtpEncryption: 'smtpEncryption', + smtpUser: 'smtpUser', + success: 'success', + messageId: 'messageId', + errorMessage: 'errorMessage', + smtpResponse: 'smtpResponse', + sentAt: 'sentAt' +}; + exports.Prisma.AppSettingScalarFieldEnum = { id: 'id', key: 'key', @@ -138,6 +157,9 @@ exports.Prisma.UserScalarFieldEnum = { lastName: 'lastName', isActive: 'isActive', tokenInvalidatedAt: 'tokenInvalidatedAt', + whatsappNumber: 'whatsappNumber', + telegramUsername: 'telegramUsername', + signalNumber: 'signalNumber', customerId: 'customerId', createdAt: 'createdAt', updatedAt: 'updatedAt' @@ -186,6 +208,7 @@ exports.Prisma.CustomerScalarFieldEnum = { commercialRegisterPath: 'commercialRegisterPath', commercialRegisterNumber: 'commercialRegisterNumber', privacyPolicyPath: 'privacyPolicyPath', + consentHash: 'consentHash', notes: 'notes', portalEnabled: 'portalEnabled', portalEmail: 'portalEmail', @@ -206,6 +229,20 @@ exports.Prisma.CustomerRepresentativeScalarFieldEnum = { updatedAt: 'updatedAt' }; +exports.Prisma.RepresentativeAuthorizationScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + representativeId: 'representativeId', + isGranted: 'isGranted', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + notes: 'notes', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.AddressScalarFieldEnum = { id: 'id', customerId: 'customerId', @@ -267,6 +304,8 @@ exports.Prisma.EmailProviderConfigScalarFieldEnum = { imapEncryption: 'imapEncryption', smtpEncryption: 'smtpEncryption', allowSelfSignedCerts: 'allowSelfSignedCerts', + systemEmailAddress: 'systemEmailAddress', + systemEmailPasswordEncrypted: 'systemEmailPasswordEncrypted', isActive: 'isActive', isDefault: 'isDefault', createdAt: 'createdAt', @@ -335,6 +374,10 @@ exports.Prisma.MeterReadingScalarFieldEnum = { value: 'value', unit: 'unit', notes: 'notes', + reportedBy: 'reportedBy', + status: 'status', + transferredAt: 'transferredAt', + transferredBy: 'transferredBy', createdAt: 'createdAt' }; @@ -577,6 +620,80 @@ exports.Prisma.CarInsuranceDetailsScalarFieldEnum = { previousInsurer: 'previousInsurer' }; +exports.Prisma.AuditLogScalarFieldEnum = { + id: 'id', + userId: 'userId', + userEmail: 'userEmail', + userRole: 'userRole', + customerId: 'customerId', + isCustomerPortal: 'isCustomerPortal', + action: 'action', + sensitivity: 'sensitivity', + resourceType: 'resourceType', + resourceId: 'resourceId', + resourceLabel: 'resourceLabel', + endpoint: 'endpoint', + httpMethod: 'httpMethod', + ipAddress: 'ipAddress', + userAgent: 'userAgent', + changesBefore: 'changesBefore', + changesAfter: 'changesAfter', + changesEncrypted: 'changesEncrypted', + dataSubjectId: 'dataSubjectId', + legalBasis: 'legalBasis', + success: 'success', + errorMessage: 'errorMessage', + durationMs: 'durationMs', + createdAt: 'createdAt', + hash: 'hash', + previousHash: 'previousHash' +}; + +exports.Prisma.CustomerConsentScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + consentType: 'consentType', + status: 'status', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + version: 'version', + ipAddress: 'ipAddress', + createdBy: 'createdBy', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.DataDeletionRequestScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + status: 'status', + requestedAt: 'requestedAt', + requestSource: 'requestSource', + requestedBy: 'requestedBy', + processedAt: 'processedAt', + processedBy: 'processedBy', + deletedData: 'deletedData', + retainedData: 'retainedData', + retentionReason: 'retentionReason', + proofDocument: 'proofDocument', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.AuditRetentionPolicyScalarFieldEnum = { + id: 'id', + resourceType: 'resourceType', + sensitivity: 'sensitivity', + retentionDays: 'retentionDays', + description: 'description', + legalBasis: 'legalBasis', + isActive: 'isActive', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.SortOrder = { asc: 'asc', desc: 'desc' @@ -625,6 +742,12 @@ exports.MeterType = exports.$Enums.MeterType = { GAS: 'GAS' }; +exports.MeterReadingStatus = exports.$Enums.MeterReadingStatus = { + RECORDED: 'RECORDED', + REPORTED: 'REPORTED', + TRANSFERRED: 'TRANSFERRED' +}; + exports.ContractType = exports.$Enums.ContractType = { ELECTRICITY: 'ELECTRICITY', GAS: 'GAS', @@ -662,7 +785,48 @@ exports.InsuranceType = exports.$Enums.InsuranceType = { FULL: 'FULL' }; +exports.AuditAction = exports.$Enums.AuditAction = { + CREATE: 'CREATE', + READ: 'READ', + UPDATE: 'UPDATE', + DELETE: 'DELETE', + EXPORT: 'EXPORT', + ANONYMIZE: 'ANONYMIZE', + LOGIN: 'LOGIN', + LOGOUT: 'LOGOUT', + LOGIN_FAILED: 'LOGIN_FAILED' +}; + +exports.AuditSensitivity = exports.$Enums.AuditSensitivity = { + LOW: 'LOW', + MEDIUM: 'MEDIUM', + HIGH: 'HIGH', + CRITICAL: 'CRITICAL' +}; + +exports.ConsentType = exports.$Enums.ConsentType = { + DATA_PROCESSING: 'DATA_PROCESSING', + MARKETING_EMAIL: 'MARKETING_EMAIL', + MARKETING_PHONE: 'MARKETING_PHONE', + DATA_SHARING_PARTNER: 'DATA_SHARING_PARTNER' +}; + +exports.ConsentStatus = exports.$Enums.ConsentStatus = { + GRANTED: 'GRANTED', + WITHDRAWN: 'WITHDRAWN', + PENDING: 'PENDING' +}; + +exports.DeletionRequestStatus = exports.$Enums.DeletionRequestStatus = { + PENDING: 'PENDING', + IN_PROGRESS: 'IN_PROGRESS', + COMPLETED: 'COMPLETED', + PARTIALLY_COMPLETED: 'PARTIALLY_COMPLETED', + REJECTED: 'REJECTED' +}; + exports.Prisma.ModelName = { + EmailLog: 'EmailLog', AppSetting: 'AppSetting', User: 'User', Role: 'Role', @@ -671,6 +835,7 @@ exports.Prisma.ModelName = { UserRole: 'UserRole', Customer: 'Customer', CustomerRepresentative: 'CustomerRepresentative', + RepresentativeAuthorization: 'RepresentativeAuthorization', Address: 'Address', BankCard: 'BankCard', IdentityDocument: 'IdentityDocument', @@ -696,7 +861,11 @@ exports.Prisma.ModelName = { MobileContractDetails: 'MobileContractDetails', SimCard: 'SimCard', TvContractDetails: 'TvContractDetails', - CarInsuranceDetails: 'CarInsuranceDetails' + CarInsuranceDetails: 'CarInsuranceDetails', + AuditLog: 'AuditLog', + CustomerConsent: 'CustomerConsent', + DataDeletionRequest: 'DataDeletionRequest', + AuditRetentionPolicy: 'AuditRetentionPolicy' }; /** diff --git a/backend/node_modules/.prisma/client/index.d.ts b/backend/node_modules/.prisma/client/index.d.ts index aceb7673..e4c23041 100644 --- a/backend/node_modules/.prisma/client/index.d.ts +++ b/backend/node_modules/.prisma/client/index.d.ts @@ -13,6 +13,11 @@ import $Result = runtime.Types.Result export type PrismaPromise = $Public.PrismaPromise +/** + * Model EmailLog + * + */ +export type EmailLog = $Result.DefaultSelection /** * Model AppSetting * @@ -53,6 +58,11 @@ export type Customer = $Result.DefaultSelection * */ export type CustomerRepresentative = $Result.DefaultSelection +/** + * Model RepresentativeAuthorization + * + */ +export type RepresentativeAuthorization = $Result.DefaultSelection /** * Model Address * @@ -183,6 +193,26 @@ export type TvContractDetails = $Result.DefaultSelection +/** + * Model AuditLog + * + */ +export type AuditLog = $Result.DefaultSelection +/** + * Model CustomerConsent + * + */ +export type CustomerConsent = $Result.DefaultSelection +/** + * Model DataDeletionRequest + * + */ +export type DataDeletionRequest = $Result.DefaultSelection +/** + * Model AuditRetentionPolicy + * + */ +export type AuditRetentionPolicy = $Result.DefaultSelection /** * Enums @@ -248,6 +278,15 @@ export const MeterType: { export type MeterType = (typeof MeterType)[keyof typeof MeterType] +export const MeterReadingStatus: { + RECORDED: 'RECORDED', + REPORTED: 'REPORTED', + TRANSFERRED: 'TRANSFERRED' +}; + +export type MeterReadingStatus = (typeof MeterReadingStatus)[keyof typeof MeterReadingStatus] + + export const ContractType: { ELECTRICITY: 'ELECTRICITY', GAS: 'GAS', @@ -299,6 +338,61 @@ export const InsuranceType: { export type InsuranceType = (typeof InsuranceType)[keyof typeof InsuranceType] + +export const AuditAction: { + CREATE: 'CREATE', + READ: 'READ', + UPDATE: 'UPDATE', + DELETE: 'DELETE', + EXPORT: 'EXPORT', + ANONYMIZE: 'ANONYMIZE', + LOGIN: 'LOGIN', + LOGOUT: 'LOGOUT', + LOGIN_FAILED: 'LOGIN_FAILED' +}; + +export type AuditAction = (typeof AuditAction)[keyof typeof AuditAction] + + +export const AuditSensitivity: { + LOW: 'LOW', + MEDIUM: 'MEDIUM', + HIGH: 'HIGH', + CRITICAL: 'CRITICAL' +}; + +export type AuditSensitivity = (typeof AuditSensitivity)[keyof typeof AuditSensitivity] + + +export const ConsentType: { + DATA_PROCESSING: 'DATA_PROCESSING', + MARKETING_EMAIL: 'MARKETING_EMAIL', + MARKETING_PHONE: 'MARKETING_PHONE', + DATA_SHARING_PARTNER: 'DATA_SHARING_PARTNER' +}; + +export type ConsentType = (typeof ConsentType)[keyof typeof ConsentType] + + +export const ConsentStatus: { + GRANTED: 'GRANTED', + WITHDRAWN: 'WITHDRAWN', + PENDING: 'PENDING' +}; + +export type ConsentStatus = (typeof ConsentStatus)[keyof typeof ConsentStatus] + + +export const DeletionRequestStatus: { + PENDING: 'PENDING', + IN_PROGRESS: 'IN_PROGRESS', + COMPLETED: 'COMPLETED', + PARTIALLY_COMPLETED: 'PARTIALLY_COMPLETED', + REJECTED: 'REJECTED' +}; + +export type DeletionRequestStatus = (typeof DeletionRequestStatus)[keyof typeof DeletionRequestStatus] + } export type CustomerType = $Enums.CustomerType @@ -329,6 +423,10 @@ export type MeterType = $Enums.MeterType export const MeterType: typeof $Enums.MeterType +export type MeterReadingStatus = $Enums.MeterReadingStatus + +export const MeterReadingStatus: typeof $Enums.MeterReadingStatus + export type ContractType = $Enums.ContractType export const ContractType: typeof $Enums.ContractType @@ -349,6 +447,26 @@ export type InsuranceType = $Enums.InsuranceType export const InsuranceType: typeof $Enums.InsuranceType +export type AuditAction = $Enums.AuditAction + +export const AuditAction: typeof $Enums.AuditAction + +export type AuditSensitivity = $Enums.AuditSensitivity + +export const AuditSensitivity: typeof $Enums.AuditSensitivity + +export type ConsentType = $Enums.ConsentType + +export const ConsentType: typeof $Enums.ConsentType + +export type ConsentStatus = $Enums.ConsentStatus + +export const ConsentStatus: typeof $Enums.ConsentStatus + +export type DeletionRequestStatus = $Enums.DeletionRequestStatus + +export const DeletionRequestStatus: typeof $Enums.DeletionRequestStatus + /** * ## Prisma Client ʲˢ * @@ -356,8 +474,8 @@ export const InsuranceType: typeof $Enums.InsuranceType * @example * ``` * const prisma = new PrismaClient() - * // Fetch zero or more AppSettings - * const appSettings = await prisma.appSetting.findMany() + * // Fetch zero or more EmailLogs + * const emailLogs = await prisma.emailLog.findMany() * ``` * * @@ -377,8 +495,8 @@ export class PrismaClient< * @example * ``` * const prisma = new PrismaClient() - * // Fetch zero or more AppSettings - * const appSettings = await prisma.appSetting.findMany() + * // Fetch zero or more EmailLogs + * const emailLogs = await prisma.emailLog.findMany() * ``` * * @@ -473,6 +591,16 @@ export class PrismaClient< $extends: $Extensions.ExtendsHook<"extends", Prisma.TypeMapCb, ExtArgs> /** + * `prisma.emailLog`: Exposes CRUD operations for the **EmailLog** model. + * Example usage: + * ```ts + * // Fetch zero or more EmailLogs + * const emailLogs = await prisma.emailLog.findMany() + * ``` + */ + get emailLog(): Prisma.EmailLogDelegate; + + /** * `prisma.appSetting`: Exposes CRUD operations for the **AppSetting** model. * Example usage: * ```ts @@ -552,6 +680,16 @@ export class PrismaClient< */ get customerRepresentative(): Prisma.CustomerRepresentativeDelegate; + /** + * `prisma.representativeAuthorization`: Exposes CRUD operations for the **RepresentativeAuthorization** model. + * Example usage: + * ```ts + * // Fetch zero or more RepresentativeAuthorizations + * const representativeAuthorizations = await prisma.representativeAuthorization.findMany() + * ``` + */ + get representativeAuthorization(): Prisma.RepresentativeAuthorizationDelegate; + /** * `prisma.address`: Exposes CRUD operations for the **Address** model. * Example usage: @@ -811,6 +949,46 @@ export class PrismaClient< * ``` */ get carInsuranceDetails(): Prisma.CarInsuranceDetailsDelegate; + + /** + * `prisma.auditLog`: Exposes CRUD operations for the **AuditLog** model. + * Example usage: + * ```ts + * // Fetch zero or more AuditLogs + * const auditLogs = await prisma.auditLog.findMany() + * ``` + */ + get auditLog(): Prisma.AuditLogDelegate; + + /** + * `prisma.customerConsent`: Exposes CRUD operations for the **CustomerConsent** model. + * Example usage: + * ```ts + * // Fetch zero or more CustomerConsents + * const customerConsents = await prisma.customerConsent.findMany() + * ``` + */ + get customerConsent(): Prisma.CustomerConsentDelegate; + + /** + * `prisma.dataDeletionRequest`: Exposes CRUD operations for the **DataDeletionRequest** model. + * Example usage: + * ```ts + * // Fetch zero or more DataDeletionRequests + * const dataDeletionRequests = await prisma.dataDeletionRequest.findMany() + * ``` + */ + get dataDeletionRequest(): Prisma.DataDeletionRequestDelegate; + + /** + * `prisma.auditRetentionPolicy`: Exposes CRUD operations for the **AuditRetentionPolicy** model. + * Example usage: + * ```ts + * // Fetch zero or more AuditRetentionPolicies + * const auditRetentionPolicies = await prisma.auditRetentionPolicy.findMany() + * ``` + */ + get auditRetentionPolicy(): Prisma.AuditRetentionPolicyDelegate; } export namespace Prisma { @@ -1252,6 +1430,7 @@ export namespace Prisma { export const ModelName: { + EmailLog: 'EmailLog', AppSetting: 'AppSetting', User: 'User', Role: 'Role', @@ -1260,6 +1439,7 @@ export namespace Prisma { UserRole: 'UserRole', Customer: 'Customer', CustomerRepresentative: 'CustomerRepresentative', + RepresentativeAuthorization: 'RepresentativeAuthorization', Address: 'Address', BankCard: 'BankCard', IdentityDocument: 'IdentityDocument', @@ -1285,7 +1465,11 @@ export namespace Prisma { MobileContractDetails: 'MobileContractDetails', SimCard: 'SimCard', TvContractDetails: 'TvContractDetails', - CarInsuranceDetails: 'CarInsuranceDetails' + CarInsuranceDetails: 'CarInsuranceDetails', + AuditLog: 'AuditLog', + CustomerConsent: 'CustomerConsent', + DataDeletionRequest: 'DataDeletionRequest', + AuditRetentionPolicy: 'AuditRetentionPolicy' }; export type ModelName = (typeof ModelName)[keyof typeof ModelName] @@ -1301,10 +1485,76 @@ export namespace Prisma { export type TypeMap = { meta: { - modelProps: "appSetting" | "user" | "role" | "permission" | "rolePermission" | "userRole" | "customer" | "customerRepresentative" | "address" | "bankCard" | "identityDocument" | "emailProviderConfig" | "stressfreiEmail" | "cachedEmail" | "meter" | "meterReading" | "salesPlatform" | "cancellationPeriod" | "contractDuration" | "provider" | "tariff" | "contractCategory" | "contract" | "contractHistoryEntry" | "contractTask" | "contractTaskSubtask" | "energyContractDetails" | "invoice" | "internetContractDetails" | "phoneNumber" | "mobileContractDetails" | "simCard" | "tvContractDetails" | "carInsuranceDetails" + modelProps: "emailLog" | "appSetting" | "user" | "role" | "permission" | "rolePermission" | "userRole" | "customer" | "customerRepresentative" | "representativeAuthorization" | "address" | "bankCard" | "identityDocument" | "emailProviderConfig" | "stressfreiEmail" | "cachedEmail" | "meter" | "meterReading" | "salesPlatform" | "cancellationPeriod" | "contractDuration" | "provider" | "tariff" | "contractCategory" | "contract" | "contractHistoryEntry" | "contractTask" | "contractTaskSubtask" | "energyContractDetails" | "invoice" | "internetContractDetails" | "phoneNumber" | "mobileContractDetails" | "simCard" | "tvContractDetails" | "carInsuranceDetails" | "auditLog" | "customerConsent" | "dataDeletionRequest" | "auditRetentionPolicy" txIsolationLevel: Prisma.TransactionIsolationLevel } model: { + EmailLog: { + payload: Prisma.$EmailLogPayload + fields: Prisma.EmailLogFieldRefs + operations: { + findUnique: { + args: Prisma.EmailLogFindUniqueArgs + result: $Utils.PayloadToResult | null + } + findUniqueOrThrow: { + args: Prisma.EmailLogFindUniqueOrThrowArgs + result: $Utils.PayloadToResult + } + findFirst: { + args: Prisma.EmailLogFindFirstArgs + result: $Utils.PayloadToResult | null + } + findFirstOrThrow: { + args: Prisma.EmailLogFindFirstOrThrowArgs + result: $Utils.PayloadToResult + } + findMany: { + args: Prisma.EmailLogFindManyArgs + result: $Utils.PayloadToResult[] + } + create: { + args: Prisma.EmailLogCreateArgs + result: $Utils.PayloadToResult + } + createMany: { + args: Prisma.EmailLogCreateManyArgs + result: BatchPayload + } + delete: { + args: Prisma.EmailLogDeleteArgs + result: $Utils.PayloadToResult + } + update: { + args: Prisma.EmailLogUpdateArgs + result: $Utils.PayloadToResult + } + deleteMany: { + args: Prisma.EmailLogDeleteManyArgs + result: BatchPayload + } + updateMany: { + args: Prisma.EmailLogUpdateManyArgs + result: BatchPayload + } + upsert: { + args: Prisma.EmailLogUpsertArgs + result: $Utils.PayloadToResult + } + aggregate: { + args: Prisma.EmailLogAggregateArgs + result: $Utils.Optional + } + groupBy: { + args: Prisma.EmailLogGroupByArgs + result: $Utils.Optional[] + } + count: { + args: Prisma.EmailLogCountArgs + result: $Utils.Optional | number + } + } + } AppSetting: { payload: Prisma.$AppSettingPayload fields: Prisma.AppSettingFieldRefs @@ -1833,6 +2083,72 @@ export namespace Prisma { } } } + RepresentativeAuthorization: { + payload: Prisma.$RepresentativeAuthorizationPayload + fields: Prisma.RepresentativeAuthorizationFieldRefs + operations: { + findUnique: { + args: Prisma.RepresentativeAuthorizationFindUniqueArgs + result: $Utils.PayloadToResult | null + } + findUniqueOrThrow: { + args: Prisma.RepresentativeAuthorizationFindUniqueOrThrowArgs + result: $Utils.PayloadToResult + } + findFirst: { + args: Prisma.RepresentativeAuthorizationFindFirstArgs + result: $Utils.PayloadToResult | null + } + findFirstOrThrow: { + args: Prisma.RepresentativeAuthorizationFindFirstOrThrowArgs + result: $Utils.PayloadToResult + } + findMany: { + args: Prisma.RepresentativeAuthorizationFindManyArgs + result: $Utils.PayloadToResult[] + } + create: { + args: Prisma.RepresentativeAuthorizationCreateArgs + result: $Utils.PayloadToResult + } + createMany: { + args: Prisma.RepresentativeAuthorizationCreateManyArgs + result: BatchPayload + } + delete: { + args: Prisma.RepresentativeAuthorizationDeleteArgs + result: $Utils.PayloadToResult + } + update: { + args: Prisma.RepresentativeAuthorizationUpdateArgs + result: $Utils.PayloadToResult + } + deleteMany: { + args: Prisma.RepresentativeAuthorizationDeleteManyArgs + result: BatchPayload + } + updateMany: { + args: Prisma.RepresentativeAuthorizationUpdateManyArgs + result: BatchPayload + } + upsert: { + args: Prisma.RepresentativeAuthorizationUpsertArgs + result: $Utils.PayloadToResult + } + aggregate: { + args: Prisma.RepresentativeAuthorizationAggregateArgs + result: $Utils.Optional + } + groupBy: { + args: Prisma.RepresentativeAuthorizationGroupByArgs + result: $Utils.Optional[] + } + count: { + args: Prisma.RepresentativeAuthorizationCountArgs + result: $Utils.Optional | number + } + } + } Address: { payload: Prisma.$AddressPayload fields: Prisma.AddressFieldRefs @@ -3549,6 +3865,270 @@ export namespace Prisma { } } } + AuditLog: { + payload: Prisma.$AuditLogPayload + fields: Prisma.AuditLogFieldRefs + operations: { + findUnique: { + args: Prisma.AuditLogFindUniqueArgs + result: $Utils.PayloadToResult | null + } + findUniqueOrThrow: { + args: Prisma.AuditLogFindUniqueOrThrowArgs + result: $Utils.PayloadToResult + } + findFirst: { + args: Prisma.AuditLogFindFirstArgs + result: $Utils.PayloadToResult | null + } + findFirstOrThrow: { + args: Prisma.AuditLogFindFirstOrThrowArgs + result: $Utils.PayloadToResult + } + findMany: { + args: Prisma.AuditLogFindManyArgs + result: $Utils.PayloadToResult[] + } + create: { + args: Prisma.AuditLogCreateArgs + result: $Utils.PayloadToResult + } + createMany: { + args: Prisma.AuditLogCreateManyArgs + result: BatchPayload + } + delete: { + args: Prisma.AuditLogDeleteArgs + result: $Utils.PayloadToResult + } + update: { + args: Prisma.AuditLogUpdateArgs + result: $Utils.PayloadToResult + } + deleteMany: { + args: Prisma.AuditLogDeleteManyArgs + result: BatchPayload + } + updateMany: { + args: Prisma.AuditLogUpdateManyArgs + result: BatchPayload + } + upsert: { + args: Prisma.AuditLogUpsertArgs + result: $Utils.PayloadToResult + } + aggregate: { + args: Prisma.AuditLogAggregateArgs + result: $Utils.Optional + } + groupBy: { + args: Prisma.AuditLogGroupByArgs + result: $Utils.Optional[] + } + count: { + args: Prisma.AuditLogCountArgs + result: $Utils.Optional | number + } + } + } + CustomerConsent: { + payload: Prisma.$CustomerConsentPayload + fields: Prisma.CustomerConsentFieldRefs + operations: { + findUnique: { + args: Prisma.CustomerConsentFindUniqueArgs + result: $Utils.PayloadToResult | null + } + findUniqueOrThrow: { + args: Prisma.CustomerConsentFindUniqueOrThrowArgs + result: $Utils.PayloadToResult + } + findFirst: { + args: Prisma.CustomerConsentFindFirstArgs + result: $Utils.PayloadToResult | null + } + findFirstOrThrow: { + args: Prisma.CustomerConsentFindFirstOrThrowArgs + result: $Utils.PayloadToResult + } + findMany: { + args: Prisma.CustomerConsentFindManyArgs + result: $Utils.PayloadToResult[] + } + create: { + args: Prisma.CustomerConsentCreateArgs + result: $Utils.PayloadToResult + } + createMany: { + args: Prisma.CustomerConsentCreateManyArgs + result: BatchPayload + } + delete: { + args: Prisma.CustomerConsentDeleteArgs + result: $Utils.PayloadToResult + } + update: { + args: Prisma.CustomerConsentUpdateArgs + result: $Utils.PayloadToResult + } + deleteMany: { + args: Prisma.CustomerConsentDeleteManyArgs + result: BatchPayload + } + updateMany: { + args: Prisma.CustomerConsentUpdateManyArgs + result: BatchPayload + } + upsert: { + args: Prisma.CustomerConsentUpsertArgs + result: $Utils.PayloadToResult + } + aggregate: { + args: Prisma.CustomerConsentAggregateArgs + result: $Utils.Optional + } + groupBy: { + args: Prisma.CustomerConsentGroupByArgs + result: $Utils.Optional[] + } + count: { + args: Prisma.CustomerConsentCountArgs + result: $Utils.Optional | number + } + } + } + DataDeletionRequest: { + payload: Prisma.$DataDeletionRequestPayload + fields: Prisma.DataDeletionRequestFieldRefs + operations: { + findUnique: { + args: Prisma.DataDeletionRequestFindUniqueArgs + result: $Utils.PayloadToResult | null + } + findUniqueOrThrow: { + args: Prisma.DataDeletionRequestFindUniqueOrThrowArgs + result: $Utils.PayloadToResult + } + findFirst: { + args: Prisma.DataDeletionRequestFindFirstArgs + result: $Utils.PayloadToResult | null + } + findFirstOrThrow: { + args: Prisma.DataDeletionRequestFindFirstOrThrowArgs + result: $Utils.PayloadToResult + } + findMany: { + args: Prisma.DataDeletionRequestFindManyArgs + result: $Utils.PayloadToResult[] + } + create: { + args: Prisma.DataDeletionRequestCreateArgs + result: $Utils.PayloadToResult + } + createMany: { + args: Prisma.DataDeletionRequestCreateManyArgs + result: BatchPayload + } + delete: { + args: Prisma.DataDeletionRequestDeleteArgs + result: $Utils.PayloadToResult + } + update: { + args: Prisma.DataDeletionRequestUpdateArgs + result: $Utils.PayloadToResult + } + deleteMany: { + args: Prisma.DataDeletionRequestDeleteManyArgs + result: BatchPayload + } + updateMany: { + args: Prisma.DataDeletionRequestUpdateManyArgs + result: BatchPayload + } + upsert: { + args: Prisma.DataDeletionRequestUpsertArgs + result: $Utils.PayloadToResult + } + aggregate: { + args: Prisma.DataDeletionRequestAggregateArgs + result: $Utils.Optional + } + groupBy: { + args: Prisma.DataDeletionRequestGroupByArgs + result: $Utils.Optional[] + } + count: { + args: Prisma.DataDeletionRequestCountArgs + result: $Utils.Optional | number + } + } + } + AuditRetentionPolicy: { + payload: Prisma.$AuditRetentionPolicyPayload + fields: Prisma.AuditRetentionPolicyFieldRefs + operations: { + findUnique: { + args: Prisma.AuditRetentionPolicyFindUniqueArgs + result: $Utils.PayloadToResult | null + } + findUniqueOrThrow: { + args: Prisma.AuditRetentionPolicyFindUniqueOrThrowArgs + result: $Utils.PayloadToResult + } + findFirst: { + args: Prisma.AuditRetentionPolicyFindFirstArgs + result: $Utils.PayloadToResult | null + } + findFirstOrThrow: { + args: Prisma.AuditRetentionPolicyFindFirstOrThrowArgs + result: $Utils.PayloadToResult + } + findMany: { + args: Prisma.AuditRetentionPolicyFindManyArgs + result: $Utils.PayloadToResult[] + } + create: { + args: Prisma.AuditRetentionPolicyCreateArgs + result: $Utils.PayloadToResult + } + createMany: { + args: Prisma.AuditRetentionPolicyCreateManyArgs + result: BatchPayload + } + delete: { + args: Prisma.AuditRetentionPolicyDeleteArgs + result: $Utils.PayloadToResult + } + update: { + args: Prisma.AuditRetentionPolicyUpdateArgs + result: $Utils.PayloadToResult + } + deleteMany: { + args: Prisma.AuditRetentionPolicyDeleteManyArgs + result: BatchPayload + } + updateMany: { + args: Prisma.AuditRetentionPolicyUpdateManyArgs + result: BatchPayload + } + upsert: { + args: Prisma.AuditRetentionPolicyUpsertArgs + result: $Utils.PayloadToResult + } + aggregate: { + args: Prisma.AuditRetentionPolicyAggregateArgs + result: $Utils.Optional + } + groupBy: { + args: Prisma.AuditRetentionPolicyGroupByArgs + result: $Utils.Optional[] + } + count: { + args: Prisma.AuditRetentionPolicyCountArgs + result: $Utils.Optional | number + } + } + } } } & { other: { @@ -3820,6 +4400,9 @@ export namespace Prisma { contracts: number representingFor: number representedBy: number + authorizationsGiven: number + authorizationsReceived: number + consents: number } export type CustomerCountOutputTypeSelect = { @@ -3831,6 +4414,9 @@ export namespace Prisma { contracts?: boolean | CustomerCountOutputTypeCountContractsArgs representingFor?: boolean | CustomerCountOutputTypeCountRepresentingForArgs representedBy?: boolean | CustomerCountOutputTypeCountRepresentedByArgs + authorizationsGiven?: boolean | CustomerCountOutputTypeCountAuthorizationsGivenArgs + authorizationsReceived?: boolean | CustomerCountOutputTypeCountAuthorizationsReceivedArgs + consents?: boolean | CustomerCountOutputTypeCountConsentsArgs } // Custom InputTypes @@ -3900,6 +4486,27 @@ export namespace Prisma { where?: CustomerRepresentativeWhereInput } + /** + * CustomerCountOutputType without action + */ + export type CustomerCountOutputTypeCountAuthorizationsGivenArgs = { + where?: RepresentativeAuthorizationWhereInput + } + + /** + * CustomerCountOutputType without action + */ + export type CustomerCountOutputTypeCountAuthorizationsReceivedArgs = { + where?: RepresentativeAuthorizationWhereInput + } + + /** + * CustomerCountOutputType without action + */ + export type CustomerCountOutputTypeCountConsentsArgs = { + where?: CustomerConsentWhereInput + } + /** * Count Type AddressCountOutputType @@ -4464,6 +5071,1001 @@ export namespace Prisma { * Models */ + /** + * Model EmailLog + */ + + export type AggregateEmailLog = { + _count: EmailLogCountAggregateOutputType | null + _avg: EmailLogAvgAggregateOutputType | null + _sum: EmailLogSumAggregateOutputType | null + _min: EmailLogMinAggregateOutputType | null + _max: EmailLogMaxAggregateOutputType | null + } + + export type EmailLogAvgAggregateOutputType = { + id: number | null + customerId: number | null + smtpPort: number | null + } + + export type EmailLogSumAggregateOutputType = { + id: number | null + customerId: number | null + smtpPort: number | null + } + + export type EmailLogMinAggregateOutputType = { + id: number | null + fromAddress: string | null + toAddress: string | null + subject: string | null + context: string | null + customerId: number | null + triggeredBy: string | null + smtpServer: string | null + smtpPort: number | null + smtpEncryption: string | null + smtpUser: string | null + success: boolean | null + messageId: string | null + errorMessage: string | null + smtpResponse: string | null + sentAt: Date | null + } + + export type EmailLogMaxAggregateOutputType = { + id: number | null + fromAddress: string | null + toAddress: string | null + subject: string | null + context: string | null + customerId: number | null + triggeredBy: string | null + smtpServer: string | null + smtpPort: number | null + smtpEncryption: string | null + smtpUser: string | null + success: boolean | null + messageId: string | null + errorMessage: string | null + smtpResponse: string | null + sentAt: Date | null + } + + export type EmailLogCountAggregateOutputType = { + id: number + fromAddress: number + toAddress: number + subject: number + context: number + customerId: number + triggeredBy: number + smtpServer: number + smtpPort: number + smtpEncryption: number + smtpUser: number + success: number + messageId: number + errorMessage: number + smtpResponse: number + sentAt: number + _all: number + } + + + export type EmailLogAvgAggregateInputType = { + id?: true + customerId?: true + smtpPort?: true + } + + export type EmailLogSumAggregateInputType = { + id?: true + customerId?: true + smtpPort?: true + } + + export type EmailLogMinAggregateInputType = { + id?: true + fromAddress?: true + toAddress?: true + subject?: true + context?: true + customerId?: true + triggeredBy?: true + smtpServer?: true + smtpPort?: true + smtpEncryption?: true + smtpUser?: true + success?: true + messageId?: true + errorMessage?: true + smtpResponse?: true + sentAt?: true + } + + export type EmailLogMaxAggregateInputType = { + id?: true + fromAddress?: true + toAddress?: true + subject?: true + context?: true + customerId?: true + triggeredBy?: true + smtpServer?: true + smtpPort?: true + smtpEncryption?: true + smtpUser?: true + success?: true + messageId?: true + errorMessage?: true + smtpResponse?: true + sentAt?: true + } + + export type EmailLogCountAggregateInputType = { + id?: true + fromAddress?: true + toAddress?: true + subject?: true + context?: true + customerId?: true + triggeredBy?: true + smtpServer?: true + smtpPort?: true + smtpEncryption?: true + smtpUser?: true + success?: true + messageId?: true + errorMessage?: true + smtpResponse?: true + sentAt?: true + _all?: true + } + + export type EmailLogAggregateArgs = { + /** + * Filter which EmailLog to aggregate. + */ + where?: EmailLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of EmailLogs to fetch. + */ + orderBy?: EmailLogOrderByWithRelationInput | EmailLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the start position + */ + cursor?: EmailLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` EmailLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` EmailLogs. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Count returned EmailLogs + **/ + _count?: true | EmailLogCountAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to average + **/ + _avg?: EmailLogAvgAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to sum + **/ + _sum?: EmailLogSumAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the minimum value + **/ + _min?: EmailLogMinAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the maximum value + **/ + _max?: EmailLogMaxAggregateInputType + } + + export type GetEmailLogAggregateType = { + [P in keyof T & keyof AggregateEmailLog]: P extends '_count' | 'count' + ? T[P] extends true + ? number + : GetScalarType + : GetScalarType + } + + + + + export type EmailLogGroupByArgs = { + where?: EmailLogWhereInput + orderBy?: EmailLogOrderByWithAggregationInput | EmailLogOrderByWithAggregationInput[] + by: EmailLogScalarFieldEnum[] | EmailLogScalarFieldEnum + having?: EmailLogScalarWhereWithAggregatesInput + take?: number + skip?: number + _count?: EmailLogCountAggregateInputType | true + _avg?: EmailLogAvgAggregateInputType + _sum?: EmailLogSumAggregateInputType + _min?: EmailLogMinAggregateInputType + _max?: EmailLogMaxAggregateInputType + } + + export type EmailLogGroupByOutputType = { + id: number + fromAddress: string + toAddress: string + subject: string + context: string + customerId: number | null + triggeredBy: string | null + smtpServer: string + smtpPort: number + smtpEncryption: string + smtpUser: string + success: boolean + messageId: string | null + errorMessage: string | null + smtpResponse: string | null + sentAt: Date + _count: EmailLogCountAggregateOutputType | null + _avg: EmailLogAvgAggregateOutputType | null + _sum: EmailLogSumAggregateOutputType | null + _min: EmailLogMinAggregateOutputType | null + _max: EmailLogMaxAggregateOutputType | null + } + + type GetEmailLogGroupByPayload = Prisma.PrismaPromise< + Array< + PickEnumerable & + { + [P in ((keyof T) & (keyof EmailLogGroupByOutputType))]: P extends '_count' + ? T[P] extends boolean + ? number + : GetScalarType + : GetScalarType + } + > + > + + + export type EmailLogSelect = $Extensions.GetSelect<{ + id?: boolean + fromAddress?: boolean + toAddress?: boolean + subject?: boolean + context?: boolean + customerId?: boolean + triggeredBy?: boolean + smtpServer?: boolean + smtpPort?: boolean + smtpEncryption?: boolean + smtpUser?: boolean + success?: boolean + messageId?: boolean + errorMessage?: boolean + smtpResponse?: boolean + sentAt?: boolean + }, ExtArgs["result"]["emailLog"]> + + + export type EmailLogSelectScalar = { + id?: boolean + fromAddress?: boolean + toAddress?: boolean + subject?: boolean + context?: boolean + customerId?: boolean + triggeredBy?: boolean + smtpServer?: boolean + smtpPort?: boolean + smtpEncryption?: boolean + smtpUser?: boolean + success?: boolean + messageId?: boolean + errorMessage?: boolean + smtpResponse?: boolean + sentAt?: boolean + } + + + export type $EmailLogPayload = { + name: "EmailLog" + objects: {} + scalars: $Extensions.GetPayloadResult<{ + id: number + fromAddress: string + toAddress: string + subject: string + context: string + customerId: number | null + triggeredBy: string | null + smtpServer: string + smtpPort: number + smtpEncryption: string + smtpUser: string + success: boolean + messageId: string | null + errorMessage: string | null + smtpResponse: string | null + sentAt: Date + }, ExtArgs["result"]["emailLog"]> + composites: {} + } + + type EmailLogGetPayload = $Result.GetResult + + type EmailLogCountArgs = + Omit & { + select?: EmailLogCountAggregateInputType | true + } + + export interface EmailLogDelegate { + [K: symbol]: { types: Prisma.TypeMap['model']['EmailLog'], meta: { name: 'EmailLog' } } + /** + * Find zero or one EmailLog that matches the filter. + * @param {EmailLogFindUniqueArgs} args - Arguments to find a EmailLog + * @example + * // Get one EmailLog + * const emailLog = await prisma.emailLog.findUnique({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUnique(args: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "findUnique"> | null, null, ExtArgs> + + /** + * Find one EmailLog that matches the filter or throw an error with `error.code='P2025'` + * if no matches were found. + * @param {EmailLogFindUniqueOrThrowArgs} args - Arguments to find a EmailLog + * @example + * // Get one EmailLog + * const emailLog = await prisma.emailLog.findUniqueOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUniqueOrThrow(args: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "findUniqueOrThrow">, never, ExtArgs> + + /** + * Find the first EmailLog that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {EmailLogFindFirstArgs} args - Arguments to find a EmailLog + * @example + * // Get one EmailLog + * const emailLog = await prisma.emailLog.findFirst({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirst(args?: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "findFirst"> | null, null, ExtArgs> + + /** + * Find the first EmailLog that matches the filter or + * throw `PrismaKnownClientError` with `P2025` code if no matches were found. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {EmailLogFindFirstOrThrowArgs} args - Arguments to find a EmailLog + * @example + * // Get one EmailLog + * const emailLog = await prisma.emailLog.findFirstOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirstOrThrow(args?: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "findFirstOrThrow">, never, ExtArgs> + + /** + * Find zero or more EmailLogs that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {EmailLogFindManyArgs} args - Arguments to filter and select certain fields only. + * @example + * // Get all EmailLogs + * const emailLogs = await prisma.emailLog.findMany() + * + * // Get first 10 EmailLogs + * const emailLogs = await prisma.emailLog.findMany({ take: 10 }) + * + * // Only select the `id` + * const emailLogWithIdOnly = await prisma.emailLog.findMany({ select: { id: true } }) + * + */ + findMany(args?: SelectSubset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany">> + + /** + * Create a EmailLog. + * @param {EmailLogCreateArgs} args - Arguments to create a EmailLog. + * @example + * // Create one EmailLog + * const EmailLog = await prisma.emailLog.create({ + * data: { + * // ... data to create a EmailLog + * } + * }) + * + */ + create(args: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "create">, never, ExtArgs> + + /** + * Create many EmailLogs. + * @param {EmailLogCreateManyArgs} args - Arguments to create many EmailLogs. + * @example + * // Create many EmailLogs + * const emailLog = await prisma.emailLog.createMany({ + * data: [ + * // ... provide data here + * ] + * }) + * + */ + createMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Delete a EmailLog. + * @param {EmailLogDeleteArgs} args - Arguments to delete one EmailLog. + * @example + * // Delete one EmailLog + * const EmailLog = await prisma.emailLog.delete({ + * where: { + * // ... filter to delete one EmailLog + * } + * }) + * + */ + delete(args: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "delete">, never, ExtArgs> + + /** + * Update one EmailLog. + * @param {EmailLogUpdateArgs} args - Arguments to update one EmailLog. + * @example + * // Update one EmailLog + * const emailLog = await prisma.emailLog.update({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + update(args: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "update">, never, ExtArgs> + + /** + * Delete zero or more EmailLogs. + * @param {EmailLogDeleteManyArgs} args - Arguments to filter EmailLogs to delete. + * @example + * // Delete a few EmailLogs + * const { count } = await prisma.emailLog.deleteMany({ + * where: { + * // ... provide filter here + * } + * }) + * + */ + deleteMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Update zero or more EmailLogs. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {EmailLogUpdateManyArgs} args - Arguments to update one or more rows. + * @example + * // Update many EmailLogs + * const emailLog = await prisma.emailLog.updateMany({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + updateMany(args: SelectSubset>): Prisma.PrismaPromise + + /** + * Create or update one EmailLog. + * @param {EmailLogUpsertArgs} args - Arguments to update or create a EmailLog. + * @example + * // Update or create a EmailLog + * const emailLog = await prisma.emailLog.upsert({ + * create: { + * // ... data to create a EmailLog + * }, + * update: { + * // ... in case it already exists, update + * }, + * where: { + * // ... the filter for the EmailLog we want to update + * } + * }) + */ + upsert(args: SelectSubset>): Prisma__EmailLogClient<$Result.GetResult, T, "upsert">, never, ExtArgs> + + + /** + * Count the number of EmailLogs. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {EmailLogCountArgs} args - Arguments to filter EmailLogs to count. + * @example + * // Count the number of EmailLogs + * const count = await prisma.emailLog.count({ + * where: { + * // ... the filter for the EmailLogs we want to count + * } + * }) + **/ + count( + args?: Subset, + ): Prisma.PrismaPromise< + T extends $Utils.Record<'select', any> + ? T['select'] extends true + ? number + : GetScalarType + : number + > + + /** + * Allows you to perform aggregations operations on a EmailLog. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {EmailLogAggregateArgs} args - Select which aggregations you would like to apply and on what fields. + * @example + * // Ordered by age ascending + * // Where email contains prisma.io + * // Limited to the 10 users + * const aggregations = await prisma.user.aggregate({ + * _avg: { + * age: true, + * }, + * where: { + * email: { + * contains: "prisma.io", + * }, + * }, + * orderBy: { + * age: "asc", + * }, + * take: 10, + * }) + **/ + aggregate(args: Subset): Prisma.PrismaPromise> + + /** + * Group by EmailLog. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {EmailLogGroupByArgs} args - Group by arguments. + * @example + * // Group by city, order by createdAt, get count + * const result = await prisma.user.groupBy({ + * by: ['city', 'createdAt'], + * orderBy: { + * createdAt: true + * }, + * _count: { + * _all: true + * }, + * }) + * + **/ + groupBy< + T extends EmailLogGroupByArgs, + HasSelectOrTake extends Or< + Extends<'skip', Keys>, + Extends<'take', Keys> + >, + OrderByArg extends True extends HasSelectOrTake + ? { orderBy: EmailLogGroupByArgs['orderBy'] } + : { orderBy?: EmailLogGroupByArgs['orderBy'] }, + OrderFields extends ExcludeUnderscoreKeys>>, + ByFields extends MaybeTupleToUnion, + ByValid extends Has, + HavingFields extends GetHavingFields, + HavingValid extends Has, + ByEmpty extends T['by'] extends never[] ? True : False, + InputErrors extends ByEmpty extends True + ? `Error: "by" must not be empty.` + : HavingValid extends False + ? { + [P in HavingFields]: P extends ByFields + ? never + : P extends string + ? `Error: Field "${P}" used in "having" needs to be provided in "by".` + : [ + Error, + 'Field ', + P, + ` in "having" needs to be provided in "by"`, + ] + }[HavingFields] + : 'take' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "take", you also need to provide "orderBy"' + : 'skip' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "skip", you also need to provide "orderBy"' + : ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + >(args: SubsetIntersection & InputErrors): {} extends InputErrors ? GetEmailLogGroupByPayload : Prisma.PrismaPromise + /** + * Fields of the EmailLog model + */ + readonly fields: EmailLogFieldRefs; + } + + /** + * The delegate class that acts as a "Promise-like" for EmailLog. + * Why is this prefixed with `Prisma__`? + * Because we want to prevent naming conflicts as mentioned in + * https://github.com/prisma/prisma-client-js/issues/707 + */ + export interface Prisma__EmailLogClient extends Prisma.PrismaPromise { + readonly [Symbol.toStringTag]: "PrismaPromise" + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): $Utils.JsPromise + } + + + + + /** + * Fields of the EmailLog model + */ + interface EmailLogFieldRefs { + readonly id: FieldRef<"EmailLog", 'Int'> + readonly fromAddress: FieldRef<"EmailLog", 'String'> + readonly toAddress: FieldRef<"EmailLog", 'String'> + readonly subject: FieldRef<"EmailLog", 'String'> + readonly context: FieldRef<"EmailLog", 'String'> + readonly customerId: FieldRef<"EmailLog", 'Int'> + readonly triggeredBy: FieldRef<"EmailLog", 'String'> + readonly smtpServer: FieldRef<"EmailLog", 'String'> + readonly smtpPort: FieldRef<"EmailLog", 'Int'> + readonly smtpEncryption: FieldRef<"EmailLog", 'String'> + readonly smtpUser: FieldRef<"EmailLog", 'String'> + readonly success: FieldRef<"EmailLog", 'Boolean'> + readonly messageId: FieldRef<"EmailLog", 'String'> + readonly errorMessage: FieldRef<"EmailLog", 'String'> + readonly smtpResponse: FieldRef<"EmailLog", 'String'> + readonly sentAt: FieldRef<"EmailLog", 'DateTime'> + } + + + // Custom InputTypes + /** + * EmailLog findUnique + */ + export type EmailLogFindUniqueArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * Filter, which EmailLog to fetch. + */ + where: EmailLogWhereUniqueInput + } + + /** + * EmailLog findUniqueOrThrow + */ + export type EmailLogFindUniqueOrThrowArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * Filter, which EmailLog to fetch. + */ + where: EmailLogWhereUniqueInput + } + + /** + * EmailLog findFirst + */ + export type EmailLogFindFirstArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * Filter, which EmailLog to fetch. + */ + where?: EmailLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of EmailLogs to fetch. + */ + orderBy?: EmailLogOrderByWithRelationInput | EmailLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for EmailLogs. + */ + cursor?: EmailLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` EmailLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` EmailLogs. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of EmailLogs. + */ + distinct?: EmailLogScalarFieldEnum | EmailLogScalarFieldEnum[] + } + + /** + * EmailLog findFirstOrThrow + */ + export type EmailLogFindFirstOrThrowArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * Filter, which EmailLog to fetch. + */ + where?: EmailLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of EmailLogs to fetch. + */ + orderBy?: EmailLogOrderByWithRelationInput | EmailLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for EmailLogs. + */ + cursor?: EmailLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` EmailLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` EmailLogs. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of EmailLogs. + */ + distinct?: EmailLogScalarFieldEnum | EmailLogScalarFieldEnum[] + } + + /** + * EmailLog findMany + */ + export type EmailLogFindManyArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * Filter, which EmailLogs to fetch. + */ + where?: EmailLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of EmailLogs to fetch. + */ + orderBy?: EmailLogOrderByWithRelationInput | EmailLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for listing EmailLogs. + */ + cursor?: EmailLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` EmailLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` EmailLogs. + */ + skip?: number + distinct?: EmailLogScalarFieldEnum | EmailLogScalarFieldEnum[] + } + + /** + * EmailLog create + */ + export type EmailLogCreateArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * The data needed to create a EmailLog. + */ + data: XOR + } + + /** + * EmailLog createMany + */ + export type EmailLogCreateManyArgs = { + /** + * The data used to create many EmailLogs. + */ + data: EmailLogCreateManyInput | EmailLogCreateManyInput[] + skipDuplicates?: boolean + } + + /** + * EmailLog update + */ + export type EmailLogUpdateArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * The data needed to update a EmailLog. + */ + data: XOR + /** + * Choose, which EmailLog to update. + */ + where: EmailLogWhereUniqueInput + } + + /** + * EmailLog updateMany + */ + export type EmailLogUpdateManyArgs = { + /** + * The data used to update EmailLogs. + */ + data: XOR + /** + * Filter which EmailLogs to update + */ + where?: EmailLogWhereInput + } + + /** + * EmailLog upsert + */ + export type EmailLogUpsertArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * The filter to search for the EmailLog to update in case it exists. + */ + where: EmailLogWhereUniqueInput + /** + * In case the EmailLog found by the `where` argument doesn't exist, create a new EmailLog with this data. + */ + create: XOR + /** + * In case the EmailLog was found with the provided `where` argument, update it with this data. + */ + update: XOR + } + + /** + * EmailLog delete + */ + export type EmailLogDeleteArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + /** + * Filter which EmailLog to delete. + */ + where: EmailLogWhereUniqueInput + } + + /** + * EmailLog deleteMany + */ + export type EmailLogDeleteManyArgs = { + /** + * Filter which EmailLogs to delete + */ + where?: EmailLogWhereInput + } + + /** + * EmailLog without action + */ + export type EmailLogDefaultArgs = { + /** + * Select specific fields to fetch from the EmailLog + */ + select?: EmailLogSelect | null + } + + /** * Model AppSetting */ @@ -5360,6 +6962,9 @@ export namespace Prisma { lastName: string | null isActive: boolean | null tokenInvalidatedAt: Date | null + whatsappNumber: string | null + telegramUsername: string | null + signalNumber: string | null customerId: number | null createdAt: Date | null updatedAt: Date | null @@ -5373,6 +6978,9 @@ export namespace Prisma { lastName: string | null isActive: boolean | null tokenInvalidatedAt: Date | null + whatsappNumber: string | null + telegramUsername: string | null + signalNumber: string | null customerId: number | null createdAt: Date | null updatedAt: Date | null @@ -5386,6 +6994,9 @@ export namespace Prisma { lastName: number isActive: number tokenInvalidatedAt: number + whatsappNumber: number + telegramUsername: number + signalNumber: number customerId: number createdAt: number updatedAt: number @@ -5411,6 +7022,9 @@ export namespace Prisma { lastName?: true isActive?: true tokenInvalidatedAt?: true + whatsappNumber?: true + telegramUsername?: true + signalNumber?: true customerId?: true createdAt?: true updatedAt?: true @@ -5424,6 +7038,9 @@ export namespace Prisma { lastName?: true isActive?: true tokenInvalidatedAt?: true + whatsappNumber?: true + telegramUsername?: true + signalNumber?: true customerId?: true createdAt?: true updatedAt?: true @@ -5437,6 +7054,9 @@ export namespace Prisma { lastName?: true isActive?: true tokenInvalidatedAt?: true + whatsappNumber?: true + telegramUsername?: true + signalNumber?: true customerId?: true createdAt?: true updatedAt?: true @@ -5537,6 +7157,9 @@ export namespace Prisma { lastName: string isActive: boolean tokenInvalidatedAt: Date | null + whatsappNumber: string | null + telegramUsername: string | null + signalNumber: string | null customerId: number | null createdAt: Date updatedAt: Date @@ -5569,6 +7192,9 @@ export namespace Prisma { lastName?: boolean isActive?: boolean tokenInvalidatedAt?: boolean + whatsappNumber?: boolean + telegramUsername?: boolean + signalNumber?: boolean customerId?: boolean createdAt?: boolean updatedAt?: boolean @@ -5586,6 +7212,9 @@ export namespace Prisma { lastName?: boolean isActive?: boolean tokenInvalidatedAt?: boolean + whatsappNumber?: boolean + telegramUsername?: boolean + signalNumber?: boolean customerId?: boolean createdAt?: boolean updatedAt?: boolean @@ -5611,6 +7240,9 @@ export namespace Prisma { lastName: string isActive: boolean tokenInvalidatedAt: Date | null + whatsappNumber: string | null + telegramUsername: string | null + signalNumber: string | null customerId: number | null createdAt: Date updatedAt: Date @@ -5992,6 +7624,9 @@ export namespace Prisma { readonly lastName: FieldRef<"User", 'String'> readonly isActive: FieldRef<"User", 'Boolean'> readonly tokenInvalidatedAt: FieldRef<"User", 'DateTime'> + readonly whatsappNumber: FieldRef<"User", 'String'> + readonly telegramUsername: FieldRef<"User", 'String'> + readonly signalNumber: FieldRef<"User", 'String'> readonly customerId: FieldRef<"User", 'Int'> readonly createdAt: FieldRef<"User", 'DateTime'> readonly updatedAt: FieldRef<"User", 'DateTime'> @@ -10030,6 +11665,7 @@ export namespace Prisma { commercialRegisterPath: string | null commercialRegisterNumber: string | null privacyPolicyPath: string | null + consentHash: string | null notes: string | null portalEnabled: boolean | null portalEmail: string | null @@ -10059,6 +11695,7 @@ export namespace Prisma { commercialRegisterPath: string | null commercialRegisterNumber: string | null privacyPolicyPath: string | null + consentHash: string | null notes: string | null portalEnabled: boolean | null portalEmail: string | null @@ -10088,6 +11725,7 @@ export namespace Prisma { commercialRegisterPath: number commercialRegisterNumber: number privacyPolicyPath: number + consentHash: number notes: number portalEnabled: number portalEmail: number @@ -10127,6 +11765,7 @@ export namespace Prisma { commercialRegisterPath?: true commercialRegisterNumber?: true privacyPolicyPath?: true + consentHash?: true notes?: true portalEnabled?: true portalEmail?: true @@ -10156,6 +11795,7 @@ export namespace Prisma { commercialRegisterPath?: true commercialRegisterNumber?: true privacyPolicyPath?: true + consentHash?: true notes?: true portalEnabled?: true portalEmail?: true @@ -10185,6 +11825,7 @@ export namespace Prisma { commercialRegisterPath?: true commercialRegisterNumber?: true privacyPolicyPath?: true + consentHash?: true notes?: true portalEnabled?: true portalEmail?: true @@ -10301,6 +11942,7 @@ export namespace Prisma { commercialRegisterPath: string | null commercialRegisterNumber: string | null privacyPolicyPath: string | null + consentHash: string | null notes: string | null portalEnabled: boolean portalEmail: string | null @@ -10349,6 +11991,7 @@ export namespace Prisma { commercialRegisterPath?: boolean commercialRegisterNumber?: boolean privacyPolicyPath?: boolean + consentHash?: boolean notes?: boolean portalEnabled?: boolean portalEmail?: boolean @@ -10366,6 +12009,9 @@ export namespace Prisma { contracts?: boolean | Customer$contractsArgs representingFor?: boolean | Customer$representingForArgs representedBy?: boolean | Customer$representedByArgs + authorizationsGiven?: boolean | Customer$authorizationsGivenArgs + authorizationsReceived?: boolean | Customer$authorizationsReceivedArgs + consents?: boolean | Customer$consentsArgs _count?: boolean | CustomerCountOutputTypeDefaultArgs }, ExtArgs["result"]["customer"]> @@ -10389,6 +12035,7 @@ export namespace Prisma { commercialRegisterPath?: boolean commercialRegisterNumber?: boolean privacyPolicyPath?: boolean + consentHash?: boolean notes?: boolean portalEnabled?: boolean portalEmail?: boolean @@ -10409,6 +12056,9 @@ export namespace Prisma { contracts?: boolean | Customer$contractsArgs representingFor?: boolean | Customer$representingForArgs representedBy?: boolean | Customer$representedByArgs + authorizationsGiven?: boolean | Customer$authorizationsGivenArgs + authorizationsReceived?: boolean | Customer$authorizationsReceivedArgs + consents?: boolean | Customer$consentsArgs _count?: boolean | CustomerCountOutputTypeDefaultArgs } @@ -10424,6 +12074,9 @@ export namespace Prisma { contracts: Prisma.$ContractPayload[] representingFor: Prisma.$CustomerRepresentativePayload[] representedBy: Prisma.$CustomerRepresentativePayload[] + authorizationsGiven: Prisma.$RepresentativeAuthorizationPayload[] + authorizationsReceived: Prisma.$RepresentativeAuthorizationPayload[] + consents: Prisma.$CustomerConsentPayload[] } scalars: $Extensions.GetPayloadResult<{ id: number @@ -10444,6 +12097,7 @@ export namespace Prisma { commercialRegisterPath: string | null commercialRegisterNumber: string | null privacyPolicyPath: string | null + consentHash: string | null notes: string | null portalEnabled: boolean portalEmail: string | null @@ -10801,6 +12455,9 @@ export namespace Prisma { contracts = {}>(args?: Subset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany"> | Null> representingFor = {}>(args?: Subset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany"> | Null> representedBy = {}>(args?: Subset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany"> | Null> + authorizationsGiven = {}>(args?: Subset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany"> | Null> + authorizationsReceived = {}>(args?: Subset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany"> | Null> + consents = {}>(args?: Subset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany"> | Null> /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. @@ -10848,6 +12505,7 @@ export namespace Prisma { readonly commercialRegisterPath: FieldRef<"Customer", 'String'> readonly commercialRegisterNumber: FieldRef<"Customer", 'String'> readonly privacyPolicyPath: FieldRef<"Customer", 'String'> + readonly consentHash: FieldRef<"Customer", 'String'> readonly notes: FieldRef<"Customer", 'String'> readonly portalEnabled: FieldRef<"Customer", 'Boolean'> readonly portalEmail: FieldRef<"Customer", 'String'> @@ -11329,6 +12987,66 @@ export namespace Prisma { distinct?: CustomerRepresentativeScalarFieldEnum | CustomerRepresentativeScalarFieldEnum[] } + /** + * Customer.authorizationsGiven + */ + export type Customer$authorizationsGivenArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + where?: RepresentativeAuthorizationWhereInput + orderBy?: RepresentativeAuthorizationOrderByWithRelationInput | RepresentativeAuthorizationOrderByWithRelationInput[] + cursor?: RepresentativeAuthorizationWhereUniqueInput + take?: number + skip?: number + distinct?: RepresentativeAuthorizationScalarFieldEnum | RepresentativeAuthorizationScalarFieldEnum[] + } + + /** + * Customer.authorizationsReceived + */ + export type Customer$authorizationsReceivedArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + where?: RepresentativeAuthorizationWhereInput + orderBy?: RepresentativeAuthorizationOrderByWithRelationInput | RepresentativeAuthorizationOrderByWithRelationInput[] + cursor?: RepresentativeAuthorizationWhereUniqueInput + take?: number + skip?: number + distinct?: RepresentativeAuthorizationScalarFieldEnum | RepresentativeAuthorizationScalarFieldEnum[] + } + + /** + * Customer.consents + */ + export type Customer$consentsArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + where?: CustomerConsentWhereInput + orderBy?: CustomerConsentOrderByWithRelationInput | CustomerConsentOrderByWithRelationInput[] + cursor?: CustomerConsentWhereUniqueInput + take?: number + skip?: number + distinct?: CustomerConsentScalarFieldEnum | CustomerConsentScalarFieldEnum[] + } + /** * Customer without action */ @@ -12291,6 +14009,997 @@ export namespace Prisma { } + /** + * Model RepresentativeAuthorization + */ + + export type AggregateRepresentativeAuthorization = { + _count: RepresentativeAuthorizationCountAggregateOutputType | null + _avg: RepresentativeAuthorizationAvgAggregateOutputType | null + _sum: RepresentativeAuthorizationSumAggregateOutputType | null + _min: RepresentativeAuthorizationMinAggregateOutputType | null + _max: RepresentativeAuthorizationMaxAggregateOutputType | null + } + + export type RepresentativeAuthorizationAvgAggregateOutputType = { + id: number | null + customerId: number | null + representativeId: number | null + } + + export type RepresentativeAuthorizationSumAggregateOutputType = { + id: number | null + customerId: number | null + representativeId: number | null + } + + export type RepresentativeAuthorizationMinAggregateOutputType = { + id: number | null + customerId: number | null + representativeId: number | null + isGranted: boolean | null + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + notes: string | null + createdAt: Date | null + updatedAt: Date | null + } + + export type RepresentativeAuthorizationMaxAggregateOutputType = { + id: number | null + customerId: number | null + representativeId: number | null + isGranted: boolean | null + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + notes: string | null + createdAt: Date | null + updatedAt: Date | null + } + + export type RepresentativeAuthorizationCountAggregateOutputType = { + id: number + customerId: number + representativeId: number + isGranted: number + grantedAt: number + withdrawnAt: number + source: number + documentPath: number + notes: number + createdAt: number + updatedAt: number + _all: number + } + + + export type RepresentativeAuthorizationAvgAggregateInputType = { + id?: true + customerId?: true + representativeId?: true + } + + export type RepresentativeAuthorizationSumAggregateInputType = { + id?: true + customerId?: true + representativeId?: true + } + + export type RepresentativeAuthorizationMinAggregateInputType = { + id?: true + customerId?: true + representativeId?: true + isGranted?: true + grantedAt?: true + withdrawnAt?: true + source?: true + documentPath?: true + notes?: true + createdAt?: true + updatedAt?: true + } + + export type RepresentativeAuthorizationMaxAggregateInputType = { + id?: true + customerId?: true + representativeId?: true + isGranted?: true + grantedAt?: true + withdrawnAt?: true + source?: true + documentPath?: true + notes?: true + createdAt?: true + updatedAt?: true + } + + export type RepresentativeAuthorizationCountAggregateInputType = { + id?: true + customerId?: true + representativeId?: true + isGranted?: true + grantedAt?: true + withdrawnAt?: true + source?: true + documentPath?: true + notes?: true + createdAt?: true + updatedAt?: true + _all?: true + } + + export type RepresentativeAuthorizationAggregateArgs = { + /** + * Filter which RepresentativeAuthorization to aggregate. + */ + where?: RepresentativeAuthorizationWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of RepresentativeAuthorizations to fetch. + */ + orderBy?: RepresentativeAuthorizationOrderByWithRelationInput | RepresentativeAuthorizationOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the start position + */ + cursor?: RepresentativeAuthorizationWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` RepresentativeAuthorizations from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` RepresentativeAuthorizations. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Count returned RepresentativeAuthorizations + **/ + _count?: true | RepresentativeAuthorizationCountAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to average + **/ + _avg?: RepresentativeAuthorizationAvgAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to sum + **/ + _sum?: RepresentativeAuthorizationSumAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the minimum value + **/ + _min?: RepresentativeAuthorizationMinAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the maximum value + **/ + _max?: RepresentativeAuthorizationMaxAggregateInputType + } + + export type GetRepresentativeAuthorizationAggregateType = { + [P in keyof T & keyof AggregateRepresentativeAuthorization]: P extends '_count' | 'count' + ? T[P] extends true + ? number + : GetScalarType + : GetScalarType + } + + + + + export type RepresentativeAuthorizationGroupByArgs = { + where?: RepresentativeAuthorizationWhereInput + orderBy?: RepresentativeAuthorizationOrderByWithAggregationInput | RepresentativeAuthorizationOrderByWithAggregationInput[] + by: RepresentativeAuthorizationScalarFieldEnum[] | RepresentativeAuthorizationScalarFieldEnum + having?: RepresentativeAuthorizationScalarWhereWithAggregatesInput + take?: number + skip?: number + _count?: RepresentativeAuthorizationCountAggregateInputType | true + _avg?: RepresentativeAuthorizationAvgAggregateInputType + _sum?: RepresentativeAuthorizationSumAggregateInputType + _min?: RepresentativeAuthorizationMinAggregateInputType + _max?: RepresentativeAuthorizationMaxAggregateInputType + } + + export type RepresentativeAuthorizationGroupByOutputType = { + id: number + customerId: number + representativeId: number + isGranted: boolean + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + notes: string | null + createdAt: Date + updatedAt: Date + _count: RepresentativeAuthorizationCountAggregateOutputType | null + _avg: RepresentativeAuthorizationAvgAggregateOutputType | null + _sum: RepresentativeAuthorizationSumAggregateOutputType | null + _min: RepresentativeAuthorizationMinAggregateOutputType | null + _max: RepresentativeAuthorizationMaxAggregateOutputType | null + } + + type GetRepresentativeAuthorizationGroupByPayload = Prisma.PrismaPromise< + Array< + PickEnumerable & + { + [P in ((keyof T) & (keyof RepresentativeAuthorizationGroupByOutputType))]: P extends '_count' + ? T[P] extends boolean + ? number + : GetScalarType + : GetScalarType + } + > + > + + + export type RepresentativeAuthorizationSelect = $Extensions.GetSelect<{ + id?: boolean + customerId?: boolean + representativeId?: boolean + isGranted?: boolean + grantedAt?: boolean + withdrawnAt?: boolean + source?: boolean + documentPath?: boolean + notes?: boolean + createdAt?: boolean + updatedAt?: boolean + customer?: boolean | CustomerDefaultArgs + representative?: boolean | CustomerDefaultArgs + }, ExtArgs["result"]["representativeAuthorization"]> + + + export type RepresentativeAuthorizationSelectScalar = { + id?: boolean + customerId?: boolean + representativeId?: boolean + isGranted?: boolean + grantedAt?: boolean + withdrawnAt?: boolean + source?: boolean + documentPath?: boolean + notes?: boolean + createdAt?: boolean + updatedAt?: boolean + } + + export type RepresentativeAuthorizationInclude = { + customer?: boolean | CustomerDefaultArgs + representative?: boolean | CustomerDefaultArgs + } + + export type $RepresentativeAuthorizationPayload = { + name: "RepresentativeAuthorization" + objects: { + customer: Prisma.$CustomerPayload + representative: Prisma.$CustomerPayload + } + scalars: $Extensions.GetPayloadResult<{ + id: number + customerId: number + representativeId: number + isGranted: boolean + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + notes: string | null + createdAt: Date + updatedAt: Date + }, ExtArgs["result"]["representativeAuthorization"]> + composites: {} + } + + type RepresentativeAuthorizationGetPayload = $Result.GetResult + + type RepresentativeAuthorizationCountArgs = + Omit & { + select?: RepresentativeAuthorizationCountAggregateInputType | true + } + + export interface RepresentativeAuthorizationDelegate { + [K: symbol]: { types: Prisma.TypeMap['model']['RepresentativeAuthorization'], meta: { name: 'RepresentativeAuthorization' } } + /** + * Find zero or one RepresentativeAuthorization that matches the filter. + * @param {RepresentativeAuthorizationFindUniqueArgs} args - Arguments to find a RepresentativeAuthorization + * @example + * // Get one RepresentativeAuthorization + * const representativeAuthorization = await prisma.representativeAuthorization.findUnique({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUnique(args: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "findUnique"> | null, null, ExtArgs> + + /** + * Find one RepresentativeAuthorization that matches the filter or throw an error with `error.code='P2025'` + * if no matches were found. + * @param {RepresentativeAuthorizationFindUniqueOrThrowArgs} args - Arguments to find a RepresentativeAuthorization + * @example + * // Get one RepresentativeAuthorization + * const representativeAuthorization = await prisma.representativeAuthorization.findUniqueOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUniqueOrThrow(args: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "findUniqueOrThrow">, never, ExtArgs> + + /** + * Find the first RepresentativeAuthorization that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {RepresentativeAuthorizationFindFirstArgs} args - Arguments to find a RepresentativeAuthorization + * @example + * // Get one RepresentativeAuthorization + * const representativeAuthorization = await prisma.representativeAuthorization.findFirst({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirst(args?: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "findFirst"> | null, null, ExtArgs> + + /** + * Find the first RepresentativeAuthorization that matches the filter or + * throw `PrismaKnownClientError` with `P2025` code if no matches were found. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {RepresentativeAuthorizationFindFirstOrThrowArgs} args - Arguments to find a RepresentativeAuthorization + * @example + * // Get one RepresentativeAuthorization + * const representativeAuthorization = await prisma.representativeAuthorization.findFirstOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirstOrThrow(args?: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "findFirstOrThrow">, never, ExtArgs> + + /** + * Find zero or more RepresentativeAuthorizations that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {RepresentativeAuthorizationFindManyArgs} args - Arguments to filter and select certain fields only. + * @example + * // Get all RepresentativeAuthorizations + * const representativeAuthorizations = await prisma.representativeAuthorization.findMany() + * + * // Get first 10 RepresentativeAuthorizations + * const representativeAuthorizations = await prisma.representativeAuthorization.findMany({ take: 10 }) + * + * // Only select the `id` + * const representativeAuthorizationWithIdOnly = await prisma.representativeAuthorization.findMany({ select: { id: true } }) + * + */ + findMany(args?: SelectSubset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany">> + + /** + * Create a RepresentativeAuthorization. + * @param {RepresentativeAuthorizationCreateArgs} args - Arguments to create a RepresentativeAuthorization. + * @example + * // Create one RepresentativeAuthorization + * const RepresentativeAuthorization = await prisma.representativeAuthorization.create({ + * data: { + * // ... data to create a RepresentativeAuthorization + * } + * }) + * + */ + create(args: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "create">, never, ExtArgs> + + /** + * Create many RepresentativeAuthorizations. + * @param {RepresentativeAuthorizationCreateManyArgs} args - Arguments to create many RepresentativeAuthorizations. + * @example + * // Create many RepresentativeAuthorizations + * const representativeAuthorization = await prisma.representativeAuthorization.createMany({ + * data: [ + * // ... provide data here + * ] + * }) + * + */ + createMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Delete a RepresentativeAuthorization. + * @param {RepresentativeAuthorizationDeleteArgs} args - Arguments to delete one RepresentativeAuthorization. + * @example + * // Delete one RepresentativeAuthorization + * const RepresentativeAuthorization = await prisma.representativeAuthorization.delete({ + * where: { + * // ... filter to delete one RepresentativeAuthorization + * } + * }) + * + */ + delete(args: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "delete">, never, ExtArgs> + + /** + * Update one RepresentativeAuthorization. + * @param {RepresentativeAuthorizationUpdateArgs} args - Arguments to update one RepresentativeAuthorization. + * @example + * // Update one RepresentativeAuthorization + * const representativeAuthorization = await prisma.representativeAuthorization.update({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + update(args: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "update">, never, ExtArgs> + + /** + * Delete zero or more RepresentativeAuthorizations. + * @param {RepresentativeAuthorizationDeleteManyArgs} args - Arguments to filter RepresentativeAuthorizations to delete. + * @example + * // Delete a few RepresentativeAuthorizations + * const { count } = await prisma.representativeAuthorization.deleteMany({ + * where: { + * // ... provide filter here + * } + * }) + * + */ + deleteMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Update zero or more RepresentativeAuthorizations. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {RepresentativeAuthorizationUpdateManyArgs} args - Arguments to update one or more rows. + * @example + * // Update many RepresentativeAuthorizations + * const representativeAuthorization = await prisma.representativeAuthorization.updateMany({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + updateMany(args: SelectSubset>): Prisma.PrismaPromise + + /** + * Create or update one RepresentativeAuthorization. + * @param {RepresentativeAuthorizationUpsertArgs} args - Arguments to update or create a RepresentativeAuthorization. + * @example + * // Update or create a RepresentativeAuthorization + * const representativeAuthorization = await prisma.representativeAuthorization.upsert({ + * create: { + * // ... data to create a RepresentativeAuthorization + * }, + * update: { + * // ... in case it already exists, update + * }, + * where: { + * // ... the filter for the RepresentativeAuthorization we want to update + * } + * }) + */ + upsert(args: SelectSubset>): Prisma__RepresentativeAuthorizationClient<$Result.GetResult, T, "upsert">, never, ExtArgs> + + + /** + * Count the number of RepresentativeAuthorizations. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {RepresentativeAuthorizationCountArgs} args - Arguments to filter RepresentativeAuthorizations to count. + * @example + * // Count the number of RepresentativeAuthorizations + * const count = await prisma.representativeAuthorization.count({ + * where: { + * // ... the filter for the RepresentativeAuthorizations we want to count + * } + * }) + **/ + count( + args?: Subset, + ): Prisma.PrismaPromise< + T extends $Utils.Record<'select', any> + ? T['select'] extends true + ? number + : GetScalarType + : number + > + + /** + * Allows you to perform aggregations operations on a RepresentativeAuthorization. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {RepresentativeAuthorizationAggregateArgs} args - Select which aggregations you would like to apply and on what fields. + * @example + * // Ordered by age ascending + * // Where email contains prisma.io + * // Limited to the 10 users + * const aggregations = await prisma.user.aggregate({ + * _avg: { + * age: true, + * }, + * where: { + * email: { + * contains: "prisma.io", + * }, + * }, + * orderBy: { + * age: "asc", + * }, + * take: 10, + * }) + **/ + aggregate(args: Subset): Prisma.PrismaPromise> + + /** + * Group by RepresentativeAuthorization. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {RepresentativeAuthorizationGroupByArgs} args - Group by arguments. + * @example + * // Group by city, order by createdAt, get count + * const result = await prisma.user.groupBy({ + * by: ['city', 'createdAt'], + * orderBy: { + * createdAt: true + * }, + * _count: { + * _all: true + * }, + * }) + * + **/ + groupBy< + T extends RepresentativeAuthorizationGroupByArgs, + HasSelectOrTake extends Or< + Extends<'skip', Keys>, + Extends<'take', Keys> + >, + OrderByArg extends True extends HasSelectOrTake + ? { orderBy: RepresentativeAuthorizationGroupByArgs['orderBy'] } + : { orderBy?: RepresentativeAuthorizationGroupByArgs['orderBy'] }, + OrderFields extends ExcludeUnderscoreKeys>>, + ByFields extends MaybeTupleToUnion, + ByValid extends Has, + HavingFields extends GetHavingFields, + HavingValid extends Has, + ByEmpty extends T['by'] extends never[] ? True : False, + InputErrors extends ByEmpty extends True + ? `Error: "by" must not be empty.` + : HavingValid extends False + ? { + [P in HavingFields]: P extends ByFields + ? never + : P extends string + ? `Error: Field "${P}" used in "having" needs to be provided in "by".` + : [ + Error, + 'Field ', + P, + ` in "having" needs to be provided in "by"`, + ] + }[HavingFields] + : 'take' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "take", you also need to provide "orderBy"' + : 'skip' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "skip", you also need to provide "orderBy"' + : ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + >(args: SubsetIntersection & InputErrors): {} extends InputErrors ? GetRepresentativeAuthorizationGroupByPayload : Prisma.PrismaPromise + /** + * Fields of the RepresentativeAuthorization model + */ + readonly fields: RepresentativeAuthorizationFieldRefs; + } + + /** + * The delegate class that acts as a "Promise-like" for RepresentativeAuthorization. + * Why is this prefixed with `Prisma__`? + * Because we want to prevent naming conflicts as mentioned in + * https://github.com/prisma/prisma-client-js/issues/707 + */ + export interface Prisma__RepresentativeAuthorizationClient extends Prisma.PrismaPromise { + readonly [Symbol.toStringTag]: "PrismaPromise" + customer = {}>(args?: Subset>): Prisma__CustomerClient<$Result.GetResult, T, "findUniqueOrThrow"> | Null, Null, ExtArgs> + representative = {}>(args?: Subset>): Prisma__CustomerClient<$Result.GetResult, T, "findUniqueOrThrow"> | Null, Null, ExtArgs> + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): $Utils.JsPromise + } + + + + + /** + * Fields of the RepresentativeAuthorization model + */ + interface RepresentativeAuthorizationFieldRefs { + readonly id: FieldRef<"RepresentativeAuthorization", 'Int'> + readonly customerId: FieldRef<"RepresentativeAuthorization", 'Int'> + readonly representativeId: FieldRef<"RepresentativeAuthorization", 'Int'> + readonly isGranted: FieldRef<"RepresentativeAuthorization", 'Boolean'> + readonly grantedAt: FieldRef<"RepresentativeAuthorization", 'DateTime'> + readonly withdrawnAt: FieldRef<"RepresentativeAuthorization", 'DateTime'> + readonly source: FieldRef<"RepresentativeAuthorization", 'String'> + readonly documentPath: FieldRef<"RepresentativeAuthorization", 'String'> + readonly notes: FieldRef<"RepresentativeAuthorization", 'String'> + readonly createdAt: FieldRef<"RepresentativeAuthorization", 'DateTime'> + readonly updatedAt: FieldRef<"RepresentativeAuthorization", 'DateTime'> + } + + + // Custom InputTypes + /** + * RepresentativeAuthorization findUnique + */ + export type RepresentativeAuthorizationFindUniqueArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * Filter, which RepresentativeAuthorization to fetch. + */ + where: RepresentativeAuthorizationWhereUniqueInput + } + + /** + * RepresentativeAuthorization findUniqueOrThrow + */ + export type RepresentativeAuthorizationFindUniqueOrThrowArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * Filter, which RepresentativeAuthorization to fetch. + */ + where: RepresentativeAuthorizationWhereUniqueInput + } + + /** + * RepresentativeAuthorization findFirst + */ + export type RepresentativeAuthorizationFindFirstArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * Filter, which RepresentativeAuthorization to fetch. + */ + where?: RepresentativeAuthorizationWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of RepresentativeAuthorizations to fetch. + */ + orderBy?: RepresentativeAuthorizationOrderByWithRelationInput | RepresentativeAuthorizationOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for RepresentativeAuthorizations. + */ + cursor?: RepresentativeAuthorizationWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` RepresentativeAuthorizations from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` RepresentativeAuthorizations. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of RepresentativeAuthorizations. + */ + distinct?: RepresentativeAuthorizationScalarFieldEnum | RepresentativeAuthorizationScalarFieldEnum[] + } + + /** + * RepresentativeAuthorization findFirstOrThrow + */ + export type RepresentativeAuthorizationFindFirstOrThrowArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * Filter, which RepresentativeAuthorization to fetch. + */ + where?: RepresentativeAuthorizationWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of RepresentativeAuthorizations to fetch. + */ + orderBy?: RepresentativeAuthorizationOrderByWithRelationInput | RepresentativeAuthorizationOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for RepresentativeAuthorizations. + */ + cursor?: RepresentativeAuthorizationWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` RepresentativeAuthorizations from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` RepresentativeAuthorizations. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of RepresentativeAuthorizations. + */ + distinct?: RepresentativeAuthorizationScalarFieldEnum | RepresentativeAuthorizationScalarFieldEnum[] + } + + /** + * RepresentativeAuthorization findMany + */ + export type RepresentativeAuthorizationFindManyArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * Filter, which RepresentativeAuthorizations to fetch. + */ + where?: RepresentativeAuthorizationWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of RepresentativeAuthorizations to fetch. + */ + orderBy?: RepresentativeAuthorizationOrderByWithRelationInput | RepresentativeAuthorizationOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for listing RepresentativeAuthorizations. + */ + cursor?: RepresentativeAuthorizationWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` RepresentativeAuthorizations from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` RepresentativeAuthorizations. + */ + skip?: number + distinct?: RepresentativeAuthorizationScalarFieldEnum | RepresentativeAuthorizationScalarFieldEnum[] + } + + /** + * RepresentativeAuthorization create + */ + export type RepresentativeAuthorizationCreateArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * The data needed to create a RepresentativeAuthorization. + */ + data: XOR + } + + /** + * RepresentativeAuthorization createMany + */ + export type RepresentativeAuthorizationCreateManyArgs = { + /** + * The data used to create many RepresentativeAuthorizations. + */ + data: RepresentativeAuthorizationCreateManyInput | RepresentativeAuthorizationCreateManyInput[] + skipDuplicates?: boolean + } + + /** + * RepresentativeAuthorization update + */ + export type RepresentativeAuthorizationUpdateArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * The data needed to update a RepresentativeAuthorization. + */ + data: XOR + /** + * Choose, which RepresentativeAuthorization to update. + */ + where: RepresentativeAuthorizationWhereUniqueInput + } + + /** + * RepresentativeAuthorization updateMany + */ + export type RepresentativeAuthorizationUpdateManyArgs = { + /** + * The data used to update RepresentativeAuthorizations. + */ + data: XOR + /** + * Filter which RepresentativeAuthorizations to update + */ + where?: RepresentativeAuthorizationWhereInput + } + + /** + * RepresentativeAuthorization upsert + */ + export type RepresentativeAuthorizationUpsertArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * The filter to search for the RepresentativeAuthorization to update in case it exists. + */ + where: RepresentativeAuthorizationWhereUniqueInput + /** + * In case the RepresentativeAuthorization found by the `where` argument doesn't exist, create a new RepresentativeAuthorization with this data. + */ + create: XOR + /** + * In case the RepresentativeAuthorization was found with the provided `where` argument, update it with this data. + */ + update: XOR + } + + /** + * RepresentativeAuthorization delete + */ + export type RepresentativeAuthorizationDeleteArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + /** + * Filter which RepresentativeAuthorization to delete. + */ + where: RepresentativeAuthorizationWhereUniqueInput + } + + /** + * RepresentativeAuthorization deleteMany + */ + export type RepresentativeAuthorizationDeleteManyArgs = { + /** + * Filter which RepresentativeAuthorizations to delete + */ + where?: RepresentativeAuthorizationWhereInput + } + + /** + * RepresentativeAuthorization without action + */ + export type RepresentativeAuthorizationDefaultArgs = { + /** + * Select specific fields to fetch from the RepresentativeAuthorization + */ + select?: RepresentativeAuthorizationSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: RepresentativeAuthorizationInclude | null + } + + /** * Model Address */ @@ -15405,6 +18114,8 @@ export namespace Prisma { imapEncryption: $Enums.MailEncryption | null smtpEncryption: $Enums.MailEncryption | null allowSelfSignedCerts: boolean | null + systemEmailAddress: string | null + systemEmailPasswordEncrypted: string | null isActive: boolean | null isDefault: boolean | null createdAt: Date | null @@ -15428,6 +18139,8 @@ export namespace Prisma { imapEncryption: $Enums.MailEncryption | null smtpEncryption: $Enums.MailEncryption | null allowSelfSignedCerts: boolean | null + systemEmailAddress: string | null + systemEmailPasswordEncrypted: string | null isActive: boolean | null isDefault: boolean | null createdAt: Date | null @@ -15451,6 +18164,8 @@ export namespace Prisma { imapEncryption: number smtpEncryption: number allowSelfSignedCerts: number + systemEmailAddress: number + systemEmailPasswordEncrypted: number isActive: number isDefault: number createdAt: number @@ -15488,6 +18203,8 @@ export namespace Prisma { imapEncryption?: true smtpEncryption?: true allowSelfSignedCerts?: true + systemEmailAddress?: true + systemEmailPasswordEncrypted?: true isActive?: true isDefault?: true createdAt?: true @@ -15511,6 +18228,8 @@ export namespace Prisma { imapEncryption?: true smtpEncryption?: true allowSelfSignedCerts?: true + systemEmailAddress?: true + systemEmailPasswordEncrypted?: true isActive?: true isDefault?: true createdAt?: true @@ -15534,6 +18253,8 @@ export namespace Prisma { imapEncryption?: true smtpEncryption?: true allowSelfSignedCerts?: true + systemEmailAddress?: true + systemEmailPasswordEncrypted?: true isActive?: true isDefault?: true createdAt?: true @@ -15644,6 +18365,8 @@ export namespace Prisma { imapEncryption: $Enums.MailEncryption smtpEncryption: $Enums.MailEncryption allowSelfSignedCerts: boolean + systemEmailAddress: string | null + systemEmailPasswordEncrypted: string | null isActive: boolean isDefault: boolean createdAt: Date @@ -15686,6 +18409,8 @@ export namespace Prisma { imapEncryption?: boolean smtpEncryption?: boolean allowSelfSignedCerts?: boolean + systemEmailAddress?: boolean + systemEmailPasswordEncrypted?: boolean isActive?: boolean isDefault?: boolean createdAt?: boolean @@ -15710,6 +18435,8 @@ export namespace Prisma { imapEncryption?: boolean smtpEncryption?: boolean allowSelfSignedCerts?: boolean + systemEmailAddress?: boolean + systemEmailPasswordEncrypted?: boolean isActive?: boolean isDefault?: boolean createdAt?: boolean @@ -15737,6 +18464,8 @@ export namespace Prisma { imapEncryption: $Enums.MailEncryption smtpEncryption: $Enums.MailEncryption allowSelfSignedCerts: boolean + systemEmailAddress: string | null + systemEmailPasswordEncrypted: string | null isActive: boolean isDefault: boolean createdAt: Date @@ -16126,6 +18855,8 @@ export namespace Prisma { readonly imapEncryption: FieldRef<"EmailProviderConfig", 'MailEncryption'> readonly smtpEncryption: FieldRef<"EmailProviderConfig", 'MailEncryption'> readonly allowSelfSignedCerts: FieldRef<"EmailProviderConfig", 'Boolean'> + readonly systemEmailAddress: FieldRef<"EmailProviderConfig", 'String'> + readonly systemEmailPasswordEncrypted: FieldRef<"EmailProviderConfig", 'String'> readonly isActive: FieldRef<"EmailProviderConfig", 'Boolean'> readonly isDefault: FieldRef<"EmailProviderConfig", 'Boolean'> readonly createdAt: FieldRef<"EmailProviderConfig", 'DateTime'> @@ -19657,6 +22388,10 @@ export namespace Prisma { value: number | null unit: string | null notes: string | null + reportedBy: string | null + status: $Enums.MeterReadingStatus | null + transferredAt: Date | null + transferredBy: string | null createdAt: Date | null } @@ -19667,6 +22402,10 @@ export namespace Prisma { value: number | null unit: string | null notes: string | null + reportedBy: string | null + status: $Enums.MeterReadingStatus | null + transferredAt: Date | null + transferredBy: string | null createdAt: Date | null } @@ -19677,6 +22416,10 @@ export namespace Prisma { value: number unit: number notes: number + reportedBy: number + status: number + transferredAt: number + transferredBy: number createdAt: number _all: number } @@ -19701,6 +22444,10 @@ export namespace Prisma { value?: true unit?: true notes?: true + reportedBy?: true + status?: true + transferredAt?: true + transferredBy?: true createdAt?: true } @@ -19711,6 +22458,10 @@ export namespace Prisma { value?: true unit?: true notes?: true + reportedBy?: true + status?: true + transferredAt?: true + transferredBy?: true createdAt?: true } @@ -19721,6 +22472,10 @@ export namespace Prisma { value?: true unit?: true notes?: true + reportedBy?: true + status?: true + transferredAt?: true + transferredBy?: true createdAt?: true _all?: true } @@ -19818,6 +22573,10 @@ export namespace Prisma { value: number unit: string notes: string | null + reportedBy: string | null + status: $Enums.MeterReadingStatus + transferredAt: Date | null + transferredBy: string | null createdAt: Date _count: MeterReadingCountAggregateOutputType | null _avg: MeterReadingAvgAggregateOutputType | null @@ -19847,6 +22606,10 @@ export namespace Prisma { value?: boolean unit?: boolean notes?: boolean + reportedBy?: boolean + status?: boolean + transferredAt?: boolean + transferredBy?: boolean createdAt?: boolean meter?: boolean | MeterDefaultArgs }, ExtArgs["result"]["meterReading"]> @@ -19859,6 +22622,10 @@ export namespace Prisma { value?: boolean unit?: boolean notes?: boolean + reportedBy?: boolean + status?: boolean + transferredAt?: boolean + transferredBy?: boolean createdAt?: boolean } @@ -19878,6 +22645,10 @@ export namespace Prisma { value: number unit: string notes: string | null + reportedBy: string | null + status: $Enums.MeterReadingStatus + transferredAt: Date | null + transferredBy: string | null createdAt: Date }, ExtArgs["result"]["meterReading"]> composites: {} @@ -20255,6 +23026,10 @@ export namespace Prisma { readonly value: FieldRef<"MeterReading", 'Float'> readonly unit: FieldRef<"MeterReading", 'String'> readonly notes: FieldRef<"MeterReading", 'String'> + readonly reportedBy: FieldRef<"MeterReading", 'String'> + readonly status: FieldRef<"MeterReading", 'MeterReadingStatus'> + readonly transferredAt: FieldRef<"MeterReading", 'DateTime'> + readonly transferredBy: FieldRef<"MeterReading", 'String'> readonly createdAt: FieldRef<"MeterReading", 'DateTime'> } @@ -38954,6 +41729,4007 @@ export namespace Prisma { } + /** + * Model AuditLog + */ + + export type AggregateAuditLog = { + _count: AuditLogCountAggregateOutputType | null + _avg: AuditLogAvgAggregateOutputType | null + _sum: AuditLogSumAggregateOutputType | null + _min: AuditLogMinAggregateOutputType | null + _max: AuditLogMaxAggregateOutputType | null + } + + export type AuditLogAvgAggregateOutputType = { + id: number | null + userId: number | null + customerId: number | null + dataSubjectId: number | null + durationMs: number | null + } + + export type AuditLogSumAggregateOutputType = { + id: number | null + userId: number | null + customerId: number | null + dataSubjectId: number | null + durationMs: number | null + } + + export type AuditLogMinAggregateOutputType = { + id: number | null + userId: number | null + userEmail: string | null + userRole: string | null + customerId: number | null + isCustomerPortal: boolean | null + action: $Enums.AuditAction | null + sensitivity: $Enums.AuditSensitivity | null + resourceType: string | null + resourceId: string | null + resourceLabel: string | null + endpoint: string | null + httpMethod: string | null + ipAddress: string | null + userAgent: string | null + changesBefore: string | null + changesAfter: string | null + changesEncrypted: boolean | null + dataSubjectId: number | null + legalBasis: string | null + success: boolean | null + errorMessage: string | null + durationMs: number | null + createdAt: Date | null + hash: string | null + previousHash: string | null + } + + export type AuditLogMaxAggregateOutputType = { + id: number | null + userId: number | null + userEmail: string | null + userRole: string | null + customerId: number | null + isCustomerPortal: boolean | null + action: $Enums.AuditAction | null + sensitivity: $Enums.AuditSensitivity | null + resourceType: string | null + resourceId: string | null + resourceLabel: string | null + endpoint: string | null + httpMethod: string | null + ipAddress: string | null + userAgent: string | null + changesBefore: string | null + changesAfter: string | null + changesEncrypted: boolean | null + dataSubjectId: number | null + legalBasis: string | null + success: boolean | null + errorMessage: string | null + durationMs: number | null + createdAt: Date | null + hash: string | null + previousHash: string | null + } + + export type AuditLogCountAggregateOutputType = { + id: number + userId: number + userEmail: number + userRole: number + customerId: number + isCustomerPortal: number + action: number + sensitivity: number + resourceType: number + resourceId: number + resourceLabel: number + endpoint: number + httpMethod: number + ipAddress: number + userAgent: number + changesBefore: number + changesAfter: number + changesEncrypted: number + dataSubjectId: number + legalBasis: number + success: number + errorMessage: number + durationMs: number + createdAt: number + hash: number + previousHash: number + _all: number + } + + + export type AuditLogAvgAggregateInputType = { + id?: true + userId?: true + customerId?: true + dataSubjectId?: true + durationMs?: true + } + + export type AuditLogSumAggregateInputType = { + id?: true + userId?: true + customerId?: true + dataSubjectId?: true + durationMs?: true + } + + export type AuditLogMinAggregateInputType = { + id?: true + userId?: true + userEmail?: true + userRole?: true + customerId?: true + isCustomerPortal?: true + action?: true + sensitivity?: true + resourceType?: true + resourceId?: true + resourceLabel?: true + endpoint?: true + httpMethod?: true + ipAddress?: true + userAgent?: true + changesBefore?: true + changesAfter?: true + changesEncrypted?: true + dataSubjectId?: true + legalBasis?: true + success?: true + errorMessage?: true + durationMs?: true + createdAt?: true + hash?: true + previousHash?: true + } + + export type AuditLogMaxAggregateInputType = { + id?: true + userId?: true + userEmail?: true + userRole?: true + customerId?: true + isCustomerPortal?: true + action?: true + sensitivity?: true + resourceType?: true + resourceId?: true + resourceLabel?: true + endpoint?: true + httpMethod?: true + ipAddress?: true + userAgent?: true + changesBefore?: true + changesAfter?: true + changesEncrypted?: true + dataSubjectId?: true + legalBasis?: true + success?: true + errorMessage?: true + durationMs?: true + createdAt?: true + hash?: true + previousHash?: true + } + + export type AuditLogCountAggregateInputType = { + id?: true + userId?: true + userEmail?: true + userRole?: true + customerId?: true + isCustomerPortal?: true + action?: true + sensitivity?: true + resourceType?: true + resourceId?: true + resourceLabel?: true + endpoint?: true + httpMethod?: true + ipAddress?: true + userAgent?: true + changesBefore?: true + changesAfter?: true + changesEncrypted?: true + dataSubjectId?: true + legalBasis?: true + success?: true + errorMessage?: true + durationMs?: true + createdAt?: true + hash?: true + previousHash?: true + _all?: true + } + + export type AuditLogAggregateArgs = { + /** + * Filter which AuditLog to aggregate. + */ + where?: AuditLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditLogs to fetch. + */ + orderBy?: AuditLogOrderByWithRelationInput | AuditLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the start position + */ + cursor?: AuditLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditLogs. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Count returned AuditLogs + **/ + _count?: true | AuditLogCountAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to average + **/ + _avg?: AuditLogAvgAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to sum + **/ + _sum?: AuditLogSumAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the minimum value + **/ + _min?: AuditLogMinAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the maximum value + **/ + _max?: AuditLogMaxAggregateInputType + } + + export type GetAuditLogAggregateType = { + [P in keyof T & keyof AggregateAuditLog]: P extends '_count' | 'count' + ? T[P] extends true + ? number + : GetScalarType + : GetScalarType + } + + + + + export type AuditLogGroupByArgs = { + where?: AuditLogWhereInput + orderBy?: AuditLogOrderByWithAggregationInput | AuditLogOrderByWithAggregationInput[] + by: AuditLogScalarFieldEnum[] | AuditLogScalarFieldEnum + having?: AuditLogScalarWhereWithAggregatesInput + take?: number + skip?: number + _count?: AuditLogCountAggregateInputType | true + _avg?: AuditLogAvgAggregateInputType + _sum?: AuditLogSumAggregateInputType + _min?: AuditLogMinAggregateInputType + _max?: AuditLogMaxAggregateInputType + } + + export type AuditLogGroupByOutputType = { + id: number + userId: number | null + userEmail: string + userRole: string | null + customerId: number | null + isCustomerPortal: boolean + action: $Enums.AuditAction + sensitivity: $Enums.AuditSensitivity + resourceType: string + resourceId: string | null + resourceLabel: string | null + endpoint: string + httpMethod: string + ipAddress: string + userAgent: string | null + changesBefore: string | null + changesAfter: string | null + changesEncrypted: boolean + dataSubjectId: number | null + legalBasis: string | null + success: boolean + errorMessage: string | null + durationMs: number | null + createdAt: Date + hash: string | null + previousHash: string | null + _count: AuditLogCountAggregateOutputType | null + _avg: AuditLogAvgAggregateOutputType | null + _sum: AuditLogSumAggregateOutputType | null + _min: AuditLogMinAggregateOutputType | null + _max: AuditLogMaxAggregateOutputType | null + } + + type GetAuditLogGroupByPayload = Prisma.PrismaPromise< + Array< + PickEnumerable & + { + [P in ((keyof T) & (keyof AuditLogGroupByOutputType))]: P extends '_count' + ? T[P] extends boolean + ? number + : GetScalarType + : GetScalarType + } + > + > + + + export type AuditLogSelect = $Extensions.GetSelect<{ + id?: boolean + userId?: boolean + userEmail?: boolean + userRole?: boolean + customerId?: boolean + isCustomerPortal?: boolean + action?: boolean + sensitivity?: boolean + resourceType?: boolean + resourceId?: boolean + resourceLabel?: boolean + endpoint?: boolean + httpMethod?: boolean + ipAddress?: boolean + userAgent?: boolean + changesBefore?: boolean + changesAfter?: boolean + changesEncrypted?: boolean + dataSubjectId?: boolean + legalBasis?: boolean + success?: boolean + errorMessage?: boolean + durationMs?: boolean + createdAt?: boolean + hash?: boolean + previousHash?: boolean + }, ExtArgs["result"]["auditLog"]> + + + export type AuditLogSelectScalar = { + id?: boolean + userId?: boolean + userEmail?: boolean + userRole?: boolean + customerId?: boolean + isCustomerPortal?: boolean + action?: boolean + sensitivity?: boolean + resourceType?: boolean + resourceId?: boolean + resourceLabel?: boolean + endpoint?: boolean + httpMethod?: boolean + ipAddress?: boolean + userAgent?: boolean + changesBefore?: boolean + changesAfter?: boolean + changesEncrypted?: boolean + dataSubjectId?: boolean + legalBasis?: boolean + success?: boolean + errorMessage?: boolean + durationMs?: boolean + createdAt?: boolean + hash?: boolean + previousHash?: boolean + } + + + export type $AuditLogPayload = { + name: "AuditLog" + objects: {} + scalars: $Extensions.GetPayloadResult<{ + id: number + userId: number | null + userEmail: string + userRole: string | null + customerId: number | null + isCustomerPortal: boolean + action: $Enums.AuditAction + sensitivity: $Enums.AuditSensitivity + resourceType: string + resourceId: string | null + resourceLabel: string | null + endpoint: string + httpMethod: string + ipAddress: string + userAgent: string | null + changesBefore: string | null + changesAfter: string | null + changesEncrypted: boolean + dataSubjectId: number | null + legalBasis: string | null + success: boolean + errorMessage: string | null + durationMs: number | null + createdAt: Date + hash: string | null + previousHash: string | null + }, ExtArgs["result"]["auditLog"]> + composites: {} + } + + type AuditLogGetPayload = $Result.GetResult + + type AuditLogCountArgs = + Omit & { + select?: AuditLogCountAggregateInputType | true + } + + export interface AuditLogDelegate { + [K: symbol]: { types: Prisma.TypeMap['model']['AuditLog'], meta: { name: 'AuditLog' } } + /** + * Find zero or one AuditLog that matches the filter. + * @param {AuditLogFindUniqueArgs} args - Arguments to find a AuditLog + * @example + * // Get one AuditLog + * const auditLog = await prisma.auditLog.findUnique({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUnique(args: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "findUnique"> | null, null, ExtArgs> + + /** + * Find one AuditLog that matches the filter or throw an error with `error.code='P2025'` + * if no matches were found. + * @param {AuditLogFindUniqueOrThrowArgs} args - Arguments to find a AuditLog + * @example + * // Get one AuditLog + * const auditLog = await prisma.auditLog.findUniqueOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUniqueOrThrow(args: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "findUniqueOrThrow">, never, ExtArgs> + + /** + * Find the first AuditLog that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditLogFindFirstArgs} args - Arguments to find a AuditLog + * @example + * // Get one AuditLog + * const auditLog = await prisma.auditLog.findFirst({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirst(args?: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "findFirst"> | null, null, ExtArgs> + + /** + * Find the first AuditLog that matches the filter or + * throw `PrismaKnownClientError` with `P2025` code if no matches were found. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditLogFindFirstOrThrowArgs} args - Arguments to find a AuditLog + * @example + * // Get one AuditLog + * const auditLog = await prisma.auditLog.findFirstOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirstOrThrow(args?: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "findFirstOrThrow">, never, ExtArgs> + + /** + * Find zero or more AuditLogs that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditLogFindManyArgs} args - Arguments to filter and select certain fields only. + * @example + * // Get all AuditLogs + * const auditLogs = await prisma.auditLog.findMany() + * + * // Get first 10 AuditLogs + * const auditLogs = await prisma.auditLog.findMany({ take: 10 }) + * + * // Only select the `id` + * const auditLogWithIdOnly = await prisma.auditLog.findMany({ select: { id: true } }) + * + */ + findMany(args?: SelectSubset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany">> + + /** + * Create a AuditLog. + * @param {AuditLogCreateArgs} args - Arguments to create a AuditLog. + * @example + * // Create one AuditLog + * const AuditLog = await prisma.auditLog.create({ + * data: { + * // ... data to create a AuditLog + * } + * }) + * + */ + create(args: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "create">, never, ExtArgs> + + /** + * Create many AuditLogs. + * @param {AuditLogCreateManyArgs} args - Arguments to create many AuditLogs. + * @example + * // Create many AuditLogs + * const auditLog = await prisma.auditLog.createMany({ + * data: [ + * // ... provide data here + * ] + * }) + * + */ + createMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Delete a AuditLog. + * @param {AuditLogDeleteArgs} args - Arguments to delete one AuditLog. + * @example + * // Delete one AuditLog + * const AuditLog = await prisma.auditLog.delete({ + * where: { + * // ... filter to delete one AuditLog + * } + * }) + * + */ + delete(args: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "delete">, never, ExtArgs> + + /** + * Update one AuditLog. + * @param {AuditLogUpdateArgs} args - Arguments to update one AuditLog. + * @example + * // Update one AuditLog + * const auditLog = await prisma.auditLog.update({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + update(args: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "update">, never, ExtArgs> + + /** + * Delete zero or more AuditLogs. + * @param {AuditLogDeleteManyArgs} args - Arguments to filter AuditLogs to delete. + * @example + * // Delete a few AuditLogs + * const { count } = await prisma.auditLog.deleteMany({ + * where: { + * // ... provide filter here + * } + * }) + * + */ + deleteMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Update zero or more AuditLogs. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditLogUpdateManyArgs} args - Arguments to update one or more rows. + * @example + * // Update many AuditLogs + * const auditLog = await prisma.auditLog.updateMany({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + updateMany(args: SelectSubset>): Prisma.PrismaPromise + + /** + * Create or update one AuditLog. + * @param {AuditLogUpsertArgs} args - Arguments to update or create a AuditLog. + * @example + * // Update or create a AuditLog + * const auditLog = await prisma.auditLog.upsert({ + * create: { + * // ... data to create a AuditLog + * }, + * update: { + * // ... in case it already exists, update + * }, + * where: { + * // ... the filter for the AuditLog we want to update + * } + * }) + */ + upsert(args: SelectSubset>): Prisma__AuditLogClient<$Result.GetResult, T, "upsert">, never, ExtArgs> + + + /** + * Count the number of AuditLogs. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditLogCountArgs} args - Arguments to filter AuditLogs to count. + * @example + * // Count the number of AuditLogs + * const count = await prisma.auditLog.count({ + * where: { + * // ... the filter for the AuditLogs we want to count + * } + * }) + **/ + count( + args?: Subset, + ): Prisma.PrismaPromise< + T extends $Utils.Record<'select', any> + ? T['select'] extends true + ? number + : GetScalarType + : number + > + + /** + * Allows you to perform aggregations operations on a AuditLog. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditLogAggregateArgs} args - Select which aggregations you would like to apply and on what fields. + * @example + * // Ordered by age ascending + * // Where email contains prisma.io + * // Limited to the 10 users + * const aggregations = await prisma.user.aggregate({ + * _avg: { + * age: true, + * }, + * where: { + * email: { + * contains: "prisma.io", + * }, + * }, + * orderBy: { + * age: "asc", + * }, + * take: 10, + * }) + **/ + aggregate(args: Subset): Prisma.PrismaPromise> + + /** + * Group by AuditLog. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditLogGroupByArgs} args - Group by arguments. + * @example + * // Group by city, order by createdAt, get count + * const result = await prisma.user.groupBy({ + * by: ['city', 'createdAt'], + * orderBy: { + * createdAt: true + * }, + * _count: { + * _all: true + * }, + * }) + * + **/ + groupBy< + T extends AuditLogGroupByArgs, + HasSelectOrTake extends Or< + Extends<'skip', Keys>, + Extends<'take', Keys> + >, + OrderByArg extends True extends HasSelectOrTake + ? { orderBy: AuditLogGroupByArgs['orderBy'] } + : { orderBy?: AuditLogGroupByArgs['orderBy'] }, + OrderFields extends ExcludeUnderscoreKeys>>, + ByFields extends MaybeTupleToUnion, + ByValid extends Has, + HavingFields extends GetHavingFields, + HavingValid extends Has, + ByEmpty extends T['by'] extends never[] ? True : False, + InputErrors extends ByEmpty extends True + ? `Error: "by" must not be empty.` + : HavingValid extends False + ? { + [P in HavingFields]: P extends ByFields + ? never + : P extends string + ? `Error: Field "${P}" used in "having" needs to be provided in "by".` + : [ + Error, + 'Field ', + P, + ` in "having" needs to be provided in "by"`, + ] + }[HavingFields] + : 'take' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "take", you also need to provide "orderBy"' + : 'skip' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "skip", you also need to provide "orderBy"' + : ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + >(args: SubsetIntersection & InputErrors): {} extends InputErrors ? GetAuditLogGroupByPayload : Prisma.PrismaPromise + /** + * Fields of the AuditLog model + */ + readonly fields: AuditLogFieldRefs; + } + + /** + * The delegate class that acts as a "Promise-like" for AuditLog. + * Why is this prefixed with `Prisma__`? + * Because we want to prevent naming conflicts as mentioned in + * https://github.com/prisma/prisma-client-js/issues/707 + */ + export interface Prisma__AuditLogClient extends Prisma.PrismaPromise { + readonly [Symbol.toStringTag]: "PrismaPromise" + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): $Utils.JsPromise + } + + + + + /** + * Fields of the AuditLog model + */ + interface AuditLogFieldRefs { + readonly id: FieldRef<"AuditLog", 'Int'> + readonly userId: FieldRef<"AuditLog", 'Int'> + readonly userEmail: FieldRef<"AuditLog", 'String'> + readonly userRole: FieldRef<"AuditLog", 'String'> + readonly customerId: FieldRef<"AuditLog", 'Int'> + readonly isCustomerPortal: FieldRef<"AuditLog", 'Boolean'> + readonly action: FieldRef<"AuditLog", 'AuditAction'> + readonly sensitivity: FieldRef<"AuditLog", 'AuditSensitivity'> + readonly resourceType: FieldRef<"AuditLog", 'String'> + readonly resourceId: FieldRef<"AuditLog", 'String'> + readonly resourceLabel: FieldRef<"AuditLog", 'String'> + readonly endpoint: FieldRef<"AuditLog", 'String'> + readonly httpMethod: FieldRef<"AuditLog", 'String'> + readonly ipAddress: FieldRef<"AuditLog", 'String'> + readonly userAgent: FieldRef<"AuditLog", 'String'> + readonly changesBefore: FieldRef<"AuditLog", 'String'> + readonly changesAfter: FieldRef<"AuditLog", 'String'> + readonly changesEncrypted: FieldRef<"AuditLog", 'Boolean'> + readonly dataSubjectId: FieldRef<"AuditLog", 'Int'> + readonly legalBasis: FieldRef<"AuditLog", 'String'> + readonly success: FieldRef<"AuditLog", 'Boolean'> + readonly errorMessage: FieldRef<"AuditLog", 'String'> + readonly durationMs: FieldRef<"AuditLog", 'Int'> + readonly createdAt: FieldRef<"AuditLog", 'DateTime'> + readonly hash: FieldRef<"AuditLog", 'String'> + readonly previousHash: FieldRef<"AuditLog", 'String'> + } + + + // Custom InputTypes + /** + * AuditLog findUnique + */ + export type AuditLogFindUniqueArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * Filter, which AuditLog to fetch. + */ + where: AuditLogWhereUniqueInput + } + + /** + * AuditLog findUniqueOrThrow + */ + export type AuditLogFindUniqueOrThrowArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * Filter, which AuditLog to fetch. + */ + where: AuditLogWhereUniqueInput + } + + /** + * AuditLog findFirst + */ + export type AuditLogFindFirstArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * Filter, which AuditLog to fetch. + */ + where?: AuditLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditLogs to fetch. + */ + orderBy?: AuditLogOrderByWithRelationInput | AuditLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for AuditLogs. + */ + cursor?: AuditLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditLogs. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of AuditLogs. + */ + distinct?: AuditLogScalarFieldEnum | AuditLogScalarFieldEnum[] + } + + /** + * AuditLog findFirstOrThrow + */ + export type AuditLogFindFirstOrThrowArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * Filter, which AuditLog to fetch. + */ + where?: AuditLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditLogs to fetch. + */ + orderBy?: AuditLogOrderByWithRelationInput | AuditLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for AuditLogs. + */ + cursor?: AuditLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditLogs. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of AuditLogs. + */ + distinct?: AuditLogScalarFieldEnum | AuditLogScalarFieldEnum[] + } + + /** + * AuditLog findMany + */ + export type AuditLogFindManyArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * Filter, which AuditLogs to fetch. + */ + where?: AuditLogWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditLogs to fetch. + */ + orderBy?: AuditLogOrderByWithRelationInput | AuditLogOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for listing AuditLogs. + */ + cursor?: AuditLogWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditLogs from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditLogs. + */ + skip?: number + distinct?: AuditLogScalarFieldEnum | AuditLogScalarFieldEnum[] + } + + /** + * AuditLog create + */ + export type AuditLogCreateArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * The data needed to create a AuditLog. + */ + data: XOR + } + + /** + * AuditLog createMany + */ + export type AuditLogCreateManyArgs = { + /** + * The data used to create many AuditLogs. + */ + data: AuditLogCreateManyInput | AuditLogCreateManyInput[] + skipDuplicates?: boolean + } + + /** + * AuditLog update + */ + export type AuditLogUpdateArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * The data needed to update a AuditLog. + */ + data: XOR + /** + * Choose, which AuditLog to update. + */ + where: AuditLogWhereUniqueInput + } + + /** + * AuditLog updateMany + */ + export type AuditLogUpdateManyArgs = { + /** + * The data used to update AuditLogs. + */ + data: XOR + /** + * Filter which AuditLogs to update + */ + where?: AuditLogWhereInput + } + + /** + * AuditLog upsert + */ + export type AuditLogUpsertArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * The filter to search for the AuditLog to update in case it exists. + */ + where: AuditLogWhereUniqueInput + /** + * In case the AuditLog found by the `where` argument doesn't exist, create a new AuditLog with this data. + */ + create: XOR + /** + * In case the AuditLog was found with the provided `where` argument, update it with this data. + */ + update: XOR + } + + /** + * AuditLog delete + */ + export type AuditLogDeleteArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + /** + * Filter which AuditLog to delete. + */ + where: AuditLogWhereUniqueInput + } + + /** + * AuditLog deleteMany + */ + export type AuditLogDeleteManyArgs = { + /** + * Filter which AuditLogs to delete + */ + where?: AuditLogWhereInput + } + + /** + * AuditLog without action + */ + export type AuditLogDefaultArgs = { + /** + * Select specific fields to fetch from the AuditLog + */ + select?: AuditLogSelect | null + } + + + /** + * Model CustomerConsent + */ + + export type AggregateCustomerConsent = { + _count: CustomerConsentCountAggregateOutputType | null + _avg: CustomerConsentAvgAggregateOutputType | null + _sum: CustomerConsentSumAggregateOutputType | null + _min: CustomerConsentMinAggregateOutputType | null + _max: CustomerConsentMaxAggregateOutputType | null + } + + export type CustomerConsentAvgAggregateOutputType = { + id: number | null + customerId: number | null + } + + export type CustomerConsentSumAggregateOutputType = { + id: number | null + customerId: number | null + } + + export type CustomerConsentMinAggregateOutputType = { + id: number | null + customerId: number | null + consentType: $Enums.ConsentType | null + status: $Enums.ConsentStatus | null + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + version: string | null + ipAddress: string | null + createdBy: string | null + createdAt: Date | null + updatedAt: Date | null + } + + export type CustomerConsentMaxAggregateOutputType = { + id: number | null + customerId: number | null + consentType: $Enums.ConsentType | null + status: $Enums.ConsentStatus | null + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + version: string | null + ipAddress: string | null + createdBy: string | null + createdAt: Date | null + updatedAt: Date | null + } + + export type CustomerConsentCountAggregateOutputType = { + id: number + customerId: number + consentType: number + status: number + grantedAt: number + withdrawnAt: number + source: number + documentPath: number + version: number + ipAddress: number + createdBy: number + createdAt: number + updatedAt: number + _all: number + } + + + export type CustomerConsentAvgAggregateInputType = { + id?: true + customerId?: true + } + + export type CustomerConsentSumAggregateInputType = { + id?: true + customerId?: true + } + + export type CustomerConsentMinAggregateInputType = { + id?: true + customerId?: true + consentType?: true + status?: true + grantedAt?: true + withdrawnAt?: true + source?: true + documentPath?: true + version?: true + ipAddress?: true + createdBy?: true + createdAt?: true + updatedAt?: true + } + + export type CustomerConsentMaxAggregateInputType = { + id?: true + customerId?: true + consentType?: true + status?: true + grantedAt?: true + withdrawnAt?: true + source?: true + documentPath?: true + version?: true + ipAddress?: true + createdBy?: true + createdAt?: true + updatedAt?: true + } + + export type CustomerConsentCountAggregateInputType = { + id?: true + customerId?: true + consentType?: true + status?: true + grantedAt?: true + withdrawnAt?: true + source?: true + documentPath?: true + version?: true + ipAddress?: true + createdBy?: true + createdAt?: true + updatedAt?: true + _all?: true + } + + export type CustomerConsentAggregateArgs = { + /** + * Filter which CustomerConsent to aggregate. + */ + where?: CustomerConsentWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of CustomerConsents to fetch. + */ + orderBy?: CustomerConsentOrderByWithRelationInput | CustomerConsentOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the start position + */ + cursor?: CustomerConsentWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` CustomerConsents from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` CustomerConsents. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Count returned CustomerConsents + **/ + _count?: true | CustomerConsentCountAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to average + **/ + _avg?: CustomerConsentAvgAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to sum + **/ + _sum?: CustomerConsentSumAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the minimum value + **/ + _min?: CustomerConsentMinAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the maximum value + **/ + _max?: CustomerConsentMaxAggregateInputType + } + + export type GetCustomerConsentAggregateType = { + [P in keyof T & keyof AggregateCustomerConsent]: P extends '_count' | 'count' + ? T[P] extends true + ? number + : GetScalarType + : GetScalarType + } + + + + + export type CustomerConsentGroupByArgs = { + where?: CustomerConsentWhereInput + orderBy?: CustomerConsentOrderByWithAggregationInput | CustomerConsentOrderByWithAggregationInput[] + by: CustomerConsentScalarFieldEnum[] | CustomerConsentScalarFieldEnum + having?: CustomerConsentScalarWhereWithAggregatesInput + take?: number + skip?: number + _count?: CustomerConsentCountAggregateInputType | true + _avg?: CustomerConsentAvgAggregateInputType + _sum?: CustomerConsentSumAggregateInputType + _min?: CustomerConsentMinAggregateInputType + _max?: CustomerConsentMaxAggregateInputType + } + + export type CustomerConsentGroupByOutputType = { + id: number + customerId: number + consentType: $Enums.ConsentType + status: $Enums.ConsentStatus + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + version: string | null + ipAddress: string | null + createdBy: string + createdAt: Date + updatedAt: Date + _count: CustomerConsentCountAggregateOutputType | null + _avg: CustomerConsentAvgAggregateOutputType | null + _sum: CustomerConsentSumAggregateOutputType | null + _min: CustomerConsentMinAggregateOutputType | null + _max: CustomerConsentMaxAggregateOutputType | null + } + + type GetCustomerConsentGroupByPayload = Prisma.PrismaPromise< + Array< + PickEnumerable & + { + [P in ((keyof T) & (keyof CustomerConsentGroupByOutputType))]: P extends '_count' + ? T[P] extends boolean + ? number + : GetScalarType + : GetScalarType + } + > + > + + + export type CustomerConsentSelect = $Extensions.GetSelect<{ + id?: boolean + customerId?: boolean + consentType?: boolean + status?: boolean + grantedAt?: boolean + withdrawnAt?: boolean + source?: boolean + documentPath?: boolean + version?: boolean + ipAddress?: boolean + createdBy?: boolean + createdAt?: boolean + updatedAt?: boolean + customer?: boolean | CustomerDefaultArgs + }, ExtArgs["result"]["customerConsent"]> + + + export type CustomerConsentSelectScalar = { + id?: boolean + customerId?: boolean + consentType?: boolean + status?: boolean + grantedAt?: boolean + withdrawnAt?: boolean + source?: boolean + documentPath?: boolean + version?: boolean + ipAddress?: boolean + createdBy?: boolean + createdAt?: boolean + updatedAt?: boolean + } + + export type CustomerConsentInclude = { + customer?: boolean | CustomerDefaultArgs + } + + export type $CustomerConsentPayload = { + name: "CustomerConsent" + objects: { + customer: Prisma.$CustomerPayload + } + scalars: $Extensions.GetPayloadResult<{ + id: number + customerId: number + consentType: $Enums.ConsentType + status: $Enums.ConsentStatus + grantedAt: Date | null + withdrawnAt: Date | null + source: string | null + documentPath: string | null + version: string | null + ipAddress: string | null + createdBy: string + createdAt: Date + updatedAt: Date + }, ExtArgs["result"]["customerConsent"]> + composites: {} + } + + type CustomerConsentGetPayload = $Result.GetResult + + type CustomerConsentCountArgs = + Omit & { + select?: CustomerConsentCountAggregateInputType | true + } + + export interface CustomerConsentDelegate { + [K: symbol]: { types: Prisma.TypeMap['model']['CustomerConsent'], meta: { name: 'CustomerConsent' } } + /** + * Find zero or one CustomerConsent that matches the filter. + * @param {CustomerConsentFindUniqueArgs} args - Arguments to find a CustomerConsent + * @example + * // Get one CustomerConsent + * const customerConsent = await prisma.customerConsent.findUnique({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUnique(args: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "findUnique"> | null, null, ExtArgs> + + /** + * Find one CustomerConsent that matches the filter or throw an error with `error.code='P2025'` + * if no matches were found. + * @param {CustomerConsentFindUniqueOrThrowArgs} args - Arguments to find a CustomerConsent + * @example + * // Get one CustomerConsent + * const customerConsent = await prisma.customerConsent.findUniqueOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUniqueOrThrow(args: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "findUniqueOrThrow">, never, ExtArgs> + + /** + * Find the first CustomerConsent that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {CustomerConsentFindFirstArgs} args - Arguments to find a CustomerConsent + * @example + * // Get one CustomerConsent + * const customerConsent = await prisma.customerConsent.findFirst({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirst(args?: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "findFirst"> | null, null, ExtArgs> + + /** + * Find the first CustomerConsent that matches the filter or + * throw `PrismaKnownClientError` with `P2025` code if no matches were found. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {CustomerConsentFindFirstOrThrowArgs} args - Arguments to find a CustomerConsent + * @example + * // Get one CustomerConsent + * const customerConsent = await prisma.customerConsent.findFirstOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirstOrThrow(args?: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "findFirstOrThrow">, never, ExtArgs> + + /** + * Find zero or more CustomerConsents that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {CustomerConsentFindManyArgs} args - Arguments to filter and select certain fields only. + * @example + * // Get all CustomerConsents + * const customerConsents = await prisma.customerConsent.findMany() + * + * // Get first 10 CustomerConsents + * const customerConsents = await prisma.customerConsent.findMany({ take: 10 }) + * + * // Only select the `id` + * const customerConsentWithIdOnly = await prisma.customerConsent.findMany({ select: { id: true } }) + * + */ + findMany(args?: SelectSubset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany">> + + /** + * Create a CustomerConsent. + * @param {CustomerConsentCreateArgs} args - Arguments to create a CustomerConsent. + * @example + * // Create one CustomerConsent + * const CustomerConsent = await prisma.customerConsent.create({ + * data: { + * // ... data to create a CustomerConsent + * } + * }) + * + */ + create(args: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "create">, never, ExtArgs> + + /** + * Create many CustomerConsents. + * @param {CustomerConsentCreateManyArgs} args - Arguments to create many CustomerConsents. + * @example + * // Create many CustomerConsents + * const customerConsent = await prisma.customerConsent.createMany({ + * data: [ + * // ... provide data here + * ] + * }) + * + */ + createMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Delete a CustomerConsent. + * @param {CustomerConsentDeleteArgs} args - Arguments to delete one CustomerConsent. + * @example + * // Delete one CustomerConsent + * const CustomerConsent = await prisma.customerConsent.delete({ + * where: { + * // ... filter to delete one CustomerConsent + * } + * }) + * + */ + delete(args: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "delete">, never, ExtArgs> + + /** + * Update one CustomerConsent. + * @param {CustomerConsentUpdateArgs} args - Arguments to update one CustomerConsent. + * @example + * // Update one CustomerConsent + * const customerConsent = await prisma.customerConsent.update({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + update(args: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "update">, never, ExtArgs> + + /** + * Delete zero or more CustomerConsents. + * @param {CustomerConsentDeleteManyArgs} args - Arguments to filter CustomerConsents to delete. + * @example + * // Delete a few CustomerConsents + * const { count } = await prisma.customerConsent.deleteMany({ + * where: { + * // ... provide filter here + * } + * }) + * + */ + deleteMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Update zero or more CustomerConsents. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {CustomerConsentUpdateManyArgs} args - Arguments to update one or more rows. + * @example + * // Update many CustomerConsents + * const customerConsent = await prisma.customerConsent.updateMany({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + updateMany(args: SelectSubset>): Prisma.PrismaPromise + + /** + * Create or update one CustomerConsent. + * @param {CustomerConsentUpsertArgs} args - Arguments to update or create a CustomerConsent. + * @example + * // Update or create a CustomerConsent + * const customerConsent = await prisma.customerConsent.upsert({ + * create: { + * // ... data to create a CustomerConsent + * }, + * update: { + * // ... in case it already exists, update + * }, + * where: { + * // ... the filter for the CustomerConsent we want to update + * } + * }) + */ + upsert(args: SelectSubset>): Prisma__CustomerConsentClient<$Result.GetResult, T, "upsert">, never, ExtArgs> + + + /** + * Count the number of CustomerConsents. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {CustomerConsentCountArgs} args - Arguments to filter CustomerConsents to count. + * @example + * // Count the number of CustomerConsents + * const count = await prisma.customerConsent.count({ + * where: { + * // ... the filter for the CustomerConsents we want to count + * } + * }) + **/ + count( + args?: Subset, + ): Prisma.PrismaPromise< + T extends $Utils.Record<'select', any> + ? T['select'] extends true + ? number + : GetScalarType + : number + > + + /** + * Allows you to perform aggregations operations on a CustomerConsent. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {CustomerConsentAggregateArgs} args - Select which aggregations you would like to apply and on what fields. + * @example + * // Ordered by age ascending + * // Where email contains prisma.io + * // Limited to the 10 users + * const aggregations = await prisma.user.aggregate({ + * _avg: { + * age: true, + * }, + * where: { + * email: { + * contains: "prisma.io", + * }, + * }, + * orderBy: { + * age: "asc", + * }, + * take: 10, + * }) + **/ + aggregate(args: Subset): Prisma.PrismaPromise> + + /** + * Group by CustomerConsent. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {CustomerConsentGroupByArgs} args - Group by arguments. + * @example + * // Group by city, order by createdAt, get count + * const result = await prisma.user.groupBy({ + * by: ['city', 'createdAt'], + * orderBy: { + * createdAt: true + * }, + * _count: { + * _all: true + * }, + * }) + * + **/ + groupBy< + T extends CustomerConsentGroupByArgs, + HasSelectOrTake extends Or< + Extends<'skip', Keys>, + Extends<'take', Keys> + >, + OrderByArg extends True extends HasSelectOrTake + ? { orderBy: CustomerConsentGroupByArgs['orderBy'] } + : { orderBy?: CustomerConsentGroupByArgs['orderBy'] }, + OrderFields extends ExcludeUnderscoreKeys>>, + ByFields extends MaybeTupleToUnion, + ByValid extends Has, + HavingFields extends GetHavingFields, + HavingValid extends Has, + ByEmpty extends T['by'] extends never[] ? True : False, + InputErrors extends ByEmpty extends True + ? `Error: "by" must not be empty.` + : HavingValid extends False + ? { + [P in HavingFields]: P extends ByFields + ? never + : P extends string + ? `Error: Field "${P}" used in "having" needs to be provided in "by".` + : [ + Error, + 'Field ', + P, + ` in "having" needs to be provided in "by"`, + ] + }[HavingFields] + : 'take' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "take", you also need to provide "orderBy"' + : 'skip' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "skip", you also need to provide "orderBy"' + : ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + >(args: SubsetIntersection & InputErrors): {} extends InputErrors ? GetCustomerConsentGroupByPayload : Prisma.PrismaPromise + /** + * Fields of the CustomerConsent model + */ + readonly fields: CustomerConsentFieldRefs; + } + + /** + * The delegate class that acts as a "Promise-like" for CustomerConsent. + * Why is this prefixed with `Prisma__`? + * Because we want to prevent naming conflicts as mentioned in + * https://github.com/prisma/prisma-client-js/issues/707 + */ + export interface Prisma__CustomerConsentClient extends Prisma.PrismaPromise { + readonly [Symbol.toStringTag]: "PrismaPromise" + customer = {}>(args?: Subset>): Prisma__CustomerClient<$Result.GetResult, T, "findUniqueOrThrow"> | Null, Null, ExtArgs> + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): $Utils.JsPromise + } + + + + + /** + * Fields of the CustomerConsent model + */ + interface CustomerConsentFieldRefs { + readonly id: FieldRef<"CustomerConsent", 'Int'> + readonly customerId: FieldRef<"CustomerConsent", 'Int'> + readonly consentType: FieldRef<"CustomerConsent", 'ConsentType'> + readonly status: FieldRef<"CustomerConsent", 'ConsentStatus'> + readonly grantedAt: FieldRef<"CustomerConsent", 'DateTime'> + readonly withdrawnAt: FieldRef<"CustomerConsent", 'DateTime'> + readonly source: FieldRef<"CustomerConsent", 'String'> + readonly documentPath: FieldRef<"CustomerConsent", 'String'> + readonly version: FieldRef<"CustomerConsent", 'String'> + readonly ipAddress: FieldRef<"CustomerConsent", 'String'> + readonly createdBy: FieldRef<"CustomerConsent", 'String'> + readonly createdAt: FieldRef<"CustomerConsent", 'DateTime'> + readonly updatedAt: FieldRef<"CustomerConsent", 'DateTime'> + } + + + // Custom InputTypes + /** + * CustomerConsent findUnique + */ + export type CustomerConsentFindUniqueArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * Filter, which CustomerConsent to fetch. + */ + where: CustomerConsentWhereUniqueInput + } + + /** + * CustomerConsent findUniqueOrThrow + */ + export type CustomerConsentFindUniqueOrThrowArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * Filter, which CustomerConsent to fetch. + */ + where: CustomerConsentWhereUniqueInput + } + + /** + * CustomerConsent findFirst + */ + export type CustomerConsentFindFirstArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * Filter, which CustomerConsent to fetch. + */ + where?: CustomerConsentWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of CustomerConsents to fetch. + */ + orderBy?: CustomerConsentOrderByWithRelationInput | CustomerConsentOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for CustomerConsents. + */ + cursor?: CustomerConsentWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` CustomerConsents from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` CustomerConsents. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of CustomerConsents. + */ + distinct?: CustomerConsentScalarFieldEnum | CustomerConsentScalarFieldEnum[] + } + + /** + * CustomerConsent findFirstOrThrow + */ + export type CustomerConsentFindFirstOrThrowArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * Filter, which CustomerConsent to fetch. + */ + where?: CustomerConsentWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of CustomerConsents to fetch. + */ + orderBy?: CustomerConsentOrderByWithRelationInput | CustomerConsentOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for CustomerConsents. + */ + cursor?: CustomerConsentWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` CustomerConsents from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` CustomerConsents. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of CustomerConsents. + */ + distinct?: CustomerConsentScalarFieldEnum | CustomerConsentScalarFieldEnum[] + } + + /** + * CustomerConsent findMany + */ + export type CustomerConsentFindManyArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * Filter, which CustomerConsents to fetch. + */ + where?: CustomerConsentWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of CustomerConsents to fetch. + */ + orderBy?: CustomerConsentOrderByWithRelationInput | CustomerConsentOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for listing CustomerConsents. + */ + cursor?: CustomerConsentWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` CustomerConsents from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` CustomerConsents. + */ + skip?: number + distinct?: CustomerConsentScalarFieldEnum | CustomerConsentScalarFieldEnum[] + } + + /** + * CustomerConsent create + */ + export type CustomerConsentCreateArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * The data needed to create a CustomerConsent. + */ + data: XOR + } + + /** + * CustomerConsent createMany + */ + export type CustomerConsentCreateManyArgs = { + /** + * The data used to create many CustomerConsents. + */ + data: CustomerConsentCreateManyInput | CustomerConsentCreateManyInput[] + skipDuplicates?: boolean + } + + /** + * CustomerConsent update + */ + export type CustomerConsentUpdateArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * The data needed to update a CustomerConsent. + */ + data: XOR + /** + * Choose, which CustomerConsent to update. + */ + where: CustomerConsentWhereUniqueInput + } + + /** + * CustomerConsent updateMany + */ + export type CustomerConsentUpdateManyArgs = { + /** + * The data used to update CustomerConsents. + */ + data: XOR + /** + * Filter which CustomerConsents to update + */ + where?: CustomerConsentWhereInput + } + + /** + * CustomerConsent upsert + */ + export type CustomerConsentUpsertArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * The filter to search for the CustomerConsent to update in case it exists. + */ + where: CustomerConsentWhereUniqueInput + /** + * In case the CustomerConsent found by the `where` argument doesn't exist, create a new CustomerConsent with this data. + */ + create: XOR + /** + * In case the CustomerConsent was found with the provided `where` argument, update it with this data. + */ + update: XOR + } + + /** + * CustomerConsent delete + */ + export type CustomerConsentDeleteArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + /** + * Filter which CustomerConsent to delete. + */ + where: CustomerConsentWhereUniqueInput + } + + /** + * CustomerConsent deleteMany + */ + export type CustomerConsentDeleteManyArgs = { + /** + * Filter which CustomerConsents to delete + */ + where?: CustomerConsentWhereInput + } + + /** + * CustomerConsent without action + */ + export type CustomerConsentDefaultArgs = { + /** + * Select specific fields to fetch from the CustomerConsent + */ + select?: CustomerConsentSelect | null + /** + * Choose, which related nodes to fetch as well + */ + include?: CustomerConsentInclude | null + } + + + /** + * Model DataDeletionRequest + */ + + export type AggregateDataDeletionRequest = { + _count: DataDeletionRequestCountAggregateOutputType | null + _avg: DataDeletionRequestAvgAggregateOutputType | null + _sum: DataDeletionRequestSumAggregateOutputType | null + _min: DataDeletionRequestMinAggregateOutputType | null + _max: DataDeletionRequestMaxAggregateOutputType | null + } + + export type DataDeletionRequestAvgAggregateOutputType = { + id: number | null + customerId: number | null + } + + export type DataDeletionRequestSumAggregateOutputType = { + id: number | null + customerId: number | null + } + + export type DataDeletionRequestMinAggregateOutputType = { + id: number | null + customerId: number | null + status: $Enums.DeletionRequestStatus | null + requestedAt: Date | null + requestSource: string | null + requestedBy: string | null + processedAt: Date | null + processedBy: string | null + deletedData: string | null + retainedData: string | null + retentionReason: string | null + proofDocument: string | null + createdAt: Date | null + updatedAt: Date | null + } + + export type DataDeletionRequestMaxAggregateOutputType = { + id: number | null + customerId: number | null + status: $Enums.DeletionRequestStatus | null + requestedAt: Date | null + requestSource: string | null + requestedBy: string | null + processedAt: Date | null + processedBy: string | null + deletedData: string | null + retainedData: string | null + retentionReason: string | null + proofDocument: string | null + createdAt: Date | null + updatedAt: Date | null + } + + export type DataDeletionRequestCountAggregateOutputType = { + id: number + customerId: number + status: number + requestedAt: number + requestSource: number + requestedBy: number + processedAt: number + processedBy: number + deletedData: number + retainedData: number + retentionReason: number + proofDocument: number + createdAt: number + updatedAt: number + _all: number + } + + + export type DataDeletionRequestAvgAggregateInputType = { + id?: true + customerId?: true + } + + export type DataDeletionRequestSumAggregateInputType = { + id?: true + customerId?: true + } + + export type DataDeletionRequestMinAggregateInputType = { + id?: true + customerId?: true + status?: true + requestedAt?: true + requestSource?: true + requestedBy?: true + processedAt?: true + processedBy?: true + deletedData?: true + retainedData?: true + retentionReason?: true + proofDocument?: true + createdAt?: true + updatedAt?: true + } + + export type DataDeletionRequestMaxAggregateInputType = { + id?: true + customerId?: true + status?: true + requestedAt?: true + requestSource?: true + requestedBy?: true + processedAt?: true + processedBy?: true + deletedData?: true + retainedData?: true + retentionReason?: true + proofDocument?: true + createdAt?: true + updatedAt?: true + } + + export type DataDeletionRequestCountAggregateInputType = { + id?: true + customerId?: true + status?: true + requestedAt?: true + requestSource?: true + requestedBy?: true + processedAt?: true + processedBy?: true + deletedData?: true + retainedData?: true + retentionReason?: true + proofDocument?: true + createdAt?: true + updatedAt?: true + _all?: true + } + + export type DataDeletionRequestAggregateArgs = { + /** + * Filter which DataDeletionRequest to aggregate. + */ + where?: DataDeletionRequestWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of DataDeletionRequests to fetch. + */ + orderBy?: DataDeletionRequestOrderByWithRelationInput | DataDeletionRequestOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the start position + */ + cursor?: DataDeletionRequestWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` DataDeletionRequests from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` DataDeletionRequests. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Count returned DataDeletionRequests + **/ + _count?: true | DataDeletionRequestCountAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to average + **/ + _avg?: DataDeletionRequestAvgAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to sum + **/ + _sum?: DataDeletionRequestSumAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the minimum value + **/ + _min?: DataDeletionRequestMinAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the maximum value + **/ + _max?: DataDeletionRequestMaxAggregateInputType + } + + export type GetDataDeletionRequestAggregateType = { + [P in keyof T & keyof AggregateDataDeletionRequest]: P extends '_count' | 'count' + ? T[P] extends true + ? number + : GetScalarType + : GetScalarType + } + + + + + export type DataDeletionRequestGroupByArgs = { + where?: DataDeletionRequestWhereInput + orderBy?: DataDeletionRequestOrderByWithAggregationInput | DataDeletionRequestOrderByWithAggregationInput[] + by: DataDeletionRequestScalarFieldEnum[] | DataDeletionRequestScalarFieldEnum + having?: DataDeletionRequestScalarWhereWithAggregatesInput + take?: number + skip?: number + _count?: DataDeletionRequestCountAggregateInputType | true + _avg?: DataDeletionRequestAvgAggregateInputType + _sum?: DataDeletionRequestSumAggregateInputType + _min?: DataDeletionRequestMinAggregateInputType + _max?: DataDeletionRequestMaxAggregateInputType + } + + export type DataDeletionRequestGroupByOutputType = { + id: number + customerId: number + status: $Enums.DeletionRequestStatus + requestedAt: Date + requestSource: string + requestedBy: string + processedAt: Date | null + processedBy: string | null + deletedData: string | null + retainedData: string | null + retentionReason: string | null + proofDocument: string | null + createdAt: Date + updatedAt: Date + _count: DataDeletionRequestCountAggregateOutputType | null + _avg: DataDeletionRequestAvgAggregateOutputType | null + _sum: DataDeletionRequestSumAggregateOutputType | null + _min: DataDeletionRequestMinAggregateOutputType | null + _max: DataDeletionRequestMaxAggregateOutputType | null + } + + type GetDataDeletionRequestGroupByPayload = Prisma.PrismaPromise< + Array< + PickEnumerable & + { + [P in ((keyof T) & (keyof DataDeletionRequestGroupByOutputType))]: P extends '_count' + ? T[P] extends boolean + ? number + : GetScalarType + : GetScalarType + } + > + > + + + export type DataDeletionRequestSelect = $Extensions.GetSelect<{ + id?: boolean + customerId?: boolean + status?: boolean + requestedAt?: boolean + requestSource?: boolean + requestedBy?: boolean + processedAt?: boolean + processedBy?: boolean + deletedData?: boolean + retainedData?: boolean + retentionReason?: boolean + proofDocument?: boolean + createdAt?: boolean + updatedAt?: boolean + }, ExtArgs["result"]["dataDeletionRequest"]> + + + export type DataDeletionRequestSelectScalar = { + id?: boolean + customerId?: boolean + status?: boolean + requestedAt?: boolean + requestSource?: boolean + requestedBy?: boolean + processedAt?: boolean + processedBy?: boolean + deletedData?: boolean + retainedData?: boolean + retentionReason?: boolean + proofDocument?: boolean + createdAt?: boolean + updatedAt?: boolean + } + + + export type $DataDeletionRequestPayload = { + name: "DataDeletionRequest" + objects: {} + scalars: $Extensions.GetPayloadResult<{ + id: number + customerId: number + status: $Enums.DeletionRequestStatus + requestedAt: Date + requestSource: string + requestedBy: string + processedAt: Date | null + processedBy: string | null + deletedData: string | null + retainedData: string | null + retentionReason: string | null + proofDocument: string | null + createdAt: Date + updatedAt: Date + }, ExtArgs["result"]["dataDeletionRequest"]> + composites: {} + } + + type DataDeletionRequestGetPayload = $Result.GetResult + + type DataDeletionRequestCountArgs = + Omit & { + select?: DataDeletionRequestCountAggregateInputType | true + } + + export interface DataDeletionRequestDelegate { + [K: symbol]: { types: Prisma.TypeMap['model']['DataDeletionRequest'], meta: { name: 'DataDeletionRequest' } } + /** + * Find zero or one DataDeletionRequest that matches the filter. + * @param {DataDeletionRequestFindUniqueArgs} args - Arguments to find a DataDeletionRequest + * @example + * // Get one DataDeletionRequest + * const dataDeletionRequest = await prisma.dataDeletionRequest.findUnique({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUnique(args: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "findUnique"> | null, null, ExtArgs> + + /** + * Find one DataDeletionRequest that matches the filter or throw an error with `error.code='P2025'` + * if no matches were found. + * @param {DataDeletionRequestFindUniqueOrThrowArgs} args - Arguments to find a DataDeletionRequest + * @example + * // Get one DataDeletionRequest + * const dataDeletionRequest = await prisma.dataDeletionRequest.findUniqueOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUniqueOrThrow(args: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "findUniqueOrThrow">, never, ExtArgs> + + /** + * Find the first DataDeletionRequest that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {DataDeletionRequestFindFirstArgs} args - Arguments to find a DataDeletionRequest + * @example + * // Get one DataDeletionRequest + * const dataDeletionRequest = await prisma.dataDeletionRequest.findFirst({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirst(args?: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "findFirst"> | null, null, ExtArgs> + + /** + * Find the first DataDeletionRequest that matches the filter or + * throw `PrismaKnownClientError` with `P2025` code if no matches were found. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {DataDeletionRequestFindFirstOrThrowArgs} args - Arguments to find a DataDeletionRequest + * @example + * // Get one DataDeletionRequest + * const dataDeletionRequest = await prisma.dataDeletionRequest.findFirstOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirstOrThrow(args?: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "findFirstOrThrow">, never, ExtArgs> + + /** + * Find zero or more DataDeletionRequests that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {DataDeletionRequestFindManyArgs} args - Arguments to filter and select certain fields only. + * @example + * // Get all DataDeletionRequests + * const dataDeletionRequests = await prisma.dataDeletionRequest.findMany() + * + * // Get first 10 DataDeletionRequests + * const dataDeletionRequests = await prisma.dataDeletionRequest.findMany({ take: 10 }) + * + * // Only select the `id` + * const dataDeletionRequestWithIdOnly = await prisma.dataDeletionRequest.findMany({ select: { id: true } }) + * + */ + findMany(args?: SelectSubset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany">> + + /** + * Create a DataDeletionRequest. + * @param {DataDeletionRequestCreateArgs} args - Arguments to create a DataDeletionRequest. + * @example + * // Create one DataDeletionRequest + * const DataDeletionRequest = await prisma.dataDeletionRequest.create({ + * data: { + * // ... data to create a DataDeletionRequest + * } + * }) + * + */ + create(args: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "create">, never, ExtArgs> + + /** + * Create many DataDeletionRequests. + * @param {DataDeletionRequestCreateManyArgs} args - Arguments to create many DataDeletionRequests. + * @example + * // Create many DataDeletionRequests + * const dataDeletionRequest = await prisma.dataDeletionRequest.createMany({ + * data: [ + * // ... provide data here + * ] + * }) + * + */ + createMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Delete a DataDeletionRequest. + * @param {DataDeletionRequestDeleteArgs} args - Arguments to delete one DataDeletionRequest. + * @example + * // Delete one DataDeletionRequest + * const DataDeletionRequest = await prisma.dataDeletionRequest.delete({ + * where: { + * // ... filter to delete one DataDeletionRequest + * } + * }) + * + */ + delete(args: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "delete">, never, ExtArgs> + + /** + * Update one DataDeletionRequest. + * @param {DataDeletionRequestUpdateArgs} args - Arguments to update one DataDeletionRequest. + * @example + * // Update one DataDeletionRequest + * const dataDeletionRequest = await prisma.dataDeletionRequest.update({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + update(args: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "update">, never, ExtArgs> + + /** + * Delete zero or more DataDeletionRequests. + * @param {DataDeletionRequestDeleteManyArgs} args - Arguments to filter DataDeletionRequests to delete. + * @example + * // Delete a few DataDeletionRequests + * const { count } = await prisma.dataDeletionRequest.deleteMany({ + * where: { + * // ... provide filter here + * } + * }) + * + */ + deleteMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Update zero or more DataDeletionRequests. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {DataDeletionRequestUpdateManyArgs} args - Arguments to update one or more rows. + * @example + * // Update many DataDeletionRequests + * const dataDeletionRequest = await prisma.dataDeletionRequest.updateMany({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + updateMany(args: SelectSubset>): Prisma.PrismaPromise + + /** + * Create or update one DataDeletionRequest. + * @param {DataDeletionRequestUpsertArgs} args - Arguments to update or create a DataDeletionRequest. + * @example + * // Update or create a DataDeletionRequest + * const dataDeletionRequest = await prisma.dataDeletionRequest.upsert({ + * create: { + * // ... data to create a DataDeletionRequest + * }, + * update: { + * // ... in case it already exists, update + * }, + * where: { + * // ... the filter for the DataDeletionRequest we want to update + * } + * }) + */ + upsert(args: SelectSubset>): Prisma__DataDeletionRequestClient<$Result.GetResult, T, "upsert">, never, ExtArgs> + + + /** + * Count the number of DataDeletionRequests. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {DataDeletionRequestCountArgs} args - Arguments to filter DataDeletionRequests to count. + * @example + * // Count the number of DataDeletionRequests + * const count = await prisma.dataDeletionRequest.count({ + * where: { + * // ... the filter for the DataDeletionRequests we want to count + * } + * }) + **/ + count( + args?: Subset, + ): Prisma.PrismaPromise< + T extends $Utils.Record<'select', any> + ? T['select'] extends true + ? number + : GetScalarType + : number + > + + /** + * Allows you to perform aggregations operations on a DataDeletionRequest. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {DataDeletionRequestAggregateArgs} args - Select which aggregations you would like to apply and on what fields. + * @example + * // Ordered by age ascending + * // Where email contains prisma.io + * // Limited to the 10 users + * const aggregations = await prisma.user.aggregate({ + * _avg: { + * age: true, + * }, + * where: { + * email: { + * contains: "prisma.io", + * }, + * }, + * orderBy: { + * age: "asc", + * }, + * take: 10, + * }) + **/ + aggregate(args: Subset): Prisma.PrismaPromise> + + /** + * Group by DataDeletionRequest. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {DataDeletionRequestGroupByArgs} args - Group by arguments. + * @example + * // Group by city, order by createdAt, get count + * const result = await prisma.user.groupBy({ + * by: ['city', 'createdAt'], + * orderBy: { + * createdAt: true + * }, + * _count: { + * _all: true + * }, + * }) + * + **/ + groupBy< + T extends DataDeletionRequestGroupByArgs, + HasSelectOrTake extends Or< + Extends<'skip', Keys>, + Extends<'take', Keys> + >, + OrderByArg extends True extends HasSelectOrTake + ? { orderBy: DataDeletionRequestGroupByArgs['orderBy'] } + : { orderBy?: DataDeletionRequestGroupByArgs['orderBy'] }, + OrderFields extends ExcludeUnderscoreKeys>>, + ByFields extends MaybeTupleToUnion, + ByValid extends Has, + HavingFields extends GetHavingFields, + HavingValid extends Has, + ByEmpty extends T['by'] extends never[] ? True : False, + InputErrors extends ByEmpty extends True + ? `Error: "by" must not be empty.` + : HavingValid extends False + ? { + [P in HavingFields]: P extends ByFields + ? never + : P extends string + ? `Error: Field "${P}" used in "having" needs to be provided in "by".` + : [ + Error, + 'Field ', + P, + ` in "having" needs to be provided in "by"`, + ] + }[HavingFields] + : 'take' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "take", you also need to provide "orderBy"' + : 'skip' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "skip", you also need to provide "orderBy"' + : ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + >(args: SubsetIntersection & InputErrors): {} extends InputErrors ? GetDataDeletionRequestGroupByPayload : Prisma.PrismaPromise + /** + * Fields of the DataDeletionRequest model + */ + readonly fields: DataDeletionRequestFieldRefs; + } + + /** + * The delegate class that acts as a "Promise-like" for DataDeletionRequest. + * Why is this prefixed with `Prisma__`? + * Because we want to prevent naming conflicts as mentioned in + * https://github.com/prisma/prisma-client-js/issues/707 + */ + export interface Prisma__DataDeletionRequestClient extends Prisma.PrismaPromise { + readonly [Symbol.toStringTag]: "PrismaPromise" + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): $Utils.JsPromise + } + + + + + /** + * Fields of the DataDeletionRequest model + */ + interface DataDeletionRequestFieldRefs { + readonly id: FieldRef<"DataDeletionRequest", 'Int'> + readonly customerId: FieldRef<"DataDeletionRequest", 'Int'> + readonly status: FieldRef<"DataDeletionRequest", 'DeletionRequestStatus'> + readonly requestedAt: FieldRef<"DataDeletionRequest", 'DateTime'> + readonly requestSource: FieldRef<"DataDeletionRequest", 'String'> + readonly requestedBy: FieldRef<"DataDeletionRequest", 'String'> + readonly processedAt: FieldRef<"DataDeletionRequest", 'DateTime'> + readonly processedBy: FieldRef<"DataDeletionRequest", 'String'> + readonly deletedData: FieldRef<"DataDeletionRequest", 'String'> + readonly retainedData: FieldRef<"DataDeletionRequest", 'String'> + readonly retentionReason: FieldRef<"DataDeletionRequest", 'String'> + readonly proofDocument: FieldRef<"DataDeletionRequest", 'String'> + readonly createdAt: FieldRef<"DataDeletionRequest", 'DateTime'> + readonly updatedAt: FieldRef<"DataDeletionRequest", 'DateTime'> + } + + + // Custom InputTypes + /** + * DataDeletionRequest findUnique + */ + export type DataDeletionRequestFindUniqueArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * Filter, which DataDeletionRequest to fetch. + */ + where: DataDeletionRequestWhereUniqueInput + } + + /** + * DataDeletionRequest findUniqueOrThrow + */ + export type DataDeletionRequestFindUniqueOrThrowArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * Filter, which DataDeletionRequest to fetch. + */ + where: DataDeletionRequestWhereUniqueInput + } + + /** + * DataDeletionRequest findFirst + */ + export type DataDeletionRequestFindFirstArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * Filter, which DataDeletionRequest to fetch. + */ + where?: DataDeletionRequestWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of DataDeletionRequests to fetch. + */ + orderBy?: DataDeletionRequestOrderByWithRelationInput | DataDeletionRequestOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for DataDeletionRequests. + */ + cursor?: DataDeletionRequestWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` DataDeletionRequests from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` DataDeletionRequests. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of DataDeletionRequests. + */ + distinct?: DataDeletionRequestScalarFieldEnum | DataDeletionRequestScalarFieldEnum[] + } + + /** + * DataDeletionRequest findFirstOrThrow + */ + export type DataDeletionRequestFindFirstOrThrowArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * Filter, which DataDeletionRequest to fetch. + */ + where?: DataDeletionRequestWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of DataDeletionRequests to fetch. + */ + orderBy?: DataDeletionRequestOrderByWithRelationInput | DataDeletionRequestOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for DataDeletionRequests. + */ + cursor?: DataDeletionRequestWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` DataDeletionRequests from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` DataDeletionRequests. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of DataDeletionRequests. + */ + distinct?: DataDeletionRequestScalarFieldEnum | DataDeletionRequestScalarFieldEnum[] + } + + /** + * DataDeletionRequest findMany + */ + export type DataDeletionRequestFindManyArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * Filter, which DataDeletionRequests to fetch. + */ + where?: DataDeletionRequestWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of DataDeletionRequests to fetch. + */ + orderBy?: DataDeletionRequestOrderByWithRelationInput | DataDeletionRequestOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for listing DataDeletionRequests. + */ + cursor?: DataDeletionRequestWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` DataDeletionRequests from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` DataDeletionRequests. + */ + skip?: number + distinct?: DataDeletionRequestScalarFieldEnum | DataDeletionRequestScalarFieldEnum[] + } + + /** + * DataDeletionRequest create + */ + export type DataDeletionRequestCreateArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * The data needed to create a DataDeletionRequest. + */ + data: XOR + } + + /** + * DataDeletionRequest createMany + */ + export type DataDeletionRequestCreateManyArgs = { + /** + * The data used to create many DataDeletionRequests. + */ + data: DataDeletionRequestCreateManyInput | DataDeletionRequestCreateManyInput[] + skipDuplicates?: boolean + } + + /** + * DataDeletionRequest update + */ + export type DataDeletionRequestUpdateArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * The data needed to update a DataDeletionRequest. + */ + data: XOR + /** + * Choose, which DataDeletionRequest to update. + */ + where: DataDeletionRequestWhereUniqueInput + } + + /** + * DataDeletionRequest updateMany + */ + export type DataDeletionRequestUpdateManyArgs = { + /** + * The data used to update DataDeletionRequests. + */ + data: XOR + /** + * Filter which DataDeletionRequests to update + */ + where?: DataDeletionRequestWhereInput + } + + /** + * DataDeletionRequest upsert + */ + export type DataDeletionRequestUpsertArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * The filter to search for the DataDeletionRequest to update in case it exists. + */ + where: DataDeletionRequestWhereUniqueInput + /** + * In case the DataDeletionRequest found by the `where` argument doesn't exist, create a new DataDeletionRequest with this data. + */ + create: XOR + /** + * In case the DataDeletionRequest was found with the provided `where` argument, update it with this data. + */ + update: XOR + } + + /** + * DataDeletionRequest delete + */ + export type DataDeletionRequestDeleteArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + /** + * Filter which DataDeletionRequest to delete. + */ + where: DataDeletionRequestWhereUniqueInput + } + + /** + * DataDeletionRequest deleteMany + */ + export type DataDeletionRequestDeleteManyArgs = { + /** + * Filter which DataDeletionRequests to delete + */ + where?: DataDeletionRequestWhereInput + } + + /** + * DataDeletionRequest without action + */ + export type DataDeletionRequestDefaultArgs = { + /** + * Select specific fields to fetch from the DataDeletionRequest + */ + select?: DataDeletionRequestSelect | null + } + + + /** + * Model AuditRetentionPolicy + */ + + export type AggregateAuditRetentionPolicy = { + _count: AuditRetentionPolicyCountAggregateOutputType | null + _avg: AuditRetentionPolicyAvgAggregateOutputType | null + _sum: AuditRetentionPolicySumAggregateOutputType | null + _min: AuditRetentionPolicyMinAggregateOutputType | null + _max: AuditRetentionPolicyMaxAggregateOutputType | null + } + + export type AuditRetentionPolicyAvgAggregateOutputType = { + id: number | null + retentionDays: number | null + } + + export type AuditRetentionPolicySumAggregateOutputType = { + id: number | null + retentionDays: number | null + } + + export type AuditRetentionPolicyMinAggregateOutputType = { + id: number | null + resourceType: string | null + sensitivity: $Enums.AuditSensitivity | null + retentionDays: number | null + description: string | null + legalBasis: string | null + isActive: boolean | null + createdAt: Date | null + updatedAt: Date | null + } + + export type AuditRetentionPolicyMaxAggregateOutputType = { + id: number | null + resourceType: string | null + sensitivity: $Enums.AuditSensitivity | null + retentionDays: number | null + description: string | null + legalBasis: string | null + isActive: boolean | null + createdAt: Date | null + updatedAt: Date | null + } + + export type AuditRetentionPolicyCountAggregateOutputType = { + id: number + resourceType: number + sensitivity: number + retentionDays: number + description: number + legalBasis: number + isActive: number + createdAt: number + updatedAt: number + _all: number + } + + + export type AuditRetentionPolicyAvgAggregateInputType = { + id?: true + retentionDays?: true + } + + export type AuditRetentionPolicySumAggregateInputType = { + id?: true + retentionDays?: true + } + + export type AuditRetentionPolicyMinAggregateInputType = { + id?: true + resourceType?: true + sensitivity?: true + retentionDays?: true + description?: true + legalBasis?: true + isActive?: true + createdAt?: true + updatedAt?: true + } + + export type AuditRetentionPolicyMaxAggregateInputType = { + id?: true + resourceType?: true + sensitivity?: true + retentionDays?: true + description?: true + legalBasis?: true + isActive?: true + createdAt?: true + updatedAt?: true + } + + export type AuditRetentionPolicyCountAggregateInputType = { + id?: true + resourceType?: true + sensitivity?: true + retentionDays?: true + description?: true + legalBasis?: true + isActive?: true + createdAt?: true + updatedAt?: true + _all?: true + } + + export type AuditRetentionPolicyAggregateArgs = { + /** + * Filter which AuditRetentionPolicy to aggregate. + */ + where?: AuditRetentionPolicyWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditRetentionPolicies to fetch. + */ + orderBy?: AuditRetentionPolicyOrderByWithRelationInput | AuditRetentionPolicyOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the start position + */ + cursor?: AuditRetentionPolicyWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditRetentionPolicies from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditRetentionPolicies. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Count returned AuditRetentionPolicies + **/ + _count?: true | AuditRetentionPolicyCountAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to average + **/ + _avg?: AuditRetentionPolicyAvgAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to sum + **/ + _sum?: AuditRetentionPolicySumAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the minimum value + **/ + _min?: AuditRetentionPolicyMinAggregateInputType + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} + * + * Select which fields to find the maximum value + **/ + _max?: AuditRetentionPolicyMaxAggregateInputType + } + + export type GetAuditRetentionPolicyAggregateType = { + [P in keyof T & keyof AggregateAuditRetentionPolicy]: P extends '_count' | 'count' + ? T[P] extends true + ? number + : GetScalarType + : GetScalarType + } + + + + + export type AuditRetentionPolicyGroupByArgs = { + where?: AuditRetentionPolicyWhereInput + orderBy?: AuditRetentionPolicyOrderByWithAggregationInput | AuditRetentionPolicyOrderByWithAggregationInput[] + by: AuditRetentionPolicyScalarFieldEnum[] | AuditRetentionPolicyScalarFieldEnum + having?: AuditRetentionPolicyScalarWhereWithAggregatesInput + take?: number + skip?: number + _count?: AuditRetentionPolicyCountAggregateInputType | true + _avg?: AuditRetentionPolicyAvgAggregateInputType + _sum?: AuditRetentionPolicySumAggregateInputType + _min?: AuditRetentionPolicyMinAggregateInputType + _max?: AuditRetentionPolicyMaxAggregateInputType + } + + export type AuditRetentionPolicyGroupByOutputType = { + id: number + resourceType: string + sensitivity: $Enums.AuditSensitivity | null + retentionDays: number + description: string | null + legalBasis: string | null + isActive: boolean + createdAt: Date + updatedAt: Date + _count: AuditRetentionPolicyCountAggregateOutputType | null + _avg: AuditRetentionPolicyAvgAggregateOutputType | null + _sum: AuditRetentionPolicySumAggregateOutputType | null + _min: AuditRetentionPolicyMinAggregateOutputType | null + _max: AuditRetentionPolicyMaxAggregateOutputType | null + } + + type GetAuditRetentionPolicyGroupByPayload = Prisma.PrismaPromise< + Array< + PickEnumerable & + { + [P in ((keyof T) & (keyof AuditRetentionPolicyGroupByOutputType))]: P extends '_count' + ? T[P] extends boolean + ? number + : GetScalarType + : GetScalarType + } + > + > + + + export type AuditRetentionPolicySelect = $Extensions.GetSelect<{ + id?: boolean + resourceType?: boolean + sensitivity?: boolean + retentionDays?: boolean + description?: boolean + legalBasis?: boolean + isActive?: boolean + createdAt?: boolean + updatedAt?: boolean + }, ExtArgs["result"]["auditRetentionPolicy"]> + + + export type AuditRetentionPolicySelectScalar = { + id?: boolean + resourceType?: boolean + sensitivity?: boolean + retentionDays?: boolean + description?: boolean + legalBasis?: boolean + isActive?: boolean + createdAt?: boolean + updatedAt?: boolean + } + + + export type $AuditRetentionPolicyPayload = { + name: "AuditRetentionPolicy" + objects: {} + scalars: $Extensions.GetPayloadResult<{ + id: number + resourceType: string + sensitivity: $Enums.AuditSensitivity | null + retentionDays: number + description: string | null + legalBasis: string | null + isActive: boolean + createdAt: Date + updatedAt: Date + }, ExtArgs["result"]["auditRetentionPolicy"]> + composites: {} + } + + type AuditRetentionPolicyGetPayload = $Result.GetResult + + type AuditRetentionPolicyCountArgs = + Omit & { + select?: AuditRetentionPolicyCountAggregateInputType | true + } + + export interface AuditRetentionPolicyDelegate { + [K: symbol]: { types: Prisma.TypeMap['model']['AuditRetentionPolicy'], meta: { name: 'AuditRetentionPolicy' } } + /** + * Find zero or one AuditRetentionPolicy that matches the filter. + * @param {AuditRetentionPolicyFindUniqueArgs} args - Arguments to find a AuditRetentionPolicy + * @example + * // Get one AuditRetentionPolicy + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.findUnique({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUnique(args: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "findUnique"> | null, null, ExtArgs> + + /** + * Find one AuditRetentionPolicy that matches the filter or throw an error with `error.code='P2025'` + * if no matches were found. + * @param {AuditRetentionPolicyFindUniqueOrThrowArgs} args - Arguments to find a AuditRetentionPolicy + * @example + * // Get one AuditRetentionPolicy + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.findUniqueOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findUniqueOrThrow(args: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "findUniqueOrThrow">, never, ExtArgs> + + /** + * Find the first AuditRetentionPolicy that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditRetentionPolicyFindFirstArgs} args - Arguments to find a AuditRetentionPolicy + * @example + * // Get one AuditRetentionPolicy + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.findFirst({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirst(args?: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "findFirst"> | null, null, ExtArgs> + + /** + * Find the first AuditRetentionPolicy that matches the filter or + * throw `PrismaKnownClientError` with `P2025` code if no matches were found. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditRetentionPolicyFindFirstOrThrowArgs} args - Arguments to find a AuditRetentionPolicy + * @example + * // Get one AuditRetentionPolicy + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.findFirstOrThrow({ + * where: { + * // ... provide filter here + * } + * }) + */ + findFirstOrThrow(args?: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "findFirstOrThrow">, never, ExtArgs> + + /** + * Find zero or more AuditRetentionPolicies that matches the filter. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditRetentionPolicyFindManyArgs} args - Arguments to filter and select certain fields only. + * @example + * // Get all AuditRetentionPolicies + * const auditRetentionPolicies = await prisma.auditRetentionPolicy.findMany() + * + * // Get first 10 AuditRetentionPolicies + * const auditRetentionPolicies = await prisma.auditRetentionPolicy.findMany({ take: 10 }) + * + * // Only select the `id` + * const auditRetentionPolicyWithIdOnly = await prisma.auditRetentionPolicy.findMany({ select: { id: true } }) + * + */ + findMany(args?: SelectSubset>): Prisma.PrismaPromise<$Result.GetResult, T, "findMany">> + + /** + * Create a AuditRetentionPolicy. + * @param {AuditRetentionPolicyCreateArgs} args - Arguments to create a AuditRetentionPolicy. + * @example + * // Create one AuditRetentionPolicy + * const AuditRetentionPolicy = await prisma.auditRetentionPolicy.create({ + * data: { + * // ... data to create a AuditRetentionPolicy + * } + * }) + * + */ + create(args: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "create">, never, ExtArgs> + + /** + * Create many AuditRetentionPolicies. + * @param {AuditRetentionPolicyCreateManyArgs} args - Arguments to create many AuditRetentionPolicies. + * @example + * // Create many AuditRetentionPolicies + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.createMany({ + * data: [ + * // ... provide data here + * ] + * }) + * + */ + createMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Delete a AuditRetentionPolicy. + * @param {AuditRetentionPolicyDeleteArgs} args - Arguments to delete one AuditRetentionPolicy. + * @example + * // Delete one AuditRetentionPolicy + * const AuditRetentionPolicy = await prisma.auditRetentionPolicy.delete({ + * where: { + * // ... filter to delete one AuditRetentionPolicy + * } + * }) + * + */ + delete(args: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "delete">, never, ExtArgs> + + /** + * Update one AuditRetentionPolicy. + * @param {AuditRetentionPolicyUpdateArgs} args - Arguments to update one AuditRetentionPolicy. + * @example + * // Update one AuditRetentionPolicy + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.update({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + update(args: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "update">, never, ExtArgs> + + /** + * Delete zero or more AuditRetentionPolicies. + * @param {AuditRetentionPolicyDeleteManyArgs} args - Arguments to filter AuditRetentionPolicies to delete. + * @example + * // Delete a few AuditRetentionPolicies + * const { count } = await prisma.auditRetentionPolicy.deleteMany({ + * where: { + * // ... provide filter here + * } + * }) + * + */ + deleteMany(args?: SelectSubset>): Prisma.PrismaPromise + + /** + * Update zero or more AuditRetentionPolicies. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditRetentionPolicyUpdateManyArgs} args - Arguments to update one or more rows. + * @example + * // Update many AuditRetentionPolicies + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.updateMany({ + * where: { + * // ... provide filter here + * }, + * data: { + * // ... provide data here + * } + * }) + * + */ + updateMany(args: SelectSubset>): Prisma.PrismaPromise + + /** + * Create or update one AuditRetentionPolicy. + * @param {AuditRetentionPolicyUpsertArgs} args - Arguments to update or create a AuditRetentionPolicy. + * @example + * // Update or create a AuditRetentionPolicy + * const auditRetentionPolicy = await prisma.auditRetentionPolicy.upsert({ + * create: { + * // ... data to create a AuditRetentionPolicy + * }, + * update: { + * // ... in case it already exists, update + * }, + * where: { + * // ... the filter for the AuditRetentionPolicy we want to update + * } + * }) + */ + upsert(args: SelectSubset>): Prisma__AuditRetentionPolicyClient<$Result.GetResult, T, "upsert">, never, ExtArgs> + + + /** + * Count the number of AuditRetentionPolicies. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditRetentionPolicyCountArgs} args - Arguments to filter AuditRetentionPolicies to count. + * @example + * // Count the number of AuditRetentionPolicies + * const count = await prisma.auditRetentionPolicy.count({ + * where: { + * // ... the filter for the AuditRetentionPolicies we want to count + * } + * }) + **/ + count( + args?: Subset, + ): Prisma.PrismaPromise< + T extends $Utils.Record<'select', any> + ? T['select'] extends true + ? number + : GetScalarType + : number + > + + /** + * Allows you to perform aggregations operations on a AuditRetentionPolicy. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditRetentionPolicyAggregateArgs} args - Select which aggregations you would like to apply and on what fields. + * @example + * // Ordered by age ascending + * // Where email contains prisma.io + * // Limited to the 10 users + * const aggregations = await prisma.user.aggregate({ + * _avg: { + * age: true, + * }, + * where: { + * email: { + * contains: "prisma.io", + * }, + * }, + * orderBy: { + * age: "asc", + * }, + * take: 10, + * }) + **/ + aggregate(args: Subset): Prisma.PrismaPromise> + + /** + * Group by AuditRetentionPolicy. + * Note, that providing `undefined` is treated as the value not being there. + * Read more here: https://pris.ly/d/null-undefined + * @param {AuditRetentionPolicyGroupByArgs} args - Group by arguments. + * @example + * // Group by city, order by createdAt, get count + * const result = await prisma.user.groupBy({ + * by: ['city', 'createdAt'], + * orderBy: { + * createdAt: true + * }, + * _count: { + * _all: true + * }, + * }) + * + **/ + groupBy< + T extends AuditRetentionPolicyGroupByArgs, + HasSelectOrTake extends Or< + Extends<'skip', Keys>, + Extends<'take', Keys> + >, + OrderByArg extends True extends HasSelectOrTake + ? { orderBy: AuditRetentionPolicyGroupByArgs['orderBy'] } + : { orderBy?: AuditRetentionPolicyGroupByArgs['orderBy'] }, + OrderFields extends ExcludeUnderscoreKeys>>, + ByFields extends MaybeTupleToUnion, + ByValid extends Has, + HavingFields extends GetHavingFields, + HavingValid extends Has, + ByEmpty extends T['by'] extends never[] ? True : False, + InputErrors extends ByEmpty extends True + ? `Error: "by" must not be empty.` + : HavingValid extends False + ? { + [P in HavingFields]: P extends ByFields + ? never + : P extends string + ? `Error: Field "${P}" used in "having" needs to be provided in "by".` + : [ + Error, + 'Field ', + P, + ` in "having" needs to be provided in "by"`, + ] + }[HavingFields] + : 'take' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "take", you also need to provide "orderBy"' + : 'skip' extends Keys + ? 'orderBy' extends Keys + ? ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + : 'Error: If you provide "skip", you also need to provide "orderBy"' + : ByValid extends True + ? {} + : { + [P in OrderFields]: P extends ByFields + ? never + : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` + }[OrderFields] + >(args: SubsetIntersection & InputErrors): {} extends InputErrors ? GetAuditRetentionPolicyGroupByPayload : Prisma.PrismaPromise + /** + * Fields of the AuditRetentionPolicy model + */ + readonly fields: AuditRetentionPolicyFieldRefs; + } + + /** + * The delegate class that acts as a "Promise-like" for AuditRetentionPolicy. + * Why is this prefixed with `Prisma__`? + * Because we want to prevent naming conflicts as mentioned in + * https://github.com/prisma/prisma-client-js/issues/707 + */ + export interface Prisma__AuditRetentionPolicyClient extends Prisma.PrismaPromise { + readonly [Symbol.toStringTag]: "PrismaPromise" + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): $Utils.JsPromise + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): $Utils.JsPromise + } + + + + + /** + * Fields of the AuditRetentionPolicy model + */ + interface AuditRetentionPolicyFieldRefs { + readonly id: FieldRef<"AuditRetentionPolicy", 'Int'> + readonly resourceType: FieldRef<"AuditRetentionPolicy", 'String'> + readonly sensitivity: FieldRef<"AuditRetentionPolicy", 'AuditSensitivity'> + readonly retentionDays: FieldRef<"AuditRetentionPolicy", 'Int'> + readonly description: FieldRef<"AuditRetentionPolicy", 'String'> + readonly legalBasis: FieldRef<"AuditRetentionPolicy", 'String'> + readonly isActive: FieldRef<"AuditRetentionPolicy", 'Boolean'> + readonly createdAt: FieldRef<"AuditRetentionPolicy", 'DateTime'> + readonly updatedAt: FieldRef<"AuditRetentionPolicy", 'DateTime'> + } + + + // Custom InputTypes + /** + * AuditRetentionPolicy findUnique + */ + export type AuditRetentionPolicyFindUniqueArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * Filter, which AuditRetentionPolicy to fetch. + */ + where: AuditRetentionPolicyWhereUniqueInput + } + + /** + * AuditRetentionPolicy findUniqueOrThrow + */ + export type AuditRetentionPolicyFindUniqueOrThrowArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * Filter, which AuditRetentionPolicy to fetch. + */ + where: AuditRetentionPolicyWhereUniqueInput + } + + /** + * AuditRetentionPolicy findFirst + */ + export type AuditRetentionPolicyFindFirstArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * Filter, which AuditRetentionPolicy to fetch. + */ + where?: AuditRetentionPolicyWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditRetentionPolicies to fetch. + */ + orderBy?: AuditRetentionPolicyOrderByWithRelationInput | AuditRetentionPolicyOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for AuditRetentionPolicies. + */ + cursor?: AuditRetentionPolicyWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditRetentionPolicies from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditRetentionPolicies. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of AuditRetentionPolicies. + */ + distinct?: AuditRetentionPolicyScalarFieldEnum | AuditRetentionPolicyScalarFieldEnum[] + } + + /** + * AuditRetentionPolicy findFirstOrThrow + */ + export type AuditRetentionPolicyFindFirstOrThrowArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * Filter, which AuditRetentionPolicy to fetch. + */ + where?: AuditRetentionPolicyWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditRetentionPolicies to fetch. + */ + orderBy?: AuditRetentionPolicyOrderByWithRelationInput | AuditRetentionPolicyOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for searching for AuditRetentionPolicies. + */ + cursor?: AuditRetentionPolicyWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditRetentionPolicies from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditRetentionPolicies. + */ + skip?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} + * + * Filter by unique combinations of AuditRetentionPolicies. + */ + distinct?: AuditRetentionPolicyScalarFieldEnum | AuditRetentionPolicyScalarFieldEnum[] + } + + /** + * AuditRetentionPolicy findMany + */ + export type AuditRetentionPolicyFindManyArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * Filter, which AuditRetentionPolicies to fetch. + */ + where?: AuditRetentionPolicyWhereInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} + * + * Determine the order of AuditRetentionPolicies to fetch. + */ + orderBy?: AuditRetentionPolicyOrderByWithRelationInput | AuditRetentionPolicyOrderByWithRelationInput[] + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} + * + * Sets the position for listing AuditRetentionPolicies. + */ + cursor?: AuditRetentionPolicyWhereUniqueInput + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Take `±n` AuditRetentionPolicies from the position of the cursor. + */ + take?: number + /** + * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} + * + * Skip the first `n` AuditRetentionPolicies. + */ + skip?: number + distinct?: AuditRetentionPolicyScalarFieldEnum | AuditRetentionPolicyScalarFieldEnum[] + } + + /** + * AuditRetentionPolicy create + */ + export type AuditRetentionPolicyCreateArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * The data needed to create a AuditRetentionPolicy. + */ + data: XOR + } + + /** + * AuditRetentionPolicy createMany + */ + export type AuditRetentionPolicyCreateManyArgs = { + /** + * The data used to create many AuditRetentionPolicies. + */ + data: AuditRetentionPolicyCreateManyInput | AuditRetentionPolicyCreateManyInput[] + skipDuplicates?: boolean + } + + /** + * AuditRetentionPolicy update + */ + export type AuditRetentionPolicyUpdateArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * The data needed to update a AuditRetentionPolicy. + */ + data: XOR + /** + * Choose, which AuditRetentionPolicy to update. + */ + where: AuditRetentionPolicyWhereUniqueInput + } + + /** + * AuditRetentionPolicy updateMany + */ + export type AuditRetentionPolicyUpdateManyArgs = { + /** + * The data used to update AuditRetentionPolicies. + */ + data: XOR + /** + * Filter which AuditRetentionPolicies to update + */ + where?: AuditRetentionPolicyWhereInput + } + + /** + * AuditRetentionPolicy upsert + */ + export type AuditRetentionPolicyUpsertArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * The filter to search for the AuditRetentionPolicy to update in case it exists. + */ + where: AuditRetentionPolicyWhereUniqueInput + /** + * In case the AuditRetentionPolicy found by the `where` argument doesn't exist, create a new AuditRetentionPolicy with this data. + */ + create: XOR + /** + * In case the AuditRetentionPolicy was found with the provided `where` argument, update it with this data. + */ + update: XOR + } + + /** + * AuditRetentionPolicy delete + */ + export type AuditRetentionPolicyDeleteArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + /** + * Filter which AuditRetentionPolicy to delete. + */ + where: AuditRetentionPolicyWhereUniqueInput + } + + /** + * AuditRetentionPolicy deleteMany + */ + export type AuditRetentionPolicyDeleteManyArgs = { + /** + * Filter which AuditRetentionPolicies to delete + */ + where?: AuditRetentionPolicyWhereInput + } + + /** + * AuditRetentionPolicy without action + */ + export type AuditRetentionPolicyDefaultArgs = { + /** + * Select specific fields to fetch from the AuditRetentionPolicy + */ + select?: AuditRetentionPolicySelect | null + } + + /** * Enums */ @@ -38968,6 +45744,28 @@ export namespace Prisma { export type TransactionIsolationLevel = (typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel] + export const EmailLogScalarFieldEnum: { + id: 'id', + fromAddress: 'fromAddress', + toAddress: 'toAddress', + subject: 'subject', + context: 'context', + customerId: 'customerId', + triggeredBy: 'triggeredBy', + smtpServer: 'smtpServer', + smtpPort: 'smtpPort', + smtpEncryption: 'smtpEncryption', + smtpUser: 'smtpUser', + success: 'success', + messageId: 'messageId', + errorMessage: 'errorMessage', + smtpResponse: 'smtpResponse', + sentAt: 'sentAt' + }; + + export type EmailLogScalarFieldEnum = (typeof EmailLogScalarFieldEnum)[keyof typeof EmailLogScalarFieldEnum] + + export const AppSettingScalarFieldEnum: { id: 'id', key: 'key', @@ -38987,6 +45785,9 @@ export namespace Prisma { lastName: 'lastName', isActive: 'isActive', tokenInvalidatedAt: 'tokenInvalidatedAt', + whatsappNumber: 'whatsappNumber', + telegramUsername: 'telegramUsername', + signalNumber: 'signalNumber', customerId: 'customerId', createdAt: 'createdAt', updatedAt: 'updatedAt' @@ -39050,6 +45851,7 @@ export namespace Prisma { commercialRegisterPath: 'commercialRegisterPath', commercialRegisterNumber: 'commercialRegisterNumber', privacyPolicyPath: 'privacyPolicyPath', + consentHash: 'consentHash', notes: 'notes', portalEnabled: 'portalEnabled', portalEmail: 'portalEmail', @@ -39076,6 +45878,23 @@ export namespace Prisma { export type CustomerRepresentativeScalarFieldEnum = (typeof CustomerRepresentativeScalarFieldEnum)[keyof typeof CustomerRepresentativeScalarFieldEnum] + export const RepresentativeAuthorizationScalarFieldEnum: { + id: 'id', + customerId: 'customerId', + representativeId: 'representativeId', + isGranted: 'isGranted', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + notes: 'notes', + createdAt: 'createdAt', + updatedAt: 'updatedAt' + }; + + export type RepresentativeAuthorizationScalarFieldEnum = (typeof RepresentativeAuthorizationScalarFieldEnum)[keyof typeof RepresentativeAuthorizationScalarFieldEnum] + + export const AddressScalarFieldEnum: { id: 'id', customerId: 'customerId', @@ -39146,6 +45965,8 @@ export namespace Prisma { imapEncryption: 'imapEncryption', smtpEncryption: 'smtpEncryption', allowSelfSignedCerts: 'allowSelfSignedCerts', + systemEmailAddress: 'systemEmailAddress', + systemEmailPasswordEncrypted: 'systemEmailPasswordEncrypted', isActive: 'isActive', isDefault: 'isDefault', createdAt: 'createdAt', @@ -39226,6 +46047,10 @@ export namespace Prisma { value: 'value', unit: 'unit', notes: 'notes', + reportedBy: 'reportedBy', + status: 'status', + transferredAt: 'transferredAt', + transferredBy: 'transferredBy', createdAt: 'createdAt' }; @@ -39525,6 +46350,92 @@ export namespace Prisma { export type CarInsuranceDetailsScalarFieldEnum = (typeof CarInsuranceDetailsScalarFieldEnum)[keyof typeof CarInsuranceDetailsScalarFieldEnum] + export const AuditLogScalarFieldEnum: { + id: 'id', + userId: 'userId', + userEmail: 'userEmail', + userRole: 'userRole', + customerId: 'customerId', + isCustomerPortal: 'isCustomerPortal', + action: 'action', + sensitivity: 'sensitivity', + resourceType: 'resourceType', + resourceId: 'resourceId', + resourceLabel: 'resourceLabel', + endpoint: 'endpoint', + httpMethod: 'httpMethod', + ipAddress: 'ipAddress', + userAgent: 'userAgent', + changesBefore: 'changesBefore', + changesAfter: 'changesAfter', + changesEncrypted: 'changesEncrypted', + dataSubjectId: 'dataSubjectId', + legalBasis: 'legalBasis', + success: 'success', + errorMessage: 'errorMessage', + durationMs: 'durationMs', + createdAt: 'createdAt', + hash: 'hash', + previousHash: 'previousHash' + }; + + export type AuditLogScalarFieldEnum = (typeof AuditLogScalarFieldEnum)[keyof typeof AuditLogScalarFieldEnum] + + + export const CustomerConsentScalarFieldEnum: { + id: 'id', + customerId: 'customerId', + consentType: 'consentType', + status: 'status', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + version: 'version', + ipAddress: 'ipAddress', + createdBy: 'createdBy', + createdAt: 'createdAt', + updatedAt: 'updatedAt' + }; + + export type CustomerConsentScalarFieldEnum = (typeof CustomerConsentScalarFieldEnum)[keyof typeof CustomerConsentScalarFieldEnum] + + + export const DataDeletionRequestScalarFieldEnum: { + id: 'id', + customerId: 'customerId', + status: 'status', + requestedAt: 'requestedAt', + requestSource: 'requestSource', + requestedBy: 'requestedBy', + processedAt: 'processedAt', + processedBy: 'processedBy', + deletedData: 'deletedData', + retainedData: 'retainedData', + retentionReason: 'retentionReason', + proofDocument: 'proofDocument', + createdAt: 'createdAt', + updatedAt: 'updatedAt' + }; + + export type DataDeletionRequestScalarFieldEnum = (typeof DataDeletionRequestScalarFieldEnum)[keyof typeof DataDeletionRequestScalarFieldEnum] + + + export const AuditRetentionPolicyScalarFieldEnum: { + id: 'id', + resourceType: 'resourceType', + sensitivity: 'sensitivity', + retentionDays: 'retentionDays', + description: 'description', + legalBasis: 'legalBasis', + isActive: 'isActive', + createdAt: 'createdAt', + updatedAt: 'updatedAt' + }; + + export type AuditRetentionPolicyScalarFieldEnum = (typeof AuditRetentionPolicyScalarFieldEnum)[keyof typeof AuditRetentionPolicyScalarFieldEnum] + + export const SortOrder: { asc: 'asc', desc: 'desc' @@ -39561,16 +46472,16 @@ export namespace Prisma { /** - * Reference to a field of type 'DateTime' + * Reference to a field of type 'Boolean' */ - export type DateTimeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'DateTime'> + export type BooleanFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Boolean'> /** - * Reference to a field of type 'Boolean' + * Reference to a field of type 'DateTime' */ - export type BooleanFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Boolean'> + export type DateTimeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'DateTime'> @@ -39630,6 +46541,13 @@ export namespace Prisma { + /** + * Reference to a field of type 'MeterReadingStatus' + */ + export type EnumMeterReadingStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'MeterReadingStatus'> + + + /** * Reference to a field of type 'ContractType' */ @@ -39663,11 +46581,155 @@ export namespace Prisma { */ export type EnumInsuranceTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'InsuranceType'> + + + /** + * Reference to a field of type 'AuditAction' + */ + export type EnumAuditActionFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AuditAction'> + + + + /** + * Reference to a field of type 'AuditSensitivity' + */ + export type EnumAuditSensitivityFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AuditSensitivity'> + + + + /** + * Reference to a field of type 'ConsentType' + */ + export type EnumConsentTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ConsentType'> + + + + /** + * Reference to a field of type 'ConsentStatus' + */ + export type EnumConsentStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ConsentStatus'> + + + + /** + * Reference to a field of type 'DeletionRequestStatus' + */ + export type EnumDeletionRequestStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'DeletionRequestStatus'> + /** * Deep Input Types */ + export type EmailLogWhereInput = { + AND?: EmailLogWhereInput | EmailLogWhereInput[] + OR?: EmailLogWhereInput[] + NOT?: EmailLogWhereInput | EmailLogWhereInput[] + id?: IntFilter<"EmailLog"> | number + fromAddress?: StringFilter<"EmailLog"> | string + toAddress?: StringFilter<"EmailLog"> | string + subject?: StringFilter<"EmailLog"> | string + context?: StringFilter<"EmailLog"> | string + customerId?: IntNullableFilter<"EmailLog"> | number | null + triggeredBy?: StringNullableFilter<"EmailLog"> | string | null + smtpServer?: StringFilter<"EmailLog"> | string + smtpPort?: IntFilter<"EmailLog"> | number + smtpEncryption?: StringFilter<"EmailLog"> | string + smtpUser?: StringFilter<"EmailLog"> | string + success?: BoolFilter<"EmailLog"> | boolean + messageId?: StringNullableFilter<"EmailLog"> | string | null + errorMessage?: StringNullableFilter<"EmailLog"> | string | null + smtpResponse?: StringNullableFilter<"EmailLog"> | string | null + sentAt?: DateTimeFilter<"EmailLog"> | Date | string + } + + export type EmailLogOrderByWithRelationInput = { + id?: SortOrder + fromAddress?: SortOrder + toAddress?: SortOrder + subject?: SortOrder + context?: SortOrder + customerId?: SortOrderInput | SortOrder + triggeredBy?: SortOrderInput | SortOrder + smtpServer?: SortOrder + smtpPort?: SortOrder + smtpEncryption?: SortOrder + smtpUser?: SortOrder + success?: SortOrder + messageId?: SortOrderInput | SortOrder + errorMessage?: SortOrderInput | SortOrder + smtpResponse?: SortOrderInput | SortOrder + sentAt?: SortOrder + } + + export type EmailLogWhereUniqueInput = Prisma.AtLeast<{ + id?: number + AND?: EmailLogWhereInput | EmailLogWhereInput[] + OR?: EmailLogWhereInput[] + NOT?: EmailLogWhereInput | EmailLogWhereInput[] + fromAddress?: StringFilter<"EmailLog"> | string + toAddress?: StringFilter<"EmailLog"> | string + subject?: StringFilter<"EmailLog"> | string + context?: StringFilter<"EmailLog"> | string + customerId?: IntNullableFilter<"EmailLog"> | number | null + triggeredBy?: StringNullableFilter<"EmailLog"> | string | null + smtpServer?: StringFilter<"EmailLog"> | string + smtpPort?: IntFilter<"EmailLog"> | number + smtpEncryption?: StringFilter<"EmailLog"> | string + smtpUser?: StringFilter<"EmailLog"> | string + success?: BoolFilter<"EmailLog"> | boolean + messageId?: StringNullableFilter<"EmailLog"> | string | null + errorMessage?: StringNullableFilter<"EmailLog"> | string | null + smtpResponse?: StringNullableFilter<"EmailLog"> | string | null + sentAt?: DateTimeFilter<"EmailLog"> | Date | string + }, "id"> + + export type EmailLogOrderByWithAggregationInput = { + id?: SortOrder + fromAddress?: SortOrder + toAddress?: SortOrder + subject?: SortOrder + context?: SortOrder + customerId?: SortOrderInput | SortOrder + triggeredBy?: SortOrderInput | SortOrder + smtpServer?: SortOrder + smtpPort?: SortOrder + smtpEncryption?: SortOrder + smtpUser?: SortOrder + success?: SortOrder + messageId?: SortOrderInput | SortOrder + errorMessage?: SortOrderInput | SortOrder + smtpResponse?: SortOrderInput | SortOrder + sentAt?: SortOrder + _count?: EmailLogCountOrderByAggregateInput + _avg?: EmailLogAvgOrderByAggregateInput + _max?: EmailLogMaxOrderByAggregateInput + _min?: EmailLogMinOrderByAggregateInput + _sum?: EmailLogSumOrderByAggregateInput + } + + export type EmailLogScalarWhereWithAggregatesInput = { + AND?: EmailLogScalarWhereWithAggregatesInput | EmailLogScalarWhereWithAggregatesInput[] + OR?: EmailLogScalarWhereWithAggregatesInput[] + NOT?: EmailLogScalarWhereWithAggregatesInput | EmailLogScalarWhereWithAggregatesInput[] + id?: IntWithAggregatesFilter<"EmailLog"> | number + fromAddress?: StringWithAggregatesFilter<"EmailLog"> | string + toAddress?: StringWithAggregatesFilter<"EmailLog"> | string + subject?: StringWithAggregatesFilter<"EmailLog"> | string + context?: StringWithAggregatesFilter<"EmailLog"> | string + customerId?: IntNullableWithAggregatesFilter<"EmailLog"> | number | null + triggeredBy?: StringNullableWithAggregatesFilter<"EmailLog"> | string | null + smtpServer?: StringWithAggregatesFilter<"EmailLog"> | string + smtpPort?: IntWithAggregatesFilter<"EmailLog"> | number + smtpEncryption?: StringWithAggregatesFilter<"EmailLog"> | string + smtpUser?: StringWithAggregatesFilter<"EmailLog"> | string + success?: BoolWithAggregatesFilter<"EmailLog"> | boolean + messageId?: StringNullableWithAggregatesFilter<"EmailLog"> | string | null + errorMessage?: StringNullableWithAggregatesFilter<"EmailLog"> | string | null + smtpResponse?: StringNullableWithAggregatesFilter<"EmailLog"> | string | null + sentAt?: DateTimeWithAggregatesFilter<"EmailLog"> | Date | string + } + export type AppSettingWhereInput = { AND?: AppSettingWhereInput | AppSettingWhereInput[] OR?: AppSettingWhereInput[] @@ -39733,6 +46795,9 @@ export namespace Prisma { lastName?: StringFilter<"User"> | string isActive?: BoolFilter<"User"> | boolean tokenInvalidatedAt?: DateTimeNullableFilter<"User"> | Date | string | null + whatsappNumber?: StringNullableFilter<"User"> | string | null + telegramUsername?: StringNullableFilter<"User"> | string | null + signalNumber?: StringNullableFilter<"User"> | string | null customerId?: IntNullableFilter<"User"> | number | null createdAt?: DateTimeFilter<"User"> | Date | string updatedAt?: DateTimeFilter<"User"> | Date | string @@ -39748,6 +46813,9 @@ export namespace Prisma { lastName?: SortOrder isActive?: SortOrder tokenInvalidatedAt?: SortOrderInput | SortOrder + whatsappNumber?: SortOrderInput | SortOrder + telegramUsername?: SortOrderInput | SortOrder + signalNumber?: SortOrderInput | SortOrder customerId?: SortOrderInput | SortOrder createdAt?: SortOrder updatedAt?: SortOrder @@ -39767,6 +46835,9 @@ export namespace Prisma { lastName?: StringFilter<"User"> | string isActive?: BoolFilter<"User"> | boolean tokenInvalidatedAt?: DateTimeNullableFilter<"User"> | Date | string | null + whatsappNumber?: StringNullableFilter<"User"> | string | null + telegramUsername?: StringNullableFilter<"User"> | string | null + signalNumber?: StringNullableFilter<"User"> | string | null createdAt?: DateTimeFilter<"User"> | Date | string updatedAt?: DateTimeFilter<"User"> | Date | string customer?: XOR | null @@ -39781,6 +46852,9 @@ export namespace Prisma { lastName?: SortOrder isActive?: SortOrder tokenInvalidatedAt?: SortOrderInput | SortOrder + whatsappNumber?: SortOrderInput | SortOrder + telegramUsername?: SortOrderInput | SortOrder + signalNumber?: SortOrderInput | SortOrder customerId?: SortOrderInput | SortOrder createdAt?: SortOrder updatedAt?: SortOrder @@ -39802,6 +46876,9 @@ export namespace Prisma { lastName?: StringWithAggregatesFilter<"User"> | string isActive?: BoolWithAggregatesFilter<"User"> | boolean tokenInvalidatedAt?: DateTimeNullableWithAggregatesFilter<"User"> | Date | string | null + whatsappNumber?: StringNullableWithAggregatesFilter<"User"> | string | null + telegramUsername?: StringNullableWithAggregatesFilter<"User"> | string | null + signalNumber?: StringNullableWithAggregatesFilter<"User"> | string | null customerId?: IntNullableWithAggregatesFilter<"User"> | number | null createdAt?: DateTimeWithAggregatesFilter<"User"> | Date | string updatedAt?: DateTimeWithAggregatesFilter<"User"> | Date | string @@ -40029,6 +47106,7 @@ export namespace Prisma { commercialRegisterPath?: StringNullableFilter<"Customer"> | string | null commercialRegisterNumber?: StringNullableFilter<"Customer"> | string | null privacyPolicyPath?: StringNullableFilter<"Customer"> | string | null + consentHash?: StringNullableFilter<"Customer"> | string | null notes?: StringNullableFilter<"Customer"> | string | null portalEnabled?: BoolFilter<"Customer"> | boolean portalEmail?: StringNullableFilter<"Customer"> | string | null @@ -40046,6 +47124,9 @@ export namespace Prisma { contracts?: ContractListRelationFilter representingFor?: CustomerRepresentativeListRelationFilter representedBy?: CustomerRepresentativeListRelationFilter + authorizationsGiven?: RepresentativeAuthorizationListRelationFilter + authorizationsReceived?: RepresentativeAuthorizationListRelationFilter + consents?: CustomerConsentListRelationFilter } export type CustomerOrderByWithRelationInput = { @@ -40067,6 +47148,7 @@ export namespace Prisma { commercialRegisterPath?: SortOrderInput | SortOrder commercialRegisterNumber?: SortOrderInput | SortOrder privacyPolicyPath?: SortOrderInput | SortOrder + consentHash?: SortOrderInput | SortOrder notes?: SortOrderInput | SortOrder portalEnabled?: SortOrder portalEmail?: SortOrderInput | SortOrder @@ -40084,11 +47166,15 @@ export namespace Prisma { contracts?: ContractOrderByRelationAggregateInput representingFor?: CustomerRepresentativeOrderByRelationAggregateInput representedBy?: CustomerRepresentativeOrderByRelationAggregateInput + authorizationsGiven?: RepresentativeAuthorizationOrderByRelationAggregateInput + authorizationsReceived?: RepresentativeAuthorizationOrderByRelationAggregateInput + consents?: CustomerConsentOrderByRelationAggregateInput } export type CustomerWhereUniqueInput = Prisma.AtLeast<{ id?: number customerNumber?: string + consentHash?: string portalEmail?: string AND?: CustomerWhereInput | CustomerWhereInput[] OR?: CustomerWhereInput[] @@ -40125,7 +47211,10 @@ export namespace Prisma { contracts?: ContractListRelationFilter representingFor?: CustomerRepresentativeListRelationFilter representedBy?: CustomerRepresentativeListRelationFilter - }, "id" | "customerNumber" | "portalEmail"> + authorizationsGiven?: RepresentativeAuthorizationListRelationFilter + authorizationsReceived?: RepresentativeAuthorizationListRelationFilter + consents?: CustomerConsentListRelationFilter + }, "id" | "customerNumber" | "consentHash" | "portalEmail"> export type CustomerOrderByWithAggregationInput = { id?: SortOrder @@ -40146,6 +47235,7 @@ export namespace Prisma { commercialRegisterPath?: SortOrderInput | SortOrder commercialRegisterNumber?: SortOrderInput | SortOrder privacyPolicyPath?: SortOrderInput | SortOrder + consentHash?: SortOrderInput | SortOrder notes?: SortOrderInput | SortOrder portalEnabled?: SortOrder portalEmail?: SortOrderInput | SortOrder @@ -40183,6 +47273,7 @@ export namespace Prisma { commercialRegisterPath?: StringNullableWithAggregatesFilter<"Customer"> | string | null commercialRegisterNumber?: StringNullableWithAggregatesFilter<"Customer"> | string | null privacyPolicyPath?: StringNullableWithAggregatesFilter<"Customer"> | string | null + consentHash?: StringNullableWithAggregatesFilter<"Customer"> | string | null notes?: StringNullableWithAggregatesFilter<"Customer"> | string | null portalEnabled?: BoolWithAggregatesFilter<"Customer"> | boolean portalEmail?: StringNullableWithAggregatesFilter<"Customer"> | string | null @@ -40264,6 +47355,97 @@ export namespace Prisma { updatedAt?: DateTimeWithAggregatesFilter<"CustomerRepresentative"> | Date | string } + export type RepresentativeAuthorizationWhereInput = { + AND?: RepresentativeAuthorizationWhereInput | RepresentativeAuthorizationWhereInput[] + OR?: RepresentativeAuthorizationWhereInput[] + NOT?: RepresentativeAuthorizationWhereInput | RepresentativeAuthorizationWhereInput[] + id?: IntFilter<"RepresentativeAuthorization"> | number + customerId?: IntFilter<"RepresentativeAuthorization"> | number + representativeId?: IntFilter<"RepresentativeAuthorization"> | number + isGranted?: BoolFilter<"RepresentativeAuthorization"> | boolean + grantedAt?: DateTimeNullableFilter<"RepresentativeAuthorization"> | Date | string | null + withdrawnAt?: DateTimeNullableFilter<"RepresentativeAuthorization"> | Date | string | null + source?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + documentPath?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + notes?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + createdAt?: DateTimeFilter<"RepresentativeAuthorization"> | Date | string + updatedAt?: DateTimeFilter<"RepresentativeAuthorization"> | Date | string + customer?: XOR + representative?: XOR + } + + export type RepresentativeAuthorizationOrderByWithRelationInput = { + id?: SortOrder + customerId?: SortOrder + representativeId?: SortOrder + isGranted?: SortOrder + grantedAt?: SortOrderInput | SortOrder + withdrawnAt?: SortOrderInput | SortOrder + source?: SortOrderInput | SortOrder + documentPath?: SortOrderInput | SortOrder + notes?: SortOrderInput | SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + customer?: CustomerOrderByWithRelationInput + representative?: CustomerOrderByWithRelationInput + } + + export type RepresentativeAuthorizationWhereUniqueInput = Prisma.AtLeast<{ + id?: number + customerId_representativeId?: RepresentativeAuthorizationCustomerIdRepresentativeIdCompoundUniqueInput + AND?: RepresentativeAuthorizationWhereInput | RepresentativeAuthorizationWhereInput[] + OR?: RepresentativeAuthorizationWhereInput[] + NOT?: RepresentativeAuthorizationWhereInput | RepresentativeAuthorizationWhereInput[] + customerId?: IntFilter<"RepresentativeAuthorization"> | number + representativeId?: IntFilter<"RepresentativeAuthorization"> | number + isGranted?: BoolFilter<"RepresentativeAuthorization"> | boolean + grantedAt?: DateTimeNullableFilter<"RepresentativeAuthorization"> | Date | string | null + withdrawnAt?: DateTimeNullableFilter<"RepresentativeAuthorization"> | Date | string | null + source?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + documentPath?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + notes?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + createdAt?: DateTimeFilter<"RepresentativeAuthorization"> | Date | string + updatedAt?: DateTimeFilter<"RepresentativeAuthorization"> | Date | string + customer?: XOR + representative?: XOR + }, "id" | "customerId_representativeId"> + + export type RepresentativeAuthorizationOrderByWithAggregationInput = { + id?: SortOrder + customerId?: SortOrder + representativeId?: SortOrder + isGranted?: SortOrder + grantedAt?: SortOrderInput | SortOrder + withdrawnAt?: SortOrderInput | SortOrder + source?: SortOrderInput | SortOrder + documentPath?: SortOrderInput | SortOrder + notes?: SortOrderInput | SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + _count?: RepresentativeAuthorizationCountOrderByAggregateInput + _avg?: RepresentativeAuthorizationAvgOrderByAggregateInput + _max?: RepresentativeAuthorizationMaxOrderByAggregateInput + _min?: RepresentativeAuthorizationMinOrderByAggregateInput + _sum?: RepresentativeAuthorizationSumOrderByAggregateInput + } + + export type RepresentativeAuthorizationScalarWhereWithAggregatesInput = { + AND?: RepresentativeAuthorizationScalarWhereWithAggregatesInput | RepresentativeAuthorizationScalarWhereWithAggregatesInput[] + OR?: RepresentativeAuthorizationScalarWhereWithAggregatesInput[] + NOT?: RepresentativeAuthorizationScalarWhereWithAggregatesInput | RepresentativeAuthorizationScalarWhereWithAggregatesInput[] + id?: IntWithAggregatesFilter<"RepresentativeAuthorization"> | number + customerId?: IntWithAggregatesFilter<"RepresentativeAuthorization"> | number + representativeId?: IntWithAggregatesFilter<"RepresentativeAuthorization"> | number + isGranted?: BoolWithAggregatesFilter<"RepresentativeAuthorization"> | boolean + grantedAt?: DateTimeNullableWithAggregatesFilter<"RepresentativeAuthorization"> | Date | string | null + withdrawnAt?: DateTimeNullableWithAggregatesFilter<"RepresentativeAuthorization"> | Date | string | null + source?: StringNullableWithAggregatesFilter<"RepresentativeAuthorization"> | string | null + documentPath?: StringNullableWithAggregatesFilter<"RepresentativeAuthorization"> | string | null + notes?: StringNullableWithAggregatesFilter<"RepresentativeAuthorization"> | string | null + createdAt?: DateTimeWithAggregatesFilter<"RepresentativeAuthorization"> | Date | string + updatedAt?: DateTimeWithAggregatesFilter<"RepresentativeAuthorization"> | Date | string + } + export type AddressWhereInput = { AND?: AddressWhereInput | AddressWhereInput[] OR?: AddressWhereInput[] @@ -40567,6 +47749,8 @@ export namespace Prisma { imapEncryption?: EnumMailEncryptionFilter<"EmailProviderConfig"> | $Enums.MailEncryption smtpEncryption?: EnumMailEncryptionFilter<"EmailProviderConfig"> | $Enums.MailEncryption allowSelfSignedCerts?: BoolFilter<"EmailProviderConfig"> | boolean + systemEmailAddress?: StringNullableFilter<"EmailProviderConfig"> | string | null + systemEmailPasswordEncrypted?: StringNullableFilter<"EmailProviderConfig"> | string | null isActive?: BoolFilter<"EmailProviderConfig"> | boolean isDefault?: BoolFilter<"EmailProviderConfig"> | boolean createdAt?: DateTimeFilter<"EmailProviderConfig"> | Date | string @@ -40590,6 +47774,8 @@ export namespace Prisma { imapEncryption?: SortOrder smtpEncryption?: SortOrder allowSelfSignedCerts?: SortOrder + systemEmailAddress?: SortOrderInput | SortOrder + systemEmailPasswordEncrypted?: SortOrderInput | SortOrder isActive?: SortOrder isDefault?: SortOrder createdAt?: SortOrder @@ -40616,6 +47802,8 @@ export namespace Prisma { imapEncryption?: EnumMailEncryptionFilter<"EmailProviderConfig"> | $Enums.MailEncryption smtpEncryption?: EnumMailEncryptionFilter<"EmailProviderConfig"> | $Enums.MailEncryption allowSelfSignedCerts?: BoolFilter<"EmailProviderConfig"> | boolean + systemEmailAddress?: StringNullableFilter<"EmailProviderConfig"> | string | null + systemEmailPasswordEncrypted?: StringNullableFilter<"EmailProviderConfig"> | string | null isActive?: BoolFilter<"EmailProviderConfig"> | boolean isDefault?: BoolFilter<"EmailProviderConfig"> | boolean createdAt?: DateTimeFilter<"EmailProviderConfig"> | Date | string @@ -40639,6 +47827,8 @@ export namespace Prisma { imapEncryption?: SortOrder smtpEncryption?: SortOrder allowSelfSignedCerts?: SortOrder + systemEmailAddress?: SortOrderInput | SortOrder + systemEmailPasswordEncrypted?: SortOrderInput | SortOrder isActive?: SortOrder isDefault?: SortOrder createdAt?: SortOrder @@ -40670,6 +47860,8 @@ export namespace Prisma { imapEncryption?: EnumMailEncryptionWithAggregatesFilter<"EmailProviderConfig"> | $Enums.MailEncryption smtpEncryption?: EnumMailEncryptionWithAggregatesFilter<"EmailProviderConfig"> | $Enums.MailEncryption allowSelfSignedCerts?: BoolWithAggregatesFilter<"EmailProviderConfig"> | boolean + systemEmailAddress?: StringNullableWithAggregatesFilter<"EmailProviderConfig"> | string | null + systemEmailPasswordEncrypted?: StringNullableWithAggregatesFilter<"EmailProviderConfig"> | string | null isActive?: BoolWithAggregatesFilter<"EmailProviderConfig"> | boolean isDefault?: BoolWithAggregatesFilter<"EmailProviderConfig"> | boolean createdAt?: DateTimeWithAggregatesFilter<"EmailProviderConfig"> | Date | string @@ -41028,6 +48220,10 @@ export namespace Prisma { value?: FloatFilter<"MeterReading"> | number unit?: StringFilter<"MeterReading"> | string notes?: StringNullableFilter<"MeterReading"> | string | null + reportedBy?: StringNullableFilter<"MeterReading"> | string | null + status?: EnumMeterReadingStatusFilter<"MeterReading"> | $Enums.MeterReadingStatus + transferredAt?: DateTimeNullableFilter<"MeterReading"> | Date | string | null + transferredBy?: StringNullableFilter<"MeterReading"> | string | null createdAt?: DateTimeFilter<"MeterReading"> | Date | string meter?: XOR } @@ -41039,6 +48235,10 @@ export namespace Prisma { value?: SortOrder unit?: SortOrder notes?: SortOrderInput | SortOrder + reportedBy?: SortOrderInput | SortOrder + status?: SortOrder + transferredAt?: SortOrderInput | SortOrder + transferredBy?: SortOrderInput | SortOrder createdAt?: SortOrder meter?: MeterOrderByWithRelationInput } @@ -41053,6 +48253,10 @@ export namespace Prisma { value?: FloatFilter<"MeterReading"> | number unit?: StringFilter<"MeterReading"> | string notes?: StringNullableFilter<"MeterReading"> | string | null + reportedBy?: StringNullableFilter<"MeterReading"> | string | null + status?: EnumMeterReadingStatusFilter<"MeterReading"> | $Enums.MeterReadingStatus + transferredAt?: DateTimeNullableFilter<"MeterReading"> | Date | string | null + transferredBy?: StringNullableFilter<"MeterReading"> | string | null createdAt?: DateTimeFilter<"MeterReading"> | Date | string meter?: XOR }, "id"> @@ -41064,6 +48268,10 @@ export namespace Prisma { value?: SortOrder unit?: SortOrder notes?: SortOrderInput | SortOrder + reportedBy?: SortOrderInput | SortOrder + status?: SortOrder + transferredAt?: SortOrderInput | SortOrder + transferredBy?: SortOrderInput | SortOrder createdAt?: SortOrder _count?: MeterReadingCountOrderByAggregateInput _avg?: MeterReadingAvgOrderByAggregateInput @@ -41082,6 +48290,10 @@ export namespace Prisma { value?: FloatWithAggregatesFilter<"MeterReading"> | number unit?: StringWithAggregatesFilter<"MeterReading"> | string notes?: StringNullableWithAggregatesFilter<"MeterReading"> | string | null + reportedBy?: StringNullableWithAggregatesFilter<"MeterReading"> | string | null + status?: EnumMeterReadingStatusWithAggregatesFilter<"MeterReading"> | $Enums.MeterReadingStatus + transferredAt?: DateTimeNullableWithAggregatesFilter<"MeterReading"> | Date | string | null + transferredBy?: StringNullableWithAggregatesFilter<"MeterReading"> | string | null createdAt?: DateTimeWithAggregatesFilter<"MeterReading"> | Date | string } @@ -42677,6 +49889,567 @@ export namespace Prisma { previousInsurer?: StringNullableWithAggregatesFilter<"CarInsuranceDetails"> | string | null } + export type AuditLogWhereInput = { + AND?: AuditLogWhereInput | AuditLogWhereInput[] + OR?: AuditLogWhereInput[] + NOT?: AuditLogWhereInput | AuditLogWhereInput[] + id?: IntFilter<"AuditLog"> | number + userId?: IntNullableFilter<"AuditLog"> | number | null + userEmail?: StringFilter<"AuditLog"> | string + userRole?: StringNullableFilter<"AuditLog"> | string | null + customerId?: IntNullableFilter<"AuditLog"> | number | null + isCustomerPortal?: BoolFilter<"AuditLog"> | boolean + action?: EnumAuditActionFilter<"AuditLog"> | $Enums.AuditAction + sensitivity?: EnumAuditSensitivityFilter<"AuditLog"> | $Enums.AuditSensitivity + resourceType?: StringFilter<"AuditLog"> | string + resourceId?: StringNullableFilter<"AuditLog"> | string | null + resourceLabel?: StringNullableFilter<"AuditLog"> | string | null + endpoint?: StringFilter<"AuditLog"> | string + httpMethod?: StringFilter<"AuditLog"> | string + ipAddress?: StringFilter<"AuditLog"> | string + userAgent?: StringNullableFilter<"AuditLog"> | string | null + changesBefore?: StringNullableFilter<"AuditLog"> | string | null + changesAfter?: StringNullableFilter<"AuditLog"> | string | null + changesEncrypted?: BoolFilter<"AuditLog"> | boolean + dataSubjectId?: IntNullableFilter<"AuditLog"> | number | null + legalBasis?: StringNullableFilter<"AuditLog"> | string | null + success?: BoolFilter<"AuditLog"> | boolean + errorMessage?: StringNullableFilter<"AuditLog"> | string | null + durationMs?: IntNullableFilter<"AuditLog"> | number | null + createdAt?: DateTimeFilter<"AuditLog"> | Date | string + hash?: StringNullableFilter<"AuditLog"> | string | null + previousHash?: StringNullableFilter<"AuditLog"> | string | null + } + + export type AuditLogOrderByWithRelationInput = { + id?: SortOrder + userId?: SortOrderInput | SortOrder + userEmail?: SortOrder + userRole?: SortOrderInput | SortOrder + customerId?: SortOrderInput | SortOrder + isCustomerPortal?: SortOrder + action?: SortOrder + sensitivity?: SortOrder + resourceType?: SortOrder + resourceId?: SortOrderInput | SortOrder + resourceLabel?: SortOrderInput | SortOrder + endpoint?: SortOrder + httpMethod?: SortOrder + ipAddress?: SortOrder + userAgent?: SortOrderInput | SortOrder + changesBefore?: SortOrderInput | SortOrder + changesAfter?: SortOrderInput | SortOrder + changesEncrypted?: SortOrder + dataSubjectId?: SortOrderInput | SortOrder + legalBasis?: SortOrderInput | SortOrder + success?: SortOrder + errorMessage?: SortOrderInput | SortOrder + durationMs?: SortOrderInput | SortOrder + createdAt?: SortOrder + hash?: SortOrderInput | SortOrder + previousHash?: SortOrderInput | SortOrder + } + + export type AuditLogWhereUniqueInput = Prisma.AtLeast<{ + id?: number + AND?: AuditLogWhereInput | AuditLogWhereInput[] + OR?: AuditLogWhereInput[] + NOT?: AuditLogWhereInput | AuditLogWhereInput[] + userId?: IntNullableFilter<"AuditLog"> | number | null + userEmail?: StringFilter<"AuditLog"> | string + userRole?: StringNullableFilter<"AuditLog"> | string | null + customerId?: IntNullableFilter<"AuditLog"> | number | null + isCustomerPortal?: BoolFilter<"AuditLog"> | boolean + action?: EnumAuditActionFilter<"AuditLog"> | $Enums.AuditAction + sensitivity?: EnumAuditSensitivityFilter<"AuditLog"> | $Enums.AuditSensitivity + resourceType?: StringFilter<"AuditLog"> | string + resourceId?: StringNullableFilter<"AuditLog"> | string | null + resourceLabel?: StringNullableFilter<"AuditLog"> | string | null + endpoint?: StringFilter<"AuditLog"> | string + httpMethod?: StringFilter<"AuditLog"> | string + ipAddress?: StringFilter<"AuditLog"> | string + userAgent?: StringNullableFilter<"AuditLog"> | string | null + changesBefore?: StringNullableFilter<"AuditLog"> | string | null + changesAfter?: StringNullableFilter<"AuditLog"> | string | null + changesEncrypted?: BoolFilter<"AuditLog"> | boolean + dataSubjectId?: IntNullableFilter<"AuditLog"> | number | null + legalBasis?: StringNullableFilter<"AuditLog"> | string | null + success?: BoolFilter<"AuditLog"> | boolean + errorMessage?: StringNullableFilter<"AuditLog"> | string | null + durationMs?: IntNullableFilter<"AuditLog"> | number | null + createdAt?: DateTimeFilter<"AuditLog"> | Date | string + hash?: StringNullableFilter<"AuditLog"> | string | null + previousHash?: StringNullableFilter<"AuditLog"> | string | null + }, "id"> + + export type AuditLogOrderByWithAggregationInput = { + id?: SortOrder + userId?: SortOrderInput | SortOrder + userEmail?: SortOrder + userRole?: SortOrderInput | SortOrder + customerId?: SortOrderInput | SortOrder + isCustomerPortal?: SortOrder + action?: SortOrder + sensitivity?: SortOrder + resourceType?: SortOrder + resourceId?: SortOrderInput | SortOrder + resourceLabel?: SortOrderInput | SortOrder + endpoint?: SortOrder + httpMethod?: SortOrder + ipAddress?: SortOrder + userAgent?: SortOrderInput | SortOrder + changesBefore?: SortOrderInput | SortOrder + changesAfter?: SortOrderInput | SortOrder + changesEncrypted?: SortOrder + dataSubjectId?: SortOrderInput | SortOrder + legalBasis?: SortOrderInput | SortOrder + success?: SortOrder + errorMessage?: SortOrderInput | SortOrder + durationMs?: SortOrderInput | SortOrder + createdAt?: SortOrder + hash?: SortOrderInput | SortOrder + previousHash?: SortOrderInput | SortOrder + _count?: AuditLogCountOrderByAggregateInput + _avg?: AuditLogAvgOrderByAggregateInput + _max?: AuditLogMaxOrderByAggregateInput + _min?: AuditLogMinOrderByAggregateInput + _sum?: AuditLogSumOrderByAggregateInput + } + + export type AuditLogScalarWhereWithAggregatesInput = { + AND?: AuditLogScalarWhereWithAggregatesInput | AuditLogScalarWhereWithAggregatesInput[] + OR?: AuditLogScalarWhereWithAggregatesInput[] + NOT?: AuditLogScalarWhereWithAggregatesInput | AuditLogScalarWhereWithAggregatesInput[] + id?: IntWithAggregatesFilter<"AuditLog"> | number + userId?: IntNullableWithAggregatesFilter<"AuditLog"> | number | null + userEmail?: StringWithAggregatesFilter<"AuditLog"> | string + userRole?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + customerId?: IntNullableWithAggregatesFilter<"AuditLog"> | number | null + isCustomerPortal?: BoolWithAggregatesFilter<"AuditLog"> | boolean + action?: EnumAuditActionWithAggregatesFilter<"AuditLog"> | $Enums.AuditAction + sensitivity?: EnumAuditSensitivityWithAggregatesFilter<"AuditLog"> | $Enums.AuditSensitivity + resourceType?: StringWithAggregatesFilter<"AuditLog"> | string + resourceId?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + resourceLabel?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + endpoint?: StringWithAggregatesFilter<"AuditLog"> | string + httpMethod?: StringWithAggregatesFilter<"AuditLog"> | string + ipAddress?: StringWithAggregatesFilter<"AuditLog"> | string + userAgent?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + changesBefore?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + changesAfter?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + changesEncrypted?: BoolWithAggregatesFilter<"AuditLog"> | boolean + dataSubjectId?: IntNullableWithAggregatesFilter<"AuditLog"> | number | null + legalBasis?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + success?: BoolWithAggregatesFilter<"AuditLog"> | boolean + errorMessage?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + durationMs?: IntNullableWithAggregatesFilter<"AuditLog"> | number | null + createdAt?: DateTimeWithAggregatesFilter<"AuditLog"> | Date | string + hash?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + previousHash?: StringNullableWithAggregatesFilter<"AuditLog"> | string | null + } + + export type CustomerConsentWhereInput = { + AND?: CustomerConsentWhereInput | CustomerConsentWhereInput[] + OR?: CustomerConsentWhereInput[] + NOT?: CustomerConsentWhereInput | CustomerConsentWhereInput[] + id?: IntFilter<"CustomerConsent"> | number + customerId?: IntFilter<"CustomerConsent"> | number + consentType?: EnumConsentTypeFilter<"CustomerConsent"> | $Enums.ConsentType + status?: EnumConsentStatusFilter<"CustomerConsent"> | $Enums.ConsentStatus + grantedAt?: DateTimeNullableFilter<"CustomerConsent"> | Date | string | null + withdrawnAt?: DateTimeNullableFilter<"CustomerConsent"> | Date | string | null + source?: StringNullableFilter<"CustomerConsent"> | string | null + documentPath?: StringNullableFilter<"CustomerConsent"> | string | null + version?: StringNullableFilter<"CustomerConsent"> | string | null + ipAddress?: StringNullableFilter<"CustomerConsent"> | string | null + createdBy?: StringFilter<"CustomerConsent"> | string + createdAt?: DateTimeFilter<"CustomerConsent"> | Date | string + updatedAt?: DateTimeFilter<"CustomerConsent"> | Date | string + customer?: XOR + } + + export type CustomerConsentOrderByWithRelationInput = { + id?: SortOrder + customerId?: SortOrder + consentType?: SortOrder + status?: SortOrder + grantedAt?: SortOrderInput | SortOrder + withdrawnAt?: SortOrderInput | SortOrder + source?: SortOrderInput | SortOrder + documentPath?: SortOrderInput | SortOrder + version?: SortOrderInput | SortOrder + ipAddress?: SortOrderInput | SortOrder + createdBy?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + customer?: CustomerOrderByWithRelationInput + } + + export type CustomerConsentWhereUniqueInput = Prisma.AtLeast<{ + id?: number + customerId_consentType?: CustomerConsentCustomerIdConsentTypeCompoundUniqueInput + AND?: CustomerConsentWhereInput | CustomerConsentWhereInput[] + OR?: CustomerConsentWhereInput[] + NOT?: CustomerConsentWhereInput | CustomerConsentWhereInput[] + customerId?: IntFilter<"CustomerConsent"> | number + consentType?: EnumConsentTypeFilter<"CustomerConsent"> | $Enums.ConsentType + status?: EnumConsentStatusFilter<"CustomerConsent"> | $Enums.ConsentStatus + grantedAt?: DateTimeNullableFilter<"CustomerConsent"> | Date | string | null + withdrawnAt?: DateTimeNullableFilter<"CustomerConsent"> | Date | string | null + source?: StringNullableFilter<"CustomerConsent"> | string | null + documentPath?: StringNullableFilter<"CustomerConsent"> | string | null + version?: StringNullableFilter<"CustomerConsent"> | string | null + ipAddress?: StringNullableFilter<"CustomerConsent"> | string | null + createdBy?: StringFilter<"CustomerConsent"> | string + createdAt?: DateTimeFilter<"CustomerConsent"> | Date | string + updatedAt?: DateTimeFilter<"CustomerConsent"> | Date | string + customer?: XOR + }, "id" | "customerId_consentType"> + + export type CustomerConsentOrderByWithAggregationInput = { + id?: SortOrder + customerId?: SortOrder + consentType?: SortOrder + status?: SortOrder + grantedAt?: SortOrderInput | SortOrder + withdrawnAt?: SortOrderInput | SortOrder + source?: SortOrderInput | SortOrder + documentPath?: SortOrderInput | SortOrder + version?: SortOrderInput | SortOrder + ipAddress?: SortOrderInput | SortOrder + createdBy?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + _count?: CustomerConsentCountOrderByAggregateInput + _avg?: CustomerConsentAvgOrderByAggregateInput + _max?: CustomerConsentMaxOrderByAggregateInput + _min?: CustomerConsentMinOrderByAggregateInput + _sum?: CustomerConsentSumOrderByAggregateInput + } + + export type CustomerConsentScalarWhereWithAggregatesInput = { + AND?: CustomerConsentScalarWhereWithAggregatesInput | CustomerConsentScalarWhereWithAggregatesInput[] + OR?: CustomerConsentScalarWhereWithAggregatesInput[] + NOT?: CustomerConsentScalarWhereWithAggregatesInput | CustomerConsentScalarWhereWithAggregatesInput[] + id?: IntWithAggregatesFilter<"CustomerConsent"> | number + customerId?: IntWithAggregatesFilter<"CustomerConsent"> | number + consentType?: EnumConsentTypeWithAggregatesFilter<"CustomerConsent"> | $Enums.ConsentType + status?: EnumConsentStatusWithAggregatesFilter<"CustomerConsent"> | $Enums.ConsentStatus + grantedAt?: DateTimeNullableWithAggregatesFilter<"CustomerConsent"> | Date | string | null + withdrawnAt?: DateTimeNullableWithAggregatesFilter<"CustomerConsent"> | Date | string | null + source?: StringNullableWithAggregatesFilter<"CustomerConsent"> | string | null + documentPath?: StringNullableWithAggregatesFilter<"CustomerConsent"> | string | null + version?: StringNullableWithAggregatesFilter<"CustomerConsent"> | string | null + ipAddress?: StringNullableWithAggregatesFilter<"CustomerConsent"> | string | null + createdBy?: StringWithAggregatesFilter<"CustomerConsent"> | string + createdAt?: DateTimeWithAggregatesFilter<"CustomerConsent"> | Date | string + updatedAt?: DateTimeWithAggregatesFilter<"CustomerConsent"> | Date | string + } + + export type DataDeletionRequestWhereInput = { + AND?: DataDeletionRequestWhereInput | DataDeletionRequestWhereInput[] + OR?: DataDeletionRequestWhereInput[] + NOT?: DataDeletionRequestWhereInput | DataDeletionRequestWhereInput[] + id?: IntFilter<"DataDeletionRequest"> | number + customerId?: IntFilter<"DataDeletionRequest"> | number + status?: EnumDeletionRequestStatusFilter<"DataDeletionRequest"> | $Enums.DeletionRequestStatus + requestedAt?: DateTimeFilter<"DataDeletionRequest"> | Date | string + requestSource?: StringFilter<"DataDeletionRequest"> | string + requestedBy?: StringFilter<"DataDeletionRequest"> | string + processedAt?: DateTimeNullableFilter<"DataDeletionRequest"> | Date | string | null + processedBy?: StringNullableFilter<"DataDeletionRequest"> | string | null + deletedData?: StringNullableFilter<"DataDeletionRequest"> | string | null + retainedData?: StringNullableFilter<"DataDeletionRequest"> | string | null + retentionReason?: StringNullableFilter<"DataDeletionRequest"> | string | null + proofDocument?: StringNullableFilter<"DataDeletionRequest"> | string | null + createdAt?: DateTimeFilter<"DataDeletionRequest"> | Date | string + updatedAt?: DateTimeFilter<"DataDeletionRequest"> | Date | string + } + + export type DataDeletionRequestOrderByWithRelationInput = { + id?: SortOrder + customerId?: SortOrder + status?: SortOrder + requestedAt?: SortOrder + requestSource?: SortOrder + requestedBy?: SortOrder + processedAt?: SortOrderInput | SortOrder + processedBy?: SortOrderInput | SortOrder + deletedData?: SortOrderInput | SortOrder + retainedData?: SortOrderInput | SortOrder + retentionReason?: SortOrderInput | SortOrder + proofDocument?: SortOrderInput | SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type DataDeletionRequestWhereUniqueInput = Prisma.AtLeast<{ + id?: number + AND?: DataDeletionRequestWhereInput | DataDeletionRequestWhereInput[] + OR?: DataDeletionRequestWhereInput[] + NOT?: DataDeletionRequestWhereInput | DataDeletionRequestWhereInput[] + customerId?: IntFilter<"DataDeletionRequest"> | number + status?: EnumDeletionRequestStatusFilter<"DataDeletionRequest"> | $Enums.DeletionRequestStatus + requestedAt?: DateTimeFilter<"DataDeletionRequest"> | Date | string + requestSource?: StringFilter<"DataDeletionRequest"> | string + requestedBy?: StringFilter<"DataDeletionRequest"> | string + processedAt?: DateTimeNullableFilter<"DataDeletionRequest"> | Date | string | null + processedBy?: StringNullableFilter<"DataDeletionRequest"> | string | null + deletedData?: StringNullableFilter<"DataDeletionRequest"> | string | null + retainedData?: StringNullableFilter<"DataDeletionRequest"> | string | null + retentionReason?: StringNullableFilter<"DataDeletionRequest"> | string | null + proofDocument?: StringNullableFilter<"DataDeletionRequest"> | string | null + createdAt?: DateTimeFilter<"DataDeletionRequest"> | Date | string + updatedAt?: DateTimeFilter<"DataDeletionRequest"> | Date | string + }, "id"> + + export type DataDeletionRequestOrderByWithAggregationInput = { + id?: SortOrder + customerId?: SortOrder + status?: SortOrder + requestedAt?: SortOrder + requestSource?: SortOrder + requestedBy?: SortOrder + processedAt?: SortOrderInput | SortOrder + processedBy?: SortOrderInput | SortOrder + deletedData?: SortOrderInput | SortOrder + retainedData?: SortOrderInput | SortOrder + retentionReason?: SortOrderInput | SortOrder + proofDocument?: SortOrderInput | SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + _count?: DataDeletionRequestCountOrderByAggregateInput + _avg?: DataDeletionRequestAvgOrderByAggregateInput + _max?: DataDeletionRequestMaxOrderByAggregateInput + _min?: DataDeletionRequestMinOrderByAggregateInput + _sum?: DataDeletionRequestSumOrderByAggregateInput + } + + export type DataDeletionRequestScalarWhereWithAggregatesInput = { + AND?: DataDeletionRequestScalarWhereWithAggregatesInput | DataDeletionRequestScalarWhereWithAggregatesInput[] + OR?: DataDeletionRequestScalarWhereWithAggregatesInput[] + NOT?: DataDeletionRequestScalarWhereWithAggregatesInput | DataDeletionRequestScalarWhereWithAggregatesInput[] + id?: IntWithAggregatesFilter<"DataDeletionRequest"> | number + customerId?: IntWithAggregatesFilter<"DataDeletionRequest"> | number + status?: EnumDeletionRequestStatusWithAggregatesFilter<"DataDeletionRequest"> | $Enums.DeletionRequestStatus + requestedAt?: DateTimeWithAggregatesFilter<"DataDeletionRequest"> | Date | string + requestSource?: StringWithAggregatesFilter<"DataDeletionRequest"> | string + requestedBy?: StringWithAggregatesFilter<"DataDeletionRequest"> | string + processedAt?: DateTimeNullableWithAggregatesFilter<"DataDeletionRequest"> | Date | string | null + processedBy?: StringNullableWithAggregatesFilter<"DataDeletionRequest"> | string | null + deletedData?: StringNullableWithAggregatesFilter<"DataDeletionRequest"> | string | null + retainedData?: StringNullableWithAggregatesFilter<"DataDeletionRequest"> | string | null + retentionReason?: StringNullableWithAggregatesFilter<"DataDeletionRequest"> | string | null + proofDocument?: StringNullableWithAggregatesFilter<"DataDeletionRequest"> | string | null + createdAt?: DateTimeWithAggregatesFilter<"DataDeletionRequest"> | Date | string + updatedAt?: DateTimeWithAggregatesFilter<"DataDeletionRequest"> | Date | string + } + + export type AuditRetentionPolicyWhereInput = { + AND?: AuditRetentionPolicyWhereInput | AuditRetentionPolicyWhereInput[] + OR?: AuditRetentionPolicyWhereInput[] + NOT?: AuditRetentionPolicyWhereInput | AuditRetentionPolicyWhereInput[] + id?: IntFilter<"AuditRetentionPolicy"> | number + resourceType?: StringFilter<"AuditRetentionPolicy"> | string + sensitivity?: EnumAuditSensitivityNullableFilter<"AuditRetentionPolicy"> | $Enums.AuditSensitivity | null + retentionDays?: IntFilter<"AuditRetentionPolicy"> | number + description?: StringNullableFilter<"AuditRetentionPolicy"> | string | null + legalBasis?: StringNullableFilter<"AuditRetentionPolicy"> | string | null + isActive?: BoolFilter<"AuditRetentionPolicy"> | boolean + createdAt?: DateTimeFilter<"AuditRetentionPolicy"> | Date | string + updatedAt?: DateTimeFilter<"AuditRetentionPolicy"> | Date | string + } + + export type AuditRetentionPolicyOrderByWithRelationInput = { + id?: SortOrder + resourceType?: SortOrder + sensitivity?: SortOrderInput | SortOrder + retentionDays?: SortOrder + description?: SortOrderInput | SortOrder + legalBasis?: SortOrderInput | SortOrder + isActive?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type AuditRetentionPolicyWhereUniqueInput = Prisma.AtLeast<{ + id?: number + resourceType_sensitivity?: AuditRetentionPolicyResourceTypeSensitivityCompoundUniqueInput + AND?: AuditRetentionPolicyWhereInput | AuditRetentionPolicyWhereInput[] + OR?: AuditRetentionPolicyWhereInput[] + NOT?: AuditRetentionPolicyWhereInput | AuditRetentionPolicyWhereInput[] + resourceType?: StringFilter<"AuditRetentionPolicy"> | string + sensitivity?: EnumAuditSensitivityNullableFilter<"AuditRetentionPolicy"> | $Enums.AuditSensitivity | null + retentionDays?: IntFilter<"AuditRetentionPolicy"> | number + description?: StringNullableFilter<"AuditRetentionPolicy"> | string | null + legalBasis?: StringNullableFilter<"AuditRetentionPolicy"> | string | null + isActive?: BoolFilter<"AuditRetentionPolicy"> | boolean + createdAt?: DateTimeFilter<"AuditRetentionPolicy"> | Date | string + updatedAt?: DateTimeFilter<"AuditRetentionPolicy"> | Date | string + }, "id" | "resourceType_sensitivity"> + + export type AuditRetentionPolicyOrderByWithAggregationInput = { + id?: SortOrder + resourceType?: SortOrder + sensitivity?: SortOrderInput | SortOrder + retentionDays?: SortOrder + description?: SortOrderInput | SortOrder + legalBasis?: SortOrderInput | SortOrder + isActive?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + _count?: AuditRetentionPolicyCountOrderByAggregateInput + _avg?: AuditRetentionPolicyAvgOrderByAggregateInput + _max?: AuditRetentionPolicyMaxOrderByAggregateInput + _min?: AuditRetentionPolicyMinOrderByAggregateInput + _sum?: AuditRetentionPolicySumOrderByAggregateInput + } + + export type AuditRetentionPolicyScalarWhereWithAggregatesInput = { + AND?: AuditRetentionPolicyScalarWhereWithAggregatesInput | AuditRetentionPolicyScalarWhereWithAggregatesInput[] + OR?: AuditRetentionPolicyScalarWhereWithAggregatesInput[] + NOT?: AuditRetentionPolicyScalarWhereWithAggregatesInput | AuditRetentionPolicyScalarWhereWithAggregatesInput[] + id?: IntWithAggregatesFilter<"AuditRetentionPolicy"> | number + resourceType?: StringWithAggregatesFilter<"AuditRetentionPolicy"> | string + sensitivity?: EnumAuditSensitivityNullableWithAggregatesFilter<"AuditRetentionPolicy"> | $Enums.AuditSensitivity | null + retentionDays?: IntWithAggregatesFilter<"AuditRetentionPolicy"> | number + description?: StringNullableWithAggregatesFilter<"AuditRetentionPolicy"> | string | null + legalBasis?: StringNullableWithAggregatesFilter<"AuditRetentionPolicy"> | string | null + isActive?: BoolWithAggregatesFilter<"AuditRetentionPolicy"> | boolean + createdAt?: DateTimeWithAggregatesFilter<"AuditRetentionPolicy"> | Date | string + updatedAt?: DateTimeWithAggregatesFilter<"AuditRetentionPolicy"> | Date | string + } + + export type EmailLogCreateInput = { + fromAddress: string + toAddress: string + subject: string + context: string + customerId?: number | null + triggeredBy?: string | null + smtpServer: string + smtpPort: number + smtpEncryption: string + smtpUser: string + success: boolean + messageId?: string | null + errorMessage?: string | null + smtpResponse?: string | null + sentAt?: Date | string + } + + export type EmailLogUncheckedCreateInput = { + id?: number + fromAddress: string + toAddress: string + subject: string + context: string + customerId?: number | null + triggeredBy?: string | null + smtpServer: string + smtpPort: number + smtpEncryption: string + smtpUser: string + success: boolean + messageId?: string | null + errorMessage?: string | null + smtpResponse?: string | null + sentAt?: Date | string + } + + export type EmailLogUpdateInput = { + fromAddress?: StringFieldUpdateOperationsInput | string + toAddress?: StringFieldUpdateOperationsInput | string + subject?: StringFieldUpdateOperationsInput | string + context?: StringFieldUpdateOperationsInput | string + customerId?: NullableIntFieldUpdateOperationsInput | number | null + triggeredBy?: NullableStringFieldUpdateOperationsInput | string | null + smtpServer?: StringFieldUpdateOperationsInput | string + smtpPort?: IntFieldUpdateOperationsInput | number + smtpEncryption?: StringFieldUpdateOperationsInput | string + smtpUser?: StringFieldUpdateOperationsInput | string + success?: BoolFieldUpdateOperationsInput | boolean + messageId?: NullableStringFieldUpdateOperationsInput | string | null + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + smtpResponse?: NullableStringFieldUpdateOperationsInput | string | null + sentAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type EmailLogUncheckedUpdateInput = { + id?: IntFieldUpdateOperationsInput | number + fromAddress?: StringFieldUpdateOperationsInput | string + toAddress?: StringFieldUpdateOperationsInput | string + subject?: StringFieldUpdateOperationsInput | string + context?: StringFieldUpdateOperationsInput | string + customerId?: NullableIntFieldUpdateOperationsInput | number | null + triggeredBy?: NullableStringFieldUpdateOperationsInput | string | null + smtpServer?: StringFieldUpdateOperationsInput | string + smtpPort?: IntFieldUpdateOperationsInput | number + smtpEncryption?: StringFieldUpdateOperationsInput | string + smtpUser?: StringFieldUpdateOperationsInput | string + success?: BoolFieldUpdateOperationsInput | boolean + messageId?: NullableStringFieldUpdateOperationsInput | string | null + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + smtpResponse?: NullableStringFieldUpdateOperationsInput | string | null + sentAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type EmailLogCreateManyInput = { + id?: number + fromAddress: string + toAddress: string + subject: string + context: string + customerId?: number | null + triggeredBy?: string | null + smtpServer: string + smtpPort: number + smtpEncryption: string + smtpUser: string + success: boolean + messageId?: string | null + errorMessage?: string | null + smtpResponse?: string | null + sentAt?: Date | string + } + + export type EmailLogUpdateManyMutationInput = { + fromAddress?: StringFieldUpdateOperationsInput | string + toAddress?: StringFieldUpdateOperationsInput | string + subject?: StringFieldUpdateOperationsInput | string + context?: StringFieldUpdateOperationsInput | string + customerId?: NullableIntFieldUpdateOperationsInput | number | null + triggeredBy?: NullableStringFieldUpdateOperationsInput | string | null + smtpServer?: StringFieldUpdateOperationsInput | string + smtpPort?: IntFieldUpdateOperationsInput | number + smtpEncryption?: StringFieldUpdateOperationsInput | string + smtpUser?: StringFieldUpdateOperationsInput | string + success?: BoolFieldUpdateOperationsInput | boolean + messageId?: NullableStringFieldUpdateOperationsInput | string | null + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + smtpResponse?: NullableStringFieldUpdateOperationsInput | string | null + sentAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type EmailLogUncheckedUpdateManyInput = { + id?: IntFieldUpdateOperationsInput | number + fromAddress?: StringFieldUpdateOperationsInput | string + toAddress?: StringFieldUpdateOperationsInput | string + subject?: StringFieldUpdateOperationsInput | string + context?: StringFieldUpdateOperationsInput | string + customerId?: NullableIntFieldUpdateOperationsInput | number | null + triggeredBy?: NullableStringFieldUpdateOperationsInput | string | null + smtpServer?: StringFieldUpdateOperationsInput | string + smtpPort?: IntFieldUpdateOperationsInput | number + smtpEncryption?: StringFieldUpdateOperationsInput | string + smtpUser?: StringFieldUpdateOperationsInput | string + success?: BoolFieldUpdateOperationsInput | boolean + messageId?: NullableStringFieldUpdateOperationsInput | string | null + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + smtpResponse?: NullableStringFieldUpdateOperationsInput | string | null + sentAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + export type AppSettingCreateInput = { key: string value: string @@ -42737,6 +50510,9 @@ export namespace Prisma { lastName: string isActive?: boolean tokenInvalidatedAt?: Date | string | null + whatsappNumber?: string | null + telegramUsername?: string | null + signalNumber?: string | null createdAt?: Date | string updatedAt?: Date | string customer?: CustomerCreateNestedOneWithoutUserInput @@ -42751,6 +50527,9 @@ export namespace Prisma { lastName: string isActive?: boolean tokenInvalidatedAt?: Date | string | null + whatsappNumber?: string | null + telegramUsername?: string | null + signalNumber?: string | null customerId?: number | null createdAt?: Date | string updatedAt?: Date | string @@ -42764,6 +50543,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string customer?: CustomerUpdateOneWithoutUserNestedInput @@ -42778,6 +50560,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null customerId?: NullableIntFieldUpdateOperationsInput | number | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string @@ -42792,6 +50577,9 @@ export namespace Prisma { lastName: string isActive?: boolean tokenInvalidatedAt?: Date | string | null + whatsappNumber?: string | null + telegramUsername?: string | null + signalNumber?: string | null customerId?: number | null createdAt?: Date | string updatedAt?: Date | string @@ -42804,6 +50592,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string } @@ -42816,6 +50607,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null customerId?: NullableIntFieldUpdateOperationsInput | number | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string @@ -43011,6 +50805,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -43028,6 +50823,9 @@ export namespace Prisma { contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateInput = { @@ -43049,6 +50847,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -43066,6 +50865,9 @@ export namespace Prisma { contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerUpdateInput = { @@ -43086,6 +50888,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -43103,6 +50906,9 @@ export namespace Prisma { contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateInput = { @@ -43124,6 +50930,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -43141,6 +50948,9 @@ export namespace Prisma { contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type CustomerCreateManyInput = { @@ -43162,6 +50972,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -43190,6 +51001,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -43219,6 +51031,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -43294,6 +51107,99 @@ export namespace Prisma { updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string } + export type RepresentativeAuthorizationCreateInput = { + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + customer: CustomerCreateNestedOneWithoutAuthorizationsGivenInput + representative: CustomerCreateNestedOneWithoutAuthorizationsReceivedInput + } + + export type RepresentativeAuthorizationUncheckedCreateInput = { + id?: number + customerId: number + representativeId: number + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type RepresentativeAuthorizationUpdateInput = { + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + customer?: CustomerUpdateOneRequiredWithoutAuthorizationsGivenNestedInput + representative?: CustomerUpdateOneRequiredWithoutAuthorizationsReceivedNestedInput + } + + export type RepresentativeAuthorizationUncheckedUpdateInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + representativeId?: IntFieldUpdateOperationsInput | number + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type RepresentativeAuthorizationCreateManyInput = { + id?: number + customerId: number + representativeId: number + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type RepresentativeAuthorizationUpdateManyMutationInput = { + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type RepresentativeAuthorizationUncheckedUpdateManyInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + representativeId?: IntFieldUpdateOperationsInput | number + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + export type AddressCreateInput = { type?: $Enums.AddressType street: string @@ -43622,6 +51528,8 @@ export namespace Prisma { imapEncryption?: $Enums.MailEncryption smtpEncryption?: $Enums.MailEncryption allowSelfSignedCerts?: boolean + systemEmailAddress?: string | null + systemEmailPasswordEncrypted?: string | null isActive?: boolean isDefault?: boolean createdAt?: Date | string @@ -43645,6 +51553,8 @@ export namespace Prisma { imapEncryption?: $Enums.MailEncryption smtpEncryption?: $Enums.MailEncryption allowSelfSignedCerts?: boolean + systemEmailAddress?: string | null + systemEmailPasswordEncrypted?: string | null isActive?: boolean isDefault?: boolean createdAt?: Date | string @@ -43667,6 +51577,8 @@ export namespace Prisma { imapEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption smtpEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption allowSelfSignedCerts?: BoolFieldUpdateOperationsInput | boolean + systemEmailAddress?: NullableStringFieldUpdateOperationsInput | string | null + systemEmailPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null isActive?: BoolFieldUpdateOperationsInput | boolean isDefault?: BoolFieldUpdateOperationsInput | boolean createdAt?: DateTimeFieldUpdateOperationsInput | Date | string @@ -43690,6 +51602,8 @@ export namespace Prisma { imapEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption smtpEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption allowSelfSignedCerts?: BoolFieldUpdateOperationsInput | boolean + systemEmailAddress?: NullableStringFieldUpdateOperationsInput | string | null + systemEmailPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null isActive?: BoolFieldUpdateOperationsInput | boolean isDefault?: BoolFieldUpdateOperationsInput | boolean createdAt?: DateTimeFieldUpdateOperationsInput | Date | string @@ -43713,6 +51627,8 @@ export namespace Prisma { imapEncryption?: $Enums.MailEncryption smtpEncryption?: $Enums.MailEncryption allowSelfSignedCerts?: boolean + systemEmailAddress?: string | null + systemEmailPasswordEncrypted?: string | null isActive?: boolean isDefault?: boolean createdAt?: Date | string @@ -43735,6 +51651,8 @@ export namespace Prisma { imapEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption smtpEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption allowSelfSignedCerts?: BoolFieldUpdateOperationsInput | boolean + systemEmailAddress?: NullableStringFieldUpdateOperationsInput | string | null + systemEmailPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null isActive?: BoolFieldUpdateOperationsInput | boolean isDefault?: BoolFieldUpdateOperationsInput | boolean createdAt?: DateTimeFieldUpdateOperationsInput | Date | string @@ -43758,6 +51676,8 @@ export namespace Prisma { imapEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption smtpEncryption?: EnumMailEncryptionFieldUpdateOperationsInput | $Enums.MailEncryption allowSelfSignedCerts?: BoolFieldUpdateOperationsInput | boolean + systemEmailAddress?: NullableStringFieldUpdateOperationsInput | string | null + systemEmailPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null isActive?: BoolFieldUpdateOperationsInput | boolean isDefault?: BoolFieldUpdateOperationsInput | boolean createdAt?: DateTimeFieldUpdateOperationsInput | Date | string @@ -44157,6 +52077,10 @@ export namespace Prisma { value: number unit?: string notes?: string | null + reportedBy?: string | null + status?: $Enums.MeterReadingStatus + transferredAt?: Date | string | null + transferredBy?: string | null createdAt?: Date | string meter: MeterCreateNestedOneWithoutReadingsInput } @@ -44168,6 +52092,10 @@ export namespace Prisma { value: number unit?: string notes?: string | null + reportedBy?: string | null + status?: $Enums.MeterReadingStatus + transferredAt?: Date | string | null + transferredBy?: string | null createdAt?: Date | string } @@ -44176,6 +52104,10 @@ export namespace Prisma { value?: FloatFieldUpdateOperationsInput | number unit?: StringFieldUpdateOperationsInput | string notes?: NullableStringFieldUpdateOperationsInput | string | null + reportedBy?: NullableStringFieldUpdateOperationsInput | string | null + status?: EnumMeterReadingStatusFieldUpdateOperationsInput | $Enums.MeterReadingStatus + transferredAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + transferredBy?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string meter?: MeterUpdateOneRequiredWithoutReadingsNestedInput } @@ -44187,6 +52119,10 @@ export namespace Prisma { value?: FloatFieldUpdateOperationsInput | number unit?: StringFieldUpdateOperationsInput | string notes?: NullableStringFieldUpdateOperationsInput | string | null + reportedBy?: NullableStringFieldUpdateOperationsInput | string | null + status?: EnumMeterReadingStatusFieldUpdateOperationsInput | $Enums.MeterReadingStatus + transferredAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + transferredBy?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string } @@ -44197,6 +52133,10 @@ export namespace Prisma { value: number unit?: string notes?: string | null + reportedBy?: string | null + status?: $Enums.MeterReadingStatus + transferredAt?: Date | string | null + transferredBy?: string | null createdAt?: Date | string } @@ -44205,6 +52145,10 @@ export namespace Prisma { value?: FloatFieldUpdateOperationsInput | number unit?: StringFieldUpdateOperationsInput | string notes?: NullableStringFieldUpdateOperationsInput | string | null + reportedBy?: NullableStringFieldUpdateOperationsInput | string | null + status?: EnumMeterReadingStatusFieldUpdateOperationsInput | $Enums.MeterReadingStatus + transferredAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + transferredBy?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string } @@ -44215,6 +52159,10 @@ export namespace Prisma { value?: FloatFieldUpdateOperationsInput | number unit?: StringFieldUpdateOperationsInput | string notes?: NullableStringFieldUpdateOperationsInput | string | null + reportedBy?: NullableStringFieldUpdateOperationsInput | string | null + status?: EnumMeterReadingStatusFieldUpdateOperationsInput | $Enums.MeterReadingStatus + transferredAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + transferredBy?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string } @@ -45894,6 +53842,511 @@ export namespace Prisma { previousInsurer?: NullableStringFieldUpdateOperationsInput | string | null } + export type AuditLogCreateInput = { + userId?: number | null + userEmail: string + userRole?: string | null + customerId?: number | null + isCustomerPortal?: boolean + action: $Enums.AuditAction + sensitivity?: $Enums.AuditSensitivity + resourceType: string + resourceId?: string | null + resourceLabel?: string | null + endpoint: string + httpMethod: string + ipAddress: string + userAgent?: string | null + changesBefore?: string | null + changesAfter?: string | null + changesEncrypted?: boolean + dataSubjectId?: number | null + legalBasis?: string | null + success?: boolean + errorMessage?: string | null + durationMs?: number | null + createdAt?: Date | string + hash?: string | null + previousHash?: string | null + } + + export type AuditLogUncheckedCreateInput = { + id?: number + userId?: number | null + userEmail: string + userRole?: string | null + customerId?: number | null + isCustomerPortal?: boolean + action: $Enums.AuditAction + sensitivity?: $Enums.AuditSensitivity + resourceType: string + resourceId?: string | null + resourceLabel?: string | null + endpoint: string + httpMethod: string + ipAddress: string + userAgent?: string | null + changesBefore?: string | null + changesAfter?: string | null + changesEncrypted?: boolean + dataSubjectId?: number | null + legalBasis?: string | null + success?: boolean + errorMessage?: string | null + durationMs?: number | null + createdAt?: Date | string + hash?: string | null + previousHash?: string | null + } + + export type AuditLogUpdateInput = { + userId?: NullableIntFieldUpdateOperationsInput | number | null + userEmail?: StringFieldUpdateOperationsInput | string + userRole?: NullableStringFieldUpdateOperationsInput | string | null + customerId?: NullableIntFieldUpdateOperationsInput | number | null + isCustomerPortal?: BoolFieldUpdateOperationsInput | boolean + action?: EnumAuditActionFieldUpdateOperationsInput | $Enums.AuditAction + sensitivity?: EnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity + resourceType?: StringFieldUpdateOperationsInput | string + resourceId?: NullableStringFieldUpdateOperationsInput | string | null + resourceLabel?: NullableStringFieldUpdateOperationsInput | string | null + endpoint?: StringFieldUpdateOperationsInput | string + httpMethod?: StringFieldUpdateOperationsInput | string + ipAddress?: StringFieldUpdateOperationsInput | string + userAgent?: NullableStringFieldUpdateOperationsInput | string | null + changesBefore?: NullableStringFieldUpdateOperationsInput | string | null + changesAfter?: NullableStringFieldUpdateOperationsInput | string | null + changesEncrypted?: BoolFieldUpdateOperationsInput | boolean + dataSubjectId?: NullableIntFieldUpdateOperationsInput | number | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + success?: BoolFieldUpdateOperationsInput | boolean + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + durationMs?: NullableIntFieldUpdateOperationsInput | number | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + hash?: NullableStringFieldUpdateOperationsInput | string | null + previousHash?: NullableStringFieldUpdateOperationsInput | string | null + } + + export type AuditLogUncheckedUpdateInput = { + id?: IntFieldUpdateOperationsInput | number + userId?: NullableIntFieldUpdateOperationsInput | number | null + userEmail?: StringFieldUpdateOperationsInput | string + userRole?: NullableStringFieldUpdateOperationsInput | string | null + customerId?: NullableIntFieldUpdateOperationsInput | number | null + isCustomerPortal?: BoolFieldUpdateOperationsInput | boolean + action?: EnumAuditActionFieldUpdateOperationsInput | $Enums.AuditAction + sensitivity?: EnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity + resourceType?: StringFieldUpdateOperationsInput | string + resourceId?: NullableStringFieldUpdateOperationsInput | string | null + resourceLabel?: NullableStringFieldUpdateOperationsInput | string | null + endpoint?: StringFieldUpdateOperationsInput | string + httpMethod?: StringFieldUpdateOperationsInput | string + ipAddress?: StringFieldUpdateOperationsInput | string + userAgent?: NullableStringFieldUpdateOperationsInput | string | null + changesBefore?: NullableStringFieldUpdateOperationsInput | string | null + changesAfter?: NullableStringFieldUpdateOperationsInput | string | null + changesEncrypted?: BoolFieldUpdateOperationsInput | boolean + dataSubjectId?: NullableIntFieldUpdateOperationsInput | number | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + success?: BoolFieldUpdateOperationsInput | boolean + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + durationMs?: NullableIntFieldUpdateOperationsInput | number | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + hash?: NullableStringFieldUpdateOperationsInput | string | null + previousHash?: NullableStringFieldUpdateOperationsInput | string | null + } + + export type AuditLogCreateManyInput = { + id?: number + userId?: number | null + userEmail: string + userRole?: string | null + customerId?: number | null + isCustomerPortal?: boolean + action: $Enums.AuditAction + sensitivity?: $Enums.AuditSensitivity + resourceType: string + resourceId?: string | null + resourceLabel?: string | null + endpoint: string + httpMethod: string + ipAddress: string + userAgent?: string | null + changesBefore?: string | null + changesAfter?: string | null + changesEncrypted?: boolean + dataSubjectId?: number | null + legalBasis?: string | null + success?: boolean + errorMessage?: string | null + durationMs?: number | null + createdAt?: Date | string + hash?: string | null + previousHash?: string | null + } + + export type AuditLogUpdateManyMutationInput = { + userId?: NullableIntFieldUpdateOperationsInput | number | null + userEmail?: StringFieldUpdateOperationsInput | string + userRole?: NullableStringFieldUpdateOperationsInput | string | null + customerId?: NullableIntFieldUpdateOperationsInput | number | null + isCustomerPortal?: BoolFieldUpdateOperationsInput | boolean + action?: EnumAuditActionFieldUpdateOperationsInput | $Enums.AuditAction + sensitivity?: EnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity + resourceType?: StringFieldUpdateOperationsInput | string + resourceId?: NullableStringFieldUpdateOperationsInput | string | null + resourceLabel?: NullableStringFieldUpdateOperationsInput | string | null + endpoint?: StringFieldUpdateOperationsInput | string + httpMethod?: StringFieldUpdateOperationsInput | string + ipAddress?: StringFieldUpdateOperationsInput | string + userAgent?: NullableStringFieldUpdateOperationsInput | string | null + changesBefore?: NullableStringFieldUpdateOperationsInput | string | null + changesAfter?: NullableStringFieldUpdateOperationsInput | string | null + changesEncrypted?: BoolFieldUpdateOperationsInput | boolean + dataSubjectId?: NullableIntFieldUpdateOperationsInput | number | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + success?: BoolFieldUpdateOperationsInput | boolean + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + durationMs?: NullableIntFieldUpdateOperationsInput | number | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + hash?: NullableStringFieldUpdateOperationsInput | string | null + previousHash?: NullableStringFieldUpdateOperationsInput | string | null + } + + export type AuditLogUncheckedUpdateManyInput = { + id?: IntFieldUpdateOperationsInput | number + userId?: NullableIntFieldUpdateOperationsInput | number | null + userEmail?: StringFieldUpdateOperationsInput | string + userRole?: NullableStringFieldUpdateOperationsInput | string | null + customerId?: NullableIntFieldUpdateOperationsInput | number | null + isCustomerPortal?: BoolFieldUpdateOperationsInput | boolean + action?: EnumAuditActionFieldUpdateOperationsInput | $Enums.AuditAction + sensitivity?: EnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity + resourceType?: StringFieldUpdateOperationsInput | string + resourceId?: NullableStringFieldUpdateOperationsInput | string | null + resourceLabel?: NullableStringFieldUpdateOperationsInput | string | null + endpoint?: StringFieldUpdateOperationsInput | string + httpMethod?: StringFieldUpdateOperationsInput | string + ipAddress?: StringFieldUpdateOperationsInput | string + userAgent?: NullableStringFieldUpdateOperationsInput | string | null + changesBefore?: NullableStringFieldUpdateOperationsInput | string | null + changesAfter?: NullableStringFieldUpdateOperationsInput | string | null + changesEncrypted?: BoolFieldUpdateOperationsInput | boolean + dataSubjectId?: NullableIntFieldUpdateOperationsInput | number | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + success?: BoolFieldUpdateOperationsInput | boolean + errorMessage?: NullableStringFieldUpdateOperationsInput | string | null + durationMs?: NullableIntFieldUpdateOperationsInput | number | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + hash?: NullableStringFieldUpdateOperationsInput | string | null + previousHash?: NullableStringFieldUpdateOperationsInput | string | null + } + + export type CustomerConsentCreateInput = { + consentType: $Enums.ConsentType + status?: $Enums.ConsentStatus + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + version?: string | null + ipAddress?: string | null + createdBy: string + createdAt?: Date | string + updatedAt?: Date | string + customer: CustomerCreateNestedOneWithoutConsentsInput + } + + export type CustomerConsentUncheckedCreateInput = { + id?: number + customerId: number + consentType: $Enums.ConsentType + status?: $Enums.ConsentStatus + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + version?: string | null + ipAddress?: string | null + createdBy: string + createdAt?: Date | string + updatedAt?: Date | string + } + + export type CustomerConsentUpdateInput = { + consentType?: EnumConsentTypeFieldUpdateOperationsInput | $Enums.ConsentType + status?: EnumConsentStatusFieldUpdateOperationsInput | $Enums.ConsentStatus + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + version?: NullableStringFieldUpdateOperationsInput | string | null + ipAddress?: NullableStringFieldUpdateOperationsInput | string | null + createdBy?: StringFieldUpdateOperationsInput | string + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + customer?: CustomerUpdateOneRequiredWithoutConsentsNestedInput + } + + export type CustomerConsentUncheckedUpdateInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + consentType?: EnumConsentTypeFieldUpdateOperationsInput | $Enums.ConsentType + status?: EnumConsentStatusFieldUpdateOperationsInput | $Enums.ConsentStatus + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + version?: NullableStringFieldUpdateOperationsInput | string | null + ipAddress?: NullableStringFieldUpdateOperationsInput | string | null + createdBy?: StringFieldUpdateOperationsInput | string + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type CustomerConsentCreateManyInput = { + id?: number + customerId: number + consentType: $Enums.ConsentType + status?: $Enums.ConsentStatus + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + version?: string | null + ipAddress?: string | null + createdBy: string + createdAt?: Date | string + updatedAt?: Date | string + } + + export type CustomerConsentUpdateManyMutationInput = { + consentType?: EnumConsentTypeFieldUpdateOperationsInput | $Enums.ConsentType + status?: EnumConsentStatusFieldUpdateOperationsInput | $Enums.ConsentStatus + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + version?: NullableStringFieldUpdateOperationsInput | string | null + ipAddress?: NullableStringFieldUpdateOperationsInput | string | null + createdBy?: StringFieldUpdateOperationsInput | string + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type CustomerConsentUncheckedUpdateManyInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + consentType?: EnumConsentTypeFieldUpdateOperationsInput | $Enums.ConsentType + status?: EnumConsentStatusFieldUpdateOperationsInput | $Enums.ConsentStatus + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + version?: NullableStringFieldUpdateOperationsInput | string | null + ipAddress?: NullableStringFieldUpdateOperationsInput | string | null + createdBy?: StringFieldUpdateOperationsInput | string + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type DataDeletionRequestCreateInput = { + customerId: number + status?: $Enums.DeletionRequestStatus + requestedAt?: Date | string + requestSource: string + requestedBy: string + processedAt?: Date | string | null + processedBy?: string | null + deletedData?: string | null + retainedData?: string | null + retentionReason?: string | null + proofDocument?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type DataDeletionRequestUncheckedCreateInput = { + id?: number + customerId: number + status?: $Enums.DeletionRequestStatus + requestedAt?: Date | string + requestSource: string + requestedBy: string + processedAt?: Date | string | null + processedBy?: string | null + deletedData?: string | null + retainedData?: string | null + retentionReason?: string | null + proofDocument?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type DataDeletionRequestUpdateInput = { + customerId?: IntFieldUpdateOperationsInput | number + status?: EnumDeletionRequestStatusFieldUpdateOperationsInput | $Enums.DeletionRequestStatus + requestedAt?: DateTimeFieldUpdateOperationsInput | Date | string + requestSource?: StringFieldUpdateOperationsInput | string + requestedBy?: StringFieldUpdateOperationsInput | string + processedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + processedBy?: NullableStringFieldUpdateOperationsInput | string | null + deletedData?: NullableStringFieldUpdateOperationsInput | string | null + retainedData?: NullableStringFieldUpdateOperationsInput | string | null + retentionReason?: NullableStringFieldUpdateOperationsInput | string | null + proofDocument?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type DataDeletionRequestUncheckedUpdateInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + status?: EnumDeletionRequestStatusFieldUpdateOperationsInput | $Enums.DeletionRequestStatus + requestedAt?: DateTimeFieldUpdateOperationsInput | Date | string + requestSource?: StringFieldUpdateOperationsInput | string + requestedBy?: StringFieldUpdateOperationsInput | string + processedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + processedBy?: NullableStringFieldUpdateOperationsInput | string | null + deletedData?: NullableStringFieldUpdateOperationsInput | string | null + retainedData?: NullableStringFieldUpdateOperationsInput | string | null + retentionReason?: NullableStringFieldUpdateOperationsInput | string | null + proofDocument?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type DataDeletionRequestCreateManyInput = { + id?: number + customerId: number + status?: $Enums.DeletionRequestStatus + requestedAt?: Date | string + requestSource: string + requestedBy: string + processedAt?: Date | string | null + processedBy?: string | null + deletedData?: string | null + retainedData?: string | null + retentionReason?: string | null + proofDocument?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type DataDeletionRequestUpdateManyMutationInput = { + customerId?: IntFieldUpdateOperationsInput | number + status?: EnumDeletionRequestStatusFieldUpdateOperationsInput | $Enums.DeletionRequestStatus + requestedAt?: DateTimeFieldUpdateOperationsInput | Date | string + requestSource?: StringFieldUpdateOperationsInput | string + requestedBy?: StringFieldUpdateOperationsInput | string + processedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + processedBy?: NullableStringFieldUpdateOperationsInput | string | null + deletedData?: NullableStringFieldUpdateOperationsInput | string | null + retainedData?: NullableStringFieldUpdateOperationsInput | string | null + retentionReason?: NullableStringFieldUpdateOperationsInput | string | null + proofDocument?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type DataDeletionRequestUncheckedUpdateManyInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + status?: EnumDeletionRequestStatusFieldUpdateOperationsInput | $Enums.DeletionRequestStatus + requestedAt?: DateTimeFieldUpdateOperationsInput | Date | string + requestSource?: StringFieldUpdateOperationsInput | string + requestedBy?: StringFieldUpdateOperationsInput | string + processedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + processedBy?: NullableStringFieldUpdateOperationsInput | string | null + deletedData?: NullableStringFieldUpdateOperationsInput | string | null + retainedData?: NullableStringFieldUpdateOperationsInput | string | null + retentionReason?: NullableStringFieldUpdateOperationsInput | string | null + proofDocument?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type AuditRetentionPolicyCreateInput = { + resourceType: string + sensitivity?: $Enums.AuditSensitivity | null + retentionDays: number + description?: string | null + legalBasis?: string | null + isActive?: boolean + createdAt?: Date | string + updatedAt?: Date | string + } + + export type AuditRetentionPolicyUncheckedCreateInput = { + id?: number + resourceType: string + sensitivity?: $Enums.AuditSensitivity | null + retentionDays: number + description?: string | null + legalBasis?: string | null + isActive?: boolean + createdAt?: Date | string + updatedAt?: Date | string + } + + export type AuditRetentionPolicyUpdateInput = { + resourceType?: StringFieldUpdateOperationsInput | string + sensitivity?: NullableEnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity | null + retentionDays?: IntFieldUpdateOperationsInput | number + description?: NullableStringFieldUpdateOperationsInput | string | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + isActive?: BoolFieldUpdateOperationsInput | boolean + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type AuditRetentionPolicyUncheckedUpdateInput = { + id?: IntFieldUpdateOperationsInput | number + resourceType?: StringFieldUpdateOperationsInput | string + sensitivity?: NullableEnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity | null + retentionDays?: IntFieldUpdateOperationsInput | number + description?: NullableStringFieldUpdateOperationsInput | string | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + isActive?: BoolFieldUpdateOperationsInput | boolean + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type AuditRetentionPolicyCreateManyInput = { + id?: number + resourceType: string + sensitivity?: $Enums.AuditSensitivity | null + retentionDays: number + description?: string | null + legalBasis?: string | null + isActive?: boolean + createdAt?: Date | string + updatedAt?: Date | string + } + + export type AuditRetentionPolicyUpdateManyMutationInput = { + resourceType?: StringFieldUpdateOperationsInput | string + sensitivity?: NullableEnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity | null + retentionDays?: IntFieldUpdateOperationsInput | number + description?: NullableStringFieldUpdateOperationsInput | string | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + isActive?: BoolFieldUpdateOperationsInput | boolean + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type AuditRetentionPolicyUncheckedUpdateManyInput = { + id?: IntFieldUpdateOperationsInput | number + resourceType?: StringFieldUpdateOperationsInput | string + sensitivity?: NullableEnumAuditSensitivityFieldUpdateOperationsInput | $Enums.AuditSensitivity | null + retentionDays?: IntFieldUpdateOperationsInput | number + description?: NullableStringFieldUpdateOperationsInput | string | null + legalBasis?: NullableStringFieldUpdateOperationsInput | string | null + isActive?: BoolFieldUpdateOperationsInput | boolean + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + export type IntFilter<$PrismaModel = never> = { equals?: number | IntFieldRefInput<$PrismaModel> in?: number[] @@ -45919,6 +54372,36 @@ export namespace Prisma { not?: NestedStringFilter<$PrismaModel> | string } + export type IntNullableFilter<$PrismaModel = never> = { + equals?: number | IntFieldRefInput<$PrismaModel> | null + in?: number[] | null + notIn?: number[] | null + lt?: number | IntFieldRefInput<$PrismaModel> + lte?: number | IntFieldRefInput<$PrismaModel> + gt?: number | IntFieldRefInput<$PrismaModel> + gte?: number | IntFieldRefInput<$PrismaModel> + not?: NestedIntNullableFilter<$PrismaModel> | number | null + } + + export type StringNullableFilter<$PrismaModel = never> = { + equals?: string | StringFieldRefInput<$PrismaModel> | null + in?: string[] | null + notIn?: string[] | null + lt?: string | StringFieldRefInput<$PrismaModel> + lte?: string | StringFieldRefInput<$PrismaModel> + gt?: string | StringFieldRefInput<$PrismaModel> + gte?: string | StringFieldRefInput<$PrismaModel> + contains?: string | StringFieldRefInput<$PrismaModel> + startsWith?: string | StringFieldRefInput<$PrismaModel> + endsWith?: string | StringFieldRefInput<$PrismaModel> + not?: NestedStringNullableFilter<$PrismaModel> | string | null + } + + export type BoolFilter<$PrismaModel = never> = { + equals?: boolean | BooleanFieldRefInput<$PrismaModel> + not?: NestedBoolFilter<$PrismaModel> | boolean + } + export type DateTimeFilter<$PrismaModel = never> = { equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> in?: Date[] | string[] @@ -45930,36 +54413,78 @@ export namespace Prisma { not?: NestedDateTimeFilter<$PrismaModel> | Date | string } - export type AppSettingCountOrderByAggregateInput = { - id?: SortOrder - key?: SortOrder - value?: SortOrder - createdAt?: SortOrder - updatedAt?: SortOrder + export type SortOrderInput = { + sort: SortOrder + nulls?: NullsOrder } - export type AppSettingAvgOrderByAggregateInput = { + export type EmailLogCountOrderByAggregateInput = { id?: SortOrder + fromAddress?: SortOrder + toAddress?: SortOrder + subject?: SortOrder + context?: SortOrder + customerId?: SortOrder + triggeredBy?: SortOrder + smtpServer?: SortOrder + smtpPort?: SortOrder + smtpEncryption?: SortOrder + smtpUser?: SortOrder + success?: SortOrder + messageId?: SortOrder + errorMessage?: SortOrder + smtpResponse?: SortOrder + sentAt?: SortOrder } - export type AppSettingMaxOrderByAggregateInput = { + export type EmailLogAvgOrderByAggregateInput = { id?: SortOrder - key?: SortOrder - value?: SortOrder - createdAt?: SortOrder - updatedAt?: SortOrder + customerId?: SortOrder + smtpPort?: SortOrder } - export type AppSettingMinOrderByAggregateInput = { + export type EmailLogMaxOrderByAggregateInput = { id?: SortOrder - key?: SortOrder - value?: SortOrder - createdAt?: SortOrder - updatedAt?: SortOrder + fromAddress?: SortOrder + toAddress?: SortOrder + subject?: SortOrder + context?: SortOrder + customerId?: SortOrder + triggeredBy?: SortOrder + smtpServer?: SortOrder + smtpPort?: SortOrder + smtpEncryption?: SortOrder + smtpUser?: SortOrder + success?: SortOrder + messageId?: SortOrder + errorMessage?: SortOrder + smtpResponse?: SortOrder + sentAt?: SortOrder } - export type AppSettingSumOrderByAggregateInput = { + export type EmailLogMinOrderByAggregateInput = { id?: SortOrder + fromAddress?: SortOrder + toAddress?: SortOrder + subject?: SortOrder + context?: SortOrder + customerId?: SortOrder + triggeredBy?: SortOrder + smtpServer?: SortOrder + smtpPort?: SortOrder + smtpEncryption?: SortOrder + smtpUser?: SortOrder + success?: SortOrder + messageId?: SortOrder + errorMessage?: SortOrder + smtpResponse?: SortOrder + sentAt?: SortOrder + } + + export type EmailLogSumOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + smtpPort?: SortOrder } export type IntWithAggregatesFilter<$PrismaModel = never> = { @@ -45995,6 +54520,47 @@ export namespace Prisma { _max?: NestedStringFilter<$PrismaModel> } + export type IntNullableWithAggregatesFilter<$PrismaModel = never> = { + equals?: number | IntFieldRefInput<$PrismaModel> | null + in?: number[] | null + notIn?: number[] | null + lt?: number | IntFieldRefInput<$PrismaModel> + lte?: number | IntFieldRefInput<$PrismaModel> + gt?: number | IntFieldRefInput<$PrismaModel> + gte?: number | IntFieldRefInput<$PrismaModel> + not?: NestedIntNullableWithAggregatesFilter<$PrismaModel> | number | null + _count?: NestedIntNullableFilter<$PrismaModel> + _avg?: NestedFloatNullableFilter<$PrismaModel> + _sum?: NestedIntNullableFilter<$PrismaModel> + _min?: NestedIntNullableFilter<$PrismaModel> + _max?: NestedIntNullableFilter<$PrismaModel> + } + + export type StringNullableWithAggregatesFilter<$PrismaModel = never> = { + equals?: string | StringFieldRefInput<$PrismaModel> | null + in?: string[] | null + notIn?: string[] | null + lt?: string | StringFieldRefInput<$PrismaModel> + lte?: string | StringFieldRefInput<$PrismaModel> + gt?: string | StringFieldRefInput<$PrismaModel> + gte?: string | StringFieldRefInput<$PrismaModel> + contains?: string | StringFieldRefInput<$PrismaModel> + startsWith?: string | StringFieldRefInput<$PrismaModel> + endsWith?: string | StringFieldRefInput<$PrismaModel> + not?: NestedStringNullableWithAggregatesFilter<$PrismaModel> | string | null + _count?: NestedIntNullableFilter<$PrismaModel> + _min?: NestedStringNullableFilter<$PrismaModel> + _max?: NestedStringNullableFilter<$PrismaModel> + } + + export type BoolWithAggregatesFilter<$PrismaModel = never> = { + equals?: boolean | BooleanFieldRefInput<$PrismaModel> + not?: NestedBoolWithAggregatesFilter<$PrismaModel> | boolean + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedBoolFilter<$PrismaModel> + _max?: NestedBoolFilter<$PrismaModel> + } + export type DateTimeWithAggregatesFilter<$PrismaModel = never> = { equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> in?: Date[] | string[] @@ -46009,9 +54575,36 @@ export namespace Prisma { _max?: NestedDateTimeFilter<$PrismaModel> } - export type BoolFilter<$PrismaModel = never> = { - equals?: boolean | BooleanFieldRefInput<$PrismaModel> - not?: NestedBoolFilter<$PrismaModel> | boolean + export type AppSettingCountOrderByAggregateInput = { + id?: SortOrder + key?: SortOrder + value?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type AppSettingAvgOrderByAggregateInput = { + id?: SortOrder + } + + export type AppSettingMaxOrderByAggregateInput = { + id?: SortOrder + key?: SortOrder + value?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type AppSettingMinOrderByAggregateInput = { + id?: SortOrder + key?: SortOrder + value?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type AppSettingSumOrderByAggregateInput = { + id?: SortOrder } export type DateTimeNullableFilter<$PrismaModel = never> = { @@ -46025,17 +54618,6 @@ export namespace Prisma { not?: NestedDateTimeNullableFilter<$PrismaModel> | Date | string | null } - export type IntNullableFilter<$PrismaModel = never> = { - equals?: number | IntFieldRefInput<$PrismaModel> | null - in?: number[] | null - notIn?: number[] | null - lt?: number | IntFieldRefInput<$PrismaModel> - lte?: number | IntFieldRefInput<$PrismaModel> - gt?: number | IntFieldRefInput<$PrismaModel> - gte?: number | IntFieldRefInput<$PrismaModel> - not?: NestedIntNullableFilter<$PrismaModel> | number | null - } - export type CustomerNullableRelationFilter = { is?: CustomerWhereInput | null isNot?: CustomerWhereInput | null @@ -46047,11 +54629,6 @@ export namespace Prisma { none?: UserRoleWhereInput } - export type SortOrderInput = { - sort: SortOrder - nulls?: NullsOrder - } - export type UserRoleOrderByRelationAggregateInput = { _count?: SortOrder } @@ -46064,6 +54641,9 @@ export namespace Prisma { lastName?: SortOrder isActive?: SortOrder tokenInvalidatedAt?: SortOrder + whatsappNumber?: SortOrder + telegramUsername?: SortOrder + signalNumber?: SortOrder customerId?: SortOrder createdAt?: SortOrder updatedAt?: SortOrder @@ -46082,6 +54662,9 @@ export namespace Prisma { lastName?: SortOrder isActive?: SortOrder tokenInvalidatedAt?: SortOrder + whatsappNumber?: SortOrder + telegramUsername?: SortOrder + signalNumber?: SortOrder customerId?: SortOrder createdAt?: SortOrder updatedAt?: SortOrder @@ -46095,6 +54678,9 @@ export namespace Prisma { lastName?: SortOrder isActive?: SortOrder tokenInvalidatedAt?: SortOrder + whatsappNumber?: SortOrder + telegramUsername?: SortOrder + signalNumber?: SortOrder customerId?: SortOrder createdAt?: SortOrder updatedAt?: SortOrder @@ -46105,14 +54691,6 @@ export namespace Prisma { customerId?: SortOrder } - export type BoolWithAggregatesFilter<$PrismaModel = never> = { - equals?: boolean | BooleanFieldRefInput<$PrismaModel> - not?: NestedBoolWithAggregatesFilter<$PrismaModel> | boolean - _count?: NestedIntFilter<$PrismaModel> - _min?: NestedBoolFilter<$PrismaModel> - _max?: NestedBoolFilter<$PrismaModel> - } - export type DateTimeNullableWithAggregatesFilter<$PrismaModel = never> = { equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> | null in?: Date[] | string[] | null @@ -46127,36 +54705,6 @@ export namespace Prisma { _max?: NestedDateTimeNullableFilter<$PrismaModel> } - export type IntNullableWithAggregatesFilter<$PrismaModel = never> = { - equals?: number | IntFieldRefInput<$PrismaModel> | null - in?: number[] | null - notIn?: number[] | null - lt?: number | IntFieldRefInput<$PrismaModel> - lte?: number | IntFieldRefInput<$PrismaModel> - gt?: number | IntFieldRefInput<$PrismaModel> - gte?: number | IntFieldRefInput<$PrismaModel> - not?: NestedIntNullableWithAggregatesFilter<$PrismaModel> | number | null - _count?: NestedIntNullableFilter<$PrismaModel> - _avg?: NestedFloatNullableFilter<$PrismaModel> - _sum?: NestedIntNullableFilter<$PrismaModel> - _min?: NestedIntNullableFilter<$PrismaModel> - _max?: NestedIntNullableFilter<$PrismaModel> - } - - export type StringNullableFilter<$PrismaModel = never> = { - equals?: string | StringFieldRefInput<$PrismaModel> | null - in?: string[] | null - notIn?: string[] | null - lt?: string | StringFieldRefInput<$PrismaModel> - lte?: string | StringFieldRefInput<$PrismaModel> - gt?: string | StringFieldRefInput<$PrismaModel> - gte?: string | StringFieldRefInput<$PrismaModel> - contains?: string | StringFieldRefInput<$PrismaModel> - startsWith?: string | StringFieldRefInput<$PrismaModel> - endsWith?: string | StringFieldRefInput<$PrismaModel> - not?: NestedStringNullableFilter<$PrismaModel> | string | null - } - export type RolePermissionListRelationFilter = { every?: RolePermissionWhereInput some?: RolePermissionWhereInput @@ -46199,23 +54747,6 @@ export namespace Prisma { id?: SortOrder } - export type StringNullableWithAggregatesFilter<$PrismaModel = never> = { - equals?: string | StringFieldRefInput<$PrismaModel> | null - in?: string[] | null - notIn?: string[] | null - lt?: string | StringFieldRefInput<$PrismaModel> - lte?: string | StringFieldRefInput<$PrismaModel> - gt?: string | StringFieldRefInput<$PrismaModel> - gte?: string | StringFieldRefInput<$PrismaModel> - contains?: string | StringFieldRefInput<$PrismaModel> - startsWith?: string | StringFieldRefInput<$PrismaModel> - endsWith?: string | StringFieldRefInput<$PrismaModel> - not?: NestedStringNullableWithAggregatesFilter<$PrismaModel> | string | null - _count?: NestedIntNullableFilter<$PrismaModel> - _min?: NestedStringNullableFilter<$PrismaModel> - _max?: NestedStringNullableFilter<$PrismaModel> - } - export type PermissionResourceActionCompoundUniqueInput = { resource: string action: string @@ -46376,6 +54907,18 @@ export namespace Prisma { none?: CustomerRepresentativeWhereInput } + export type RepresentativeAuthorizationListRelationFilter = { + every?: RepresentativeAuthorizationWhereInput + some?: RepresentativeAuthorizationWhereInput + none?: RepresentativeAuthorizationWhereInput + } + + export type CustomerConsentListRelationFilter = { + every?: CustomerConsentWhereInput + some?: CustomerConsentWhereInput + none?: CustomerConsentWhereInput + } + export type AddressOrderByRelationAggregateInput = { _count?: SortOrder } @@ -46404,6 +54947,14 @@ export namespace Prisma { _count?: SortOrder } + export type RepresentativeAuthorizationOrderByRelationAggregateInput = { + _count?: SortOrder + } + + export type CustomerConsentOrderByRelationAggregateInput = { + _count?: SortOrder + } + export type CustomerCountOrderByAggregateInput = { id?: SortOrder customerNumber?: SortOrder @@ -46423,6 +54974,7 @@ export namespace Prisma { commercialRegisterPath?: SortOrder commercialRegisterNumber?: SortOrder privacyPolicyPath?: SortOrder + consentHash?: SortOrder notes?: SortOrder portalEnabled?: SortOrder portalEmail?: SortOrder @@ -46456,6 +55008,7 @@ export namespace Prisma { commercialRegisterPath?: SortOrder commercialRegisterNumber?: SortOrder privacyPolicyPath?: SortOrder + consentHash?: SortOrder notes?: SortOrder portalEnabled?: SortOrder portalEmail?: SortOrder @@ -46485,6 +55038,7 @@ export namespace Prisma { commercialRegisterPath?: SortOrder commercialRegisterNumber?: SortOrder privacyPolicyPath?: SortOrder + consentHash?: SortOrder notes?: SortOrder portalEnabled?: SortOrder portalEmail?: SortOrder @@ -46561,6 +55115,65 @@ export namespace Prisma { representativeId?: SortOrder } + export type RepresentativeAuthorizationCustomerIdRepresentativeIdCompoundUniqueInput = { + customerId: number + representativeId: number + } + + export type RepresentativeAuthorizationCountOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + representativeId?: SortOrder + isGranted?: SortOrder + grantedAt?: SortOrder + withdrawnAt?: SortOrder + source?: SortOrder + documentPath?: SortOrder + notes?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type RepresentativeAuthorizationAvgOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + representativeId?: SortOrder + } + + export type RepresentativeAuthorizationMaxOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + representativeId?: SortOrder + isGranted?: SortOrder + grantedAt?: SortOrder + withdrawnAt?: SortOrder + source?: SortOrder + documentPath?: SortOrder + notes?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type RepresentativeAuthorizationMinOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + representativeId?: SortOrder + isGranted?: SortOrder + grantedAt?: SortOrder + withdrawnAt?: SortOrder + source?: SortOrder + documentPath?: SortOrder + notes?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type RepresentativeAuthorizationSumOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + representativeId?: SortOrder + } + export type EnumAddressTypeFilter<$PrismaModel = never> = { equals?: $Enums.AddressType | EnumAddressTypeFieldRefInput<$PrismaModel> in?: $Enums.AddressType[] @@ -46788,6 +55401,8 @@ export namespace Prisma { imapEncryption?: SortOrder smtpEncryption?: SortOrder allowSelfSignedCerts?: SortOrder + systemEmailAddress?: SortOrder + systemEmailPasswordEncrypted?: SortOrder isActive?: SortOrder isDefault?: SortOrder createdAt?: SortOrder @@ -46817,6 +55432,8 @@ export namespace Prisma { imapEncryption?: SortOrder smtpEncryption?: SortOrder allowSelfSignedCerts?: SortOrder + systemEmailAddress?: SortOrder + systemEmailPasswordEncrypted?: SortOrder isActive?: SortOrder isDefault?: SortOrder createdAt?: SortOrder @@ -46840,6 +55457,8 @@ export namespace Prisma { imapEncryption?: SortOrder smtpEncryption?: SortOrder allowSelfSignedCerts?: SortOrder + systemEmailAddress?: SortOrder + systemEmailPasswordEncrypted?: SortOrder isActive?: SortOrder isDefault?: SortOrder createdAt?: SortOrder @@ -47164,6 +55783,13 @@ export namespace Prisma { not?: NestedFloatFilter<$PrismaModel> | number } + export type EnumMeterReadingStatusFilter<$PrismaModel = never> = { + equals?: $Enums.MeterReadingStatus | EnumMeterReadingStatusFieldRefInput<$PrismaModel> + in?: $Enums.MeterReadingStatus[] + notIn?: $Enums.MeterReadingStatus[] + not?: NestedEnumMeterReadingStatusFilter<$PrismaModel> | $Enums.MeterReadingStatus + } + export type MeterRelationFilter = { is?: MeterWhereInput isNot?: MeterWhereInput @@ -47176,6 +55802,10 @@ export namespace Prisma { value?: SortOrder unit?: SortOrder notes?: SortOrder + reportedBy?: SortOrder + status?: SortOrder + transferredAt?: SortOrder + transferredBy?: SortOrder createdAt?: SortOrder } @@ -47192,6 +55822,10 @@ export namespace Prisma { value?: SortOrder unit?: SortOrder notes?: SortOrder + reportedBy?: SortOrder + status?: SortOrder + transferredAt?: SortOrder + transferredBy?: SortOrder createdAt?: SortOrder } @@ -47202,6 +55836,10 @@ export namespace Prisma { value?: SortOrder unit?: SortOrder notes?: SortOrder + reportedBy?: SortOrder + status?: SortOrder + transferredAt?: SortOrder + transferredBy?: SortOrder createdAt?: SortOrder } @@ -47227,6 +55865,16 @@ export namespace Prisma { _max?: NestedFloatFilter<$PrismaModel> } + export type EnumMeterReadingStatusWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.MeterReadingStatus | EnumMeterReadingStatusFieldRefInput<$PrismaModel> + in?: $Enums.MeterReadingStatus[] + notIn?: $Enums.MeterReadingStatus[] + not?: NestedEnumMeterReadingStatusWithAggregatesFilter<$PrismaModel> | $Enums.MeterReadingStatus + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumMeterReadingStatusFilter<$PrismaModel> + _max?: NestedEnumMeterReadingStatusFilter<$PrismaModel> + } + export type SalesPlatformCountOrderByAggregateInput = { id?: SortOrder name?: SortOrder @@ -48467,12 +57115,400 @@ export namespace Prisma { _max?: NestedEnumInsuranceTypeFilter<$PrismaModel> } + export type EnumAuditActionFilter<$PrismaModel = never> = { + equals?: $Enums.AuditAction | EnumAuditActionFieldRefInput<$PrismaModel> + in?: $Enums.AuditAction[] + notIn?: $Enums.AuditAction[] + not?: NestedEnumAuditActionFilter<$PrismaModel> | $Enums.AuditAction + } + + export type EnumAuditSensitivityFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> + in?: $Enums.AuditSensitivity[] + notIn?: $Enums.AuditSensitivity[] + not?: NestedEnumAuditSensitivityFilter<$PrismaModel> | $Enums.AuditSensitivity + } + + export type AuditLogCountOrderByAggregateInput = { + id?: SortOrder + userId?: SortOrder + userEmail?: SortOrder + userRole?: SortOrder + customerId?: SortOrder + isCustomerPortal?: SortOrder + action?: SortOrder + sensitivity?: SortOrder + resourceType?: SortOrder + resourceId?: SortOrder + resourceLabel?: SortOrder + endpoint?: SortOrder + httpMethod?: SortOrder + ipAddress?: SortOrder + userAgent?: SortOrder + changesBefore?: SortOrder + changesAfter?: SortOrder + changesEncrypted?: SortOrder + dataSubjectId?: SortOrder + legalBasis?: SortOrder + success?: SortOrder + errorMessage?: SortOrder + durationMs?: SortOrder + createdAt?: SortOrder + hash?: SortOrder + previousHash?: SortOrder + } + + export type AuditLogAvgOrderByAggregateInput = { + id?: SortOrder + userId?: SortOrder + customerId?: SortOrder + dataSubjectId?: SortOrder + durationMs?: SortOrder + } + + export type AuditLogMaxOrderByAggregateInput = { + id?: SortOrder + userId?: SortOrder + userEmail?: SortOrder + userRole?: SortOrder + customerId?: SortOrder + isCustomerPortal?: SortOrder + action?: SortOrder + sensitivity?: SortOrder + resourceType?: SortOrder + resourceId?: SortOrder + resourceLabel?: SortOrder + endpoint?: SortOrder + httpMethod?: SortOrder + ipAddress?: SortOrder + userAgent?: SortOrder + changesBefore?: SortOrder + changesAfter?: SortOrder + changesEncrypted?: SortOrder + dataSubjectId?: SortOrder + legalBasis?: SortOrder + success?: SortOrder + errorMessage?: SortOrder + durationMs?: SortOrder + createdAt?: SortOrder + hash?: SortOrder + previousHash?: SortOrder + } + + export type AuditLogMinOrderByAggregateInput = { + id?: SortOrder + userId?: SortOrder + userEmail?: SortOrder + userRole?: SortOrder + customerId?: SortOrder + isCustomerPortal?: SortOrder + action?: SortOrder + sensitivity?: SortOrder + resourceType?: SortOrder + resourceId?: SortOrder + resourceLabel?: SortOrder + endpoint?: SortOrder + httpMethod?: SortOrder + ipAddress?: SortOrder + userAgent?: SortOrder + changesBefore?: SortOrder + changesAfter?: SortOrder + changesEncrypted?: SortOrder + dataSubjectId?: SortOrder + legalBasis?: SortOrder + success?: SortOrder + errorMessage?: SortOrder + durationMs?: SortOrder + createdAt?: SortOrder + hash?: SortOrder + previousHash?: SortOrder + } + + export type AuditLogSumOrderByAggregateInput = { + id?: SortOrder + userId?: SortOrder + customerId?: SortOrder + dataSubjectId?: SortOrder + durationMs?: SortOrder + } + + export type EnumAuditActionWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.AuditAction | EnumAuditActionFieldRefInput<$PrismaModel> + in?: $Enums.AuditAction[] + notIn?: $Enums.AuditAction[] + not?: NestedEnumAuditActionWithAggregatesFilter<$PrismaModel> | $Enums.AuditAction + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumAuditActionFilter<$PrismaModel> + _max?: NestedEnumAuditActionFilter<$PrismaModel> + } + + export type EnumAuditSensitivityWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> + in?: $Enums.AuditSensitivity[] + notIn?: $Enums.AuditSensitivity[] + not?: NestedEnumAuditSensitivityWithAggregatesFilter<$PrismaModel> | $Enums.AuditSensitivity + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumAuditSensitivityFilter<$PrismaModel> + _max?: NestedEnumAuditSensitivityFilter<$PrismaModel> + } + + export type EnumConsentTypeFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentType | EnumConsentTypeFieldRefInput<$PrismaModel> + in?: $Enums.ConsentType[] + notIn?: $Enums.ConsentType[] + not?: NestedEnumConsentTypeFilter<$PrismaModel> | $Enums.ConsentType + } + + export type EnumConsentStatusFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentStatus | EnumConsentStatusFieldRefInput<$PrismaModel> + in?: $Enums.ConsentStatus[] + notIn?: $Enums.ConsentStatus[] + not?: NestedEnumConsentStatusFilter<$PrismaModel> | $Enums.ConsentStatus + } + + export type CustomerConsentCustomerIdConsentTypeCompoundUniqueInput = { + customerId: number + consentType: $Enums.ConsentType + } + + export type CustomerConsentCountOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + consentType?: SortOrder + status?: SortOrder + grantedAt?: SortOrder + withdrawnAt?: SortOrder + source?: SortOrder + documentPath?: SortOrder + version?: SortOrder + ipAddress?: SortOrder + createdBy?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type CustomerConsentAvgOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + } + + export type CustomerConsentMaxOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + consentType?: SortOrder + status?: SortOrder + grantedAt?: SortOrder + withdrawnAt?: SortOrder + source?: SortOrder + documentPath?: SortOrder + version?: SortOrder + ipAddress?: SortOrder + createdBy?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type CustomerConsentMinOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + consentType?: SortOrder + status?: SortOrder + grantedAt?: SortOrder + withdrawnAt?: SortOrder + source?: SortOrder + documentPath?: SortOrder + version?: SortOrder + ipAddress?: SortOrder + createdBy?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type CustomerConsentSumOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + } + + export type EnumConsentTypeWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentType | EnumConsentTypeFieldRefInput<$PrismaModel> + in?: $Enums.ConsentType[] + notIn?: $Enums.ConsentType[] + not?: NestedEnumConsentTypeWithAggregatesFilter<$PrismaModel> | $Enums.ConsentType + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumConsentTypeFilter<$PrismaModel> + _max?: NestedEnumConsentTypeFilter<$PrismaModel> + } + + export type EnumConsentStatusWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentStatus | EnumConsentStatusFieldRefInput<$PrismaModel> + in?: $Enums.ConsentStatus[] + notIn?: $Enums.ConsentStatus[] + not?: NestedEnumConsentStatusWithAggregatesFilter<$PrismaModel> | $Enums.ConsentStatus + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumConsentStatusFilter<$PrismaModel> + _max?: NestedEnumConsentStatusFilter<$PrismaModel> + } + + export type EnumDeletionRequestStatusFilter<$PrismaModel = never> = { + equals?: $Enums.DeletionRequestStatus | EnumDeletionRequestStatusFieldRefInput<$PrismaModel> + in?: $Enums.DeletionRequestStatus[] + notIn?: $Enums.DeletionRequestStatus[] + not?: NestedEnumDeletionRequestStatusFilter<$PrismaModel> | $Enums.DeletionRequestStatus + } + + export type DataDeletionRequestCountOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + status?: SortOrder + requestedAt?: SortOrder + requestSource?: SortOrder + requestedBy?: SortOrder + processedAt?: SortOrder + processedBy?: SortOrder + deletedData?: SortOrder + retainedData?: SortOrder + retentionReason?: SortOrder + proofDocument?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type DataDeletionRequestAvgOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + } + + export type DataDeletionRequestMaxOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + status?: SortOrder + requestedAt?: SortOrder + requestSource?: SortOrder + requestedBy?: SortOrder + processedAt?: SortOrder + processedBy?: SortOrder + deletedData?: SortOrder + retainedData?: SortOrder + retentionReason?: SortOrder + proofDocument?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type DataDeletionRequestMinOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + status?: SortOrder + requestedAt?: SortOrder + requestSource?: SortOrder + requestedBy?: SortOrder + processedAt?: SortOrder + processedBy?: SortOrder + deletedData?: SortOrder + retainedData?: SortOrder + retentionReason?: SortOrder + proofDocument?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type DataDeletionRequestSumOrderByAggregateInput = { + id?: SortOrder + customerId?: SortOrder + } + + export type EnumDeletionRequestStatusWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.DeletionRequestStatus | EnumDeletionRequestStatusFieldRefInput<$PrismaModel> + in?: $Enums.DeletionRequestStatus[] + notIn?: $Enums.DeletionRequestStatus[] + not?: NestedEnumDeletionRequestStatusWithAggregatesFilter<$PrismaModel> | $Enums.DeletionRequestStatus + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumDeletionRequestStatusFilter<$PrismaModel> + _max?: NestedEnumDeletionRequestStatusFilter<$PrismaModel> + } + + export type EnumAuditSensitivityNullableFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> | null + in?: $Enums.AuditSensitivity[] | null + notIn?: $Enums.AuditSensitivity[] | null + not?: NestedEnumAuditSensitivityNullableFilter<$PrismaModel> | $Enums.AuditSensitivity | null + } + + export type AuditRetentionPolicyResourceTypeSensitivityCompoundUniqueInput = { + resourceType: string + sensitivity: $Enums.AuditSensitivity + } + + export type AuditRetentionPolicyCountOrderByAggregateInput = { + id?: SortOrder + resourceType?: SortOrder + sensitivity?: SortOrder + retentionDays?: SortOrder + description?: SortOrder + legalBasis?: SortOrder + isActive?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type AuditRetentionPolicyAvgOrderByAggregateInput = { + id?: SortOrder + retentionDays?: SortOrder + } + + export type AuditRetentionPolicyMaxOrderByAggregateInput = { + id?: SortOrder + resourceType?: SortOrder + sensitivity?: SortOrder + retentionDays?: SortOrder + description?: SortOrder + legalBasis?: SortOrder + isActive?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type AuditRetentionPolicyMinOrderByAggregateInput = { + id?: SortOrder + resourceType?: SortOrder + sensitivity?: SortOrder + retentionDays?: SortOrder + description?: SortOrder + legalBasis?: SortOrder + isActive?: SortOrder + createdAt?: SortOrder + updatedAt?: SortOrder + } + + export type AuditRetentionPolicySumOrderByAggregateInput = { + id?: SortOrder + retentionDays?: SortOrder + } + + export type EnumAuditSensitivityNullableWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> | null + in?: $Enums.AuditSensitivity[] | null + notIn?: $Enums.AuditSensitivity[] | null + not?: NestedEnumAuditSensitivityNullableWithAggregatesFilter<$PrismaModel> | $Enums.AuditSensitivity | null + _count?: NestedIntNullableFilter<$PrismaModel> + _min?: NestedEnumAuditSensitivityNullableFilter<$PrismaModel> + _max?: NestedEnumAuditSensitivityNullableFilter<$PrismaModel> + } + export type StringFieldUpdateOperationsInput = { set?: string } - export type DateTimeFieldUpdateOperationsInput = { - set?: Date | string + export type NullableIntFieldUpdateOperationsInput = { + set?: number | null + increment?: number + decrement?: number + multiply?: number + divide?: number + } + + export type NullableStringFieldUpdateOperationsInput = { + set?: string | null } export type IntFieldUpdateOperationsInput = { @@ -48483,6 +57519,14 @@ export namespace Prisma { divide?: number } + export type BoolFieldUpdateOperationsInput = { + set?: boolean + } + + export type DateTimeFieldUpdateOperationsInput = { + set?: Date | string + } + export type CustomerCreateNestedOneWithoutUserInput = { create?: XOR connectOrCreate?: CustomerCreateOrConnectWithoutUserInput @@ -48503,10 +57547,6 @@ export namespace Prisma { connect?: UserRoleWhereUniqueInput | UserRoleWhereUniqueInput[] } - export type BoolFieldUpdateOperationsInput = { - set?: boolean - } - export type NullableDateTimeFieldUpdateOperationsInput = { set?: Date | string | null } @@ -48535,14 +57575,6 @@ export namespace Prisma { deleteMany?: UserRoleScalarWhereInput | UserRoleScalarWhereInput[] } - export type NullableIntFieldUpdateOperationsInput = { - set?: number | null - increment?: number - decrement?: number - multiply?: number - divide?: number - } - export type UserRoleUncheckedUpdateManyWithoutUserNestedInput = { create?: XOR | UserRoleCreateWithoutUserInput[] | UserRoleUncheckedCreateWithoutUserInput[] connectOrCreate?: UserRoleCreateOrConnectWithoutUserInput | UserRoleCreateOrConnectWithoutUserInput[] @@ -48585,10 +57617,6 @@ export namespace Prisma { connect?: UserRoleWhereUniqueInput | UserRoleWhereUniqueInput[] } - export type NullableStringFieldUpdateOperationsInput = { - set?: string | null - } - export type RolePermissionUpdateManyWithoutRoleNestedInput = { create?: XOR | RolePermissionCreateWithoutRoleInput[] | RolePermissionUncheckedCreateWithoutRoleInput[] connectOrCreate?: RolePermissionCreateOrConnectWithoutRoleInput | RolePermissionCreateOrConnectWithoutRoleInput[] @@ -48805,6 +57833,27 @@ export namespace Prisma { connect?: CustomerRepresentativeWhereUniqueInput | CustomerRepresentativeWhereUniqueInput[] } + export type RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutCustomerInput[] | RepresentativeAuthorizationUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput | RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput[] + createMany?: RepresentativeAuthorizationCreateManyCustomerInputEnvelope + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + } + + export type RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutRepresentativeInput[] | RepresentativeAuthorizationUncheckedCreateWithoutRepresentativeInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput | RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput[] + createMany?: RepresentativeAuthorizationCreateManyRepresentativeInputEnvelope + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + } + + export type CustomerConsentCreateNestedManyWithoutCustomerInput = { + create?: XOR | CustomerConsentCreateWithoutCustomerInput[] | CustomerConsentUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: CustomerConsentCreateOrConnectWithoutCustomerInput | CustomerConsentCreateOrConnectWithoutCustomerInput[] + createMany?: CustomerConsentCreateManyCustomerInputEnvelope + connect?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + } + export type UserUncheckedCreateNestedOneWithoutCustomerInput = { create?: XOR connectOrCreate?: UserCreateOrConnectWithoutCustomerInput @@ -48867,6 +57916,27 @@ export namespace Prisma { connect?: CustomerRepresentativeWhereUniqueInput | CustomerRepresentativeWhereUniqueInput[] } + export type RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutCustomerInput[] | RepresentativeAuthorizationUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput | RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput[] + createMany?: RepresentativeAuthorizationCreateManyCustomerInputEnvelope + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + } + + export type RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutRepresentativeInput[] | RepresentativeAuthorizationUncheckedCreateWithoutRepresentativeInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput | RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput[] + createMany?: RepresentativeAuthorizationCreateManyRepresentativeInputEnvelope + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + } + + export type CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput = { + create?: XOR | CustomerConsentCreateWithoutCustomerInput[] | CustomerConsentUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: CustomerConsentCreateOrConnectWithoutCustomerInput | CustomerConsentCreateOrConnectWithoutCustomerInput[] + createMany?: CustomerConsentCreateManyCustomerInputEnvelope + connect?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + } + export type EnumCustomerTypeFieldUpdateOperationsInput = { set?: $Enums.CustomerType } @@ -48993,6 +58063,48 @@ export namespace Prisma { deleteMany?: CustomerRepresentativeScalarWhereInput | CustomerRepresentativeScalarWhereInput[] } + export type RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutCustomerInput[] | RepresentativeAuthorizationUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput | RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput[] + upsert?: RepresentativeAuthorizationUpsertWithWhereUniqueWithoutCustomerInput | RepresentativeAuthorizationUpsertWithWhereUniqueWithoutCustomerInput[] + createMany?: RepresentativeAuthorizationCreateManyCustomerInputEnvelope + set?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + disconnect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + delete?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + update?: RepresentativeAuthorizationUpdateWithWhereUniqueWithoutCustomerInput | RepresentativeAuthorizationUpdateWithWhereUniqueWithoutCustomerInput[] + updateMany?: RepresentativeAuthorizationUpdateManyWithWhereWithoutCustomerInput | RepresentativeAuthorizationUpdateManyWithWhereWithoutCustomerInput[] + deleteMany?: RepresentativeAuthorizationScalarWhereInput | RepresentativeAuthorizationScalarWhereInput[] + } + + export type RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutRepresentativeInput[] | RepresentativeAuthorizationUncheckedCreateWithoutRepresentativeInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput | RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput[] + upsert?: RepresentativeAuthorizationUpsertWithWhereUniqueWithoutRepresentativeInput | RepresentativeAuthorizationUpsertWithWhereUniqueWithoutRepresentativeInput[] + createMany?: RepresentativeAuthorizationCreateManyRepresentativeInputEnvelope + set?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + disconnect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + delete?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + update?: RepresentativeAuthorizationUpdateWithWhereUniqueWithoutRepresentativeInput | RepresentativeAuthorizationUpdateWithWhereUniqueWithoutRepresentativeInput[] + updateMany?: RepresentativeAuthorizationUpdateManyWithWhereWithoutRepresentativeInput | RepresentativeAuthorizationUpdateManyWithWhereWithoutRepresentativeInput[] + deleteMany?: RepresentativeAuthorizationScalarWhereInput | RepresentativeAuthorizationScalarWhereInput[] + } + + export type CustomerConsentUpdateManyWithoutCustomerNestedInput = { + create?: XOR | CustomerConsentCreateWithoutCustomerInput[] | CustomerConsentUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: CustomerConsentCreateOrConnectWithoutCustomerInput | CustomerConsentCreateOrConnectWithoutCustomerInput[] + upsert?: CustomerConsentUpsertWithWhereUniqueWithoutCustomerInput | CustomerConsentUpsertWithWhereUniqueWithoutCustomerInput[] + createMany?: CustomerConsentCreateManyCustomerInputEnvelope + set?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + disconnect?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + delete?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + connect?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + update?: CustomerConsentUpdateWithWhereUniqueWithoutCustomerInput | CustomerConsentUpdateWithWhereUniqueWithoutCustomerInput[] + updateMany?: CustomerConsentUpdateManyWithWhereWithoutCustomerInput | CustomerConsentUpdateManyWithWhereWithoutCustomerInput[] + deleteMany?: CustomerConsentScalarWhereInput | CustomerConsentScalarWhereInput[] + } + export type UserUncheckedUpdateOneWithoutCustomerNestedInput = { create?: XOR connectOrCreate?: UserCreateOrConnectWithoutCustomerInput @@ -49115,6 +58227,48 @@ export namespace Prisma { deleteMany?: CustomerRepresentativeScalarWhereInput | CustomerRepresentativeScalarWhereInput[] } + export type RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutCustomerInput[] | RepresentativeAuthorizationUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput | RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput[] + upsert?: RepresentativeAuthorizationUpsertWithWhereUniqueWithoutCustomerInput | RepresentativeAuthorizationUpsertWithWhereUniqueWithoutCustomerInput[] + createMany?: RepresentativeAuthorizationCreateManyCustomerInputEnvelope + set?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + disconnect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + delete?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + update?: RepresentativeAuthorizationUpdateWithWhereUniqueWithoutCustomerInput | RepresentativeAuthorizationUpdateWithWhereUniqueWithoutCustomerInput[] + updateMany?: RepresentativeAuthorizationUpdateManyWithWhereWithoutCustomerInput | RepresentativeAuthorizationUpdateManyWithWhereWithoutCustomerInput[] + deleteMany?: RepresentativeAuthorizationScalarWhereInput | RepresentativeAuthorizationScalarWhereInput[] + } + + export type RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput = { + create?: XOR | RepresentativeAuthorizationCreateWithoutRepresentativeInput[] | RepresentativeAuthorizationUncheckedCreateWithoutRepresentativeInput[] + connectOrCreate?: RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput | RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput[] + upsert?: RepresentativeAuthorizationUpsertWithWhereUniqueWithoutRepresentativeInput | RepresentativeAuthorizationUpsertWithWhereUniqueWithoutRepresentativeInput[] + createMany?: RepresentativeAuthorizationCreateManyRepresentativeInputEnvelope + set?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + disconnect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + delete?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + connect?: RepresentativeAuthorizationWhereUniqueInput | RepresentativeAuthorizationWhereUniqueInput[] + update?: RepresentativeAuthorizationUpdateWithWhereUniqueWithoutRepresentativeInput | RepresentativeAuthorizationUpdateWithWhereUniqueWithoutRepresentativeInput[] + updateMany?: RepresentativeAuthorizationUpdateManyWithWhereWithoutRepresentativeInput | RepresentativeAuthorizationUpdateManyWithWhereWithoutRepresentativeInput[] + deleteMany?: RepresentativeAuthorizationScalarWhereInput | RepresentativeAuthorizationScalarWhereInput[] + } + + export type CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput = { + create?: XOR | CustomerConsentCreateWithoutCustomerInput[] | CustomerConsentUncheckedCreateWithoutCustomerInput[] + connectOrCreate?: CustomerConsentCreateOrConnectWithoutCustomerInput | CustomerConsentCreateOrConnectWithoutCustomerInput[] + upsert?: CustomerConsentUpsertWithWhereUniqueWithoutCustomerInput | CustomerConsentUpsertWithWhereUniqueWithoutCustomerInput[] + createMany?: CustomerConsentCreateManyCustomerInputEnvelope + set?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + disconnect?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + delete?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + connect?: CustomerConsentWhereUniqueInput | CustomerConsentWhereUniqueInput[] + update?: CustomerConsentUpdateWithWhereUniqueWithoutCustomerInput | CustomerConsentUpdateWithWhereUniqueWithoutCustomerInput[] + updateMany?: CustomerConsentUpdateManyWithWhereWithoutCustomerInput | CustomerConsentUpdateManyWithWhereWithoutCustomerInput[] + deleteMany?: CustomerConsentScalarWhereInput | CustomerConsentScalarWhereInput[] + } + export type CustomerCreateNestedOneWithoutRepresentedByInput = { create?: XOR connectOrCreate?: CustomerCreateOrConnectWithoutRepresentedByInput @@ -49143,6 +58297,34 @@ export namespace Prisma { update?: XOR, CustomerUncheckedUpdateWithoutRepresentingForInput> } + export type CustomerCreateNestedOneWithoutAuthorizationsGivenInput = { + create?: XOR + connectOrCreate?: CustomerCreateOrConnectWithoutAuthorizationsGivenInput + connect?: CustomerWhereUniqueInput + } + + export type CustomerCreateNestedOneWithoutAuthorizationsReceivedInput = { + create?: XOR + connectOrCreate?: CustomerCreateOrConnectWithoutAuthorizationsReceivedInput + connect?: CustomerWhereUniqueInput + } + + export type CustomerUpdateOneRequiredWithoutAuthorizationsGivenNestedInput = { + create?: XOR + connectOrCreate?: CustomerCreateOrConnectWithoutAuthorizationsGivenInput + upsert?: CustomerUpsertWithoutAuthorizationsGivenInput + connect?: CustomerWhereUniqueInput + update?: XOR, CustomerUncheckedUpdateWithoutAuthorizationsGivenInput> + } + + export type CustomerUpdateOneRequiredWithoutAuthorizationsReceivedNestedInput = { + create?: XOR + connectOrCreate?: CustomerCreateOrConnectWithoutAuthorizationsReceivedInput + upsert?: CustomerUpsertWithoutAuthorizationsReceivedInput + connect?: CustomerWhereUniqueInput + update?: XOR, CustomerUncheckedUpdateWithoutAuthorizationsReceivedInput> + } + export type CustomerCreateNestedOneWithoutAddressesInput = { create?: XOR connectOrCreate?: CustomerCreateOrConnectWithoutAddressesInput @@ -49617,6 +58799,10 @@ export namespace Prisma { divide?: number } + export type EnumMeterReadingStatusFieldUpdateOperationsInput = { + set?: $Enums.MeterReadingStatus + } + export type MeterUpdateOneRequiredWithoutReadingsNestedInput = { create?: XOR connectOrCreate?: MeterCreateOrConnectWithoutReadingsInput @@ -50881,6 +60067,44 @@ export namespace Prisma { update?: XOR, ContractUncheckedUpdateWithoutCarInsuranceDetailsInput> } + export type EnumAuditActionFieldUpdateOperationsInput = { + set?: $Enums.AuditAction + } + + export type EnumAuditSensitivityFieldUpdateOperationsInput = { + set?: $Enums.AuditSensitivity + } + + export type CustomerCreateNestedOneWithoutConsentsInput = { + create?: XOR + connectOrCreate?: CustomerCreateOrConnectWithoutConsentsInput + connect?: CustomerWhereUniqueInput + } + + export type EnumConsentTypeFieldUpdateOperationsInput = { + set?: $Enums.ConsentType + } + + export type EnumConsentStatusFieldUpdateOperationsInput = { + set?: $Enums.ConsentStatus + } + + export type CustomerUpdateOneRequiredWithoutConsentsNestedInput = { + create?: XOR + connectOrCreate?: CustomerCreateOrConnectWithoutConsentsInput + upsert?: CustomerUpsertWithoutConsentsInput + connect?: CustomerWhereUniqueInput + update?: XOR, CustomerUncheckedUpdateWithoutConsentsInput> + } + + export type EnumDeletionRequestStatusFieldUpdateOperationsInput = { + set?: $Enums.DeletionRequestStatus + } + + export type NullableEnumAuditSensitivityFieldUpdateOperationsInput = { + set?: $Enums.AuditSensitivity | null + } + export type NestedIntFilter<$PrismaModel = never> = { equals?: number | IntFieldRefInput<$PrismaModel> in?: number[] @@ -50906,6 +60130,36 @@ export namespace Prisma { not?: NestedStringFilter<$PrismaModel> | string } + export type NestedIntNullableFilter<$PrismaModel = never> = { + equals?: number | IntFieldRefInput<$PrismaModel> | null + in?: number[] | null + notIn?: number[] | null + lt?: number | IntFieldRefInput<$PrismaModel> + lte?: number | IntFieldRefInput<$PrismaModel> + gt?: number | IntFieldRefInput<$PrismaModel> + gte?: number | IntFieldRefInput<$PrismaModel> + not?: NestedIntNullableFilter<$PrismaModel> | number | null + } + + export type NestedStringNullableFilter<$PrismaModel = never> = { + equals?: string | StringFieldRefInput<$PrismaModel> | null + in?: string[] | null + notIn?: string[] | null + lt?: string | StringFieldRefInput<$PrismaModel> + lte?: string | StringFieldRefInput<$PrismaModel> + gt?: string | StringFieldRefInput<$PrismaModel> + gte?: string | StringFieldRefInput<$PrismaModel> + contains?: string | StringFieldRefInput<$PrismaModel> + startsWith?: string | StringFieldRefInput<$PrismaModel> + endsWith?: string | StringFieldRefInput<$PrismaModel> + not?: NestedStringNullableFilter<$PrismaModel> | string | null + } + + export type NestedBoolFilter<$PrismaModel = never> = { + equals?: boolean | BooleanFieldRefInput<$PrismaModel> + not?: NestedBoolFilter<$PrismaModel> | boolean + } + export type NestedDateTimeFilter<$PrismaModel = never> = { equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> in?: Date[] | string[] @@ -50961,69 +60215,6 @@ export namespace Prisma { _max?: NestedStringFilter<$PrismaModel> } - export type NestedDateTimeWithAggregatesFilter<$PrismaModel = never> = { - equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> - in?: Date[] | string[] - notIn?: Date[] | string[] - lt?: Date | string | DateTimeFieldRefInput<$PrismaModel> - lte?: Date | string | DateTimeFieldRefInput<$PrismaModel> - gt?: Date | string | DateTimeFieldRefInput<$PrismaModel> - gte?: Date | string | DateTimeFieldRefInput<$PrismaModel> - not?: NestedDateTimeWithAggregatesFilter<$PrismaModel> | Date | string - _count?: NestedIntFilter<$PrismaModel> - _min?: NestedDateTimeFilter<$PrismaModel> - _max?: NestedDateTimeFilter<$PrismaModel> - } - - export type NestedBoolFilter<$PrismaModel = never> = { - equals?: boolean | BooleanFieldRefInput<$PrismaModel> - not?: NestedBoolFilter<$PrismaModel> | boolean - } - - export type NestedDateTimeNullableFilter<$PrismaModel = never> = { - equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> | null - in?: Date[] | string[] | null - notIn?: Date[] | string[] | null - lt?: Date | string | DateTimeFieldRefInput<$PrismaModel> - lte?: Date | string | DateTimeFieldRefInput<$PrismaModel> - gt?: Date | string | DateTimeFieldRefInput<$PrismaModel> - gte?: Date | string | DateTimeFieldRefInput<$PrismaModel> - not?: NestedDateTimeNullableFilter<$PrismaModel> | Date | string | null - } - - export type NestedIntNullableFilter<$PrismaModel = never> = { - equals?: number | IntFieldRefInput<$PrismaModel> | null - in?: number[] | null - notIn?: number[] | null - lt?: number | IntFieldRefInput<$PrismaModel> - lte?: number | IntFieldRefInput<$PrismaModel> - gt?: number | IntFieldRefInput<$PrismaModel> - gte?: number | IntFieldRefInput<$PrismaModel> - not?: NestedIntNullableFilter<$PrismaModel> | number | null - } - - export type NestedBoolWithAggregatesFilter<$PrismaModel = never> = { - equals?: boolean | BooleanFieldRefInput<$PrismaModel> - not?: NestedBoolWithAggregatesFilter<$PrismaModel> | boolean - _count?: NestedIntFilter<$PrismaModel> - _min?: NestedBoolFilter<$PrismaModel> - _max?: NestedBoolFilter<$PrismaModel> - } - - export type NestedDateTimeNullableWithAggregatesFilter<$PrismaModel = never> = { - equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> | null - in?: Date[] | string[] | null - notIn?: Date[] | string[] | null - lt?: Date | string | DateTimeFieldRefInput<$PrismaModel> - lte?: Date | string | DateTimeFieldRefInput<$PrismaModel> - gt?: Date | string | DateTimeFieldRefInput<$PrismaModel> - gte?: Date | string | DateTimeFieldRefInput<$PrismaModel> - not?: NestedDateTimeNullableWithAggregatesFilter<$PrismaModel> | Date | string | null - _count?: NestedIntNullableFilter<$PrismaModel> - _min?: NestedDateTimeNullableFilter<$PrismaModel> - _max?: NestedDateTimeNullableFilter<$PrismaModel> - } - export type NestedIntNullableWithAggregatesFilter<$PrismaModel = never> = { equals?: number | IntFieldRefInput<$PrismaModel> | null in?: number[] | null @@ -51051,20 +60242,6 @@ export namespace Prisma { not?: NestedFloatNullableFilter<$PrismaModel> | number | null } - export type NestedStringNullableFilter<$PrismaModel = never> = { - equals?: string | StringFieldRefInput<$PrismaModel> | null - in?: string[] | null - notIn?: string[] | null - lt?: string | StringFieldRefInput<$PrismaModel> - lte?: string | StringFieldRefInput<$PrismaModel> - gt?: string | StringFieldRefInput<$PrismaModel> - gte?: string | StringFieldRefInput<$PrismaModel> - contains?: string | StringFieldRefInput<$PrismaModel> - startsWith?: string | StringFieldRefInput<$PrismaModel> - endsWith?: string | StringFieldRefInput<$PrismaModel> - not?: NestedStringNullableFilter<$PrismaModel> | string | null - } - export type NestedStringNullableWithAggregatesFilter<$PrismaModel = never> = { equals?: string | StringFieldRefInput<$PrismaModel> | null in?: string[] | null @@ -51082,6 +60259,53 @@ export namespace Prisma { _max?: NestedStringNullableFilter<$PrismaModel> } + export type NestedBoolWithAggregatesFilter<$PrismaModel = never> = { + equals?: boolean | BooleanFieldRefInput<$PrismaModel> + not?: NestedBoolWithAggregatesFilter<$PrismaModel> | boolean + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedBoolFilter<$PrismaModel> + _max?: NestedBoolFilter<$PrismaModel> + } + + export type NestedDateTimeWithAggregatesFilter<$PrismaModel = never> = { + equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> + in?: Date[] | string[] + notIn?: Date[] | string[] + lt?: Date | string | DateTimeFieldRefInput<$PrismaModel> + lte?: Date | string | DateTimeFieldRefInput<$PrismaModel> + gt?: Date | string | DateTimeFieldRefInput<$PrismaModel> + gte?: Date | string | DateTimeFieldRefInput<$PrismaModel> + not?: NestedDateTimeWithAggregatesFilter<$PrismaModel> | Date | string + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedDateTimeFilter<$PrismaModel> + _max?: NestedDateTimeFilter<$PrismaModel> + } + + export type NestedDateTimeNullableFilter<$PrismaModel = never> = { + equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> | null + in?: Date[] | string[] | null + notIn?: Date[] | string[] | null + lt?: Date | string | DateTimeFieldRefInput<$PrismaModel> + lte?: Date | string | DateTimeFieldRefInput<$PrismaModel> + gt?: Date | string | DateTimeFieldRefInput<$PrismaModel> + gte?: Date | string | DateTimeFieldRefInput<$PrismaModel> + not?: NestedDateTimeNullableFilter<$PrismaModel> | Date | string | null + } + + export type NestedDateTimeNullableWithAggregatesFilter<$PrismaModel = never> = { + equals?: Date | string | DateTimeFieldRefInput<$PrismaModel> | null + in?: Date[] | string[] | null + notIn?: Date[] | string[] | null + lt?: Date | string | DateTimeFieldRefInput<$PrismaModel> + lte?: Date | string | DateTimeFieldRefInput<$PrismaModel> + gt?: Date | string | DateTimeFieldRefInput<$PrismaModel> + gte?: Date | string | DateTimeFieldRefInput<$PrismaModel> + not?: NestedDateTimeNullableWithAggregatesFilter<$PrismaModel> | Date | string | null + _count?: NestedIntNullableFilter<$PrismaModel> + _min?: NestedDateTimeNullableFilter<$PrismaModel> + _max?: NestedDateTimeNullableFilter<$PrismaModel> + } + export type NestedEnumCustomerTypeFilter<$PrismaModel = never> = { equals?: $Enums.CustomerType | EnumCustomerTypeFieldRefInput<$PrismaModel> in?: $Enums.CustomerType[] @@ -51201,6 +60425,13 @@ export namespace Prisma { _max?: NestedEnumMeterTypeFilter<$PrismaModel> } + export type NestedEnumMeterReadingStatusFilter<$PrismaModel = never> = { + equals?: $Enums.MeterReadingStatus | EnumMeterReadingStatusFieldRefInput<$PrismaModel> + in?: $Enums.MeterReadingStatus[] + notIn?: $Enums.MeterReadingStatus[] + not?: NestedEnumMeterReadingStatusFilter<$PrismaModel> | $Enums.MeterReadingStatus + } + export type NestedFloatWithAggregatesFilter<$PrismaModel = never> = { equals?: number | FloatFieldRefInput<$PrismaModel> in?: number[] @@ -51217,6 +60448,16 @@ export namespace Prisma { _max?: NestedFloatFilter<$PrismaModel> } + export type NestedEnumMeterReadingStatusWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.MeterReadingStatus | EnumMeterReadingStatusFieldRefInput<$PrismaModel> + in?: $Enums.MeterReadingStatus[] + notIn?: $Enums.MeterReadingStatus[] + not?: NestedEnumMeterReadingStatusWithAggregatesFilter<$PrismaModel> | $Enums.MeterReadingStatus + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumMeterReadingStatusFilter<$PrismaModel> + _max?: NestedEnumMeterReadingStatusFilter<$PrismaModel> + } + export type NestedEnumContractTypeFilter<$PrismaModel = never> = { equals?: $Enums.ContractType | EnumContractTypeFieldRefInput<$PrismaModel> in?: $Enums.ContractType[] @@ -51318,6 +60559,108 @@ export namespace Prisma { _max?: NestedEnumInsuranceTypeFilter<$PrismaModel> } + export type NestedEnumAuditActionFilter<$PrismaModel = never> = { + equals?: $Enums.AuditAction | EnumAuditActionFieldRefInput<$PrismaModel> + in?: $Enums.AuditAction[] + notIn?: $Enums.AuditAction[] + not?: NestedEnumAuditActionFilter<$PrismaModel> | $Enums.AuditAction + } + + export type NestedEnumAuditSensitivityFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> + in?: $Enums.AuditSensitivity[] + notIn?: $Enums.AuditSensitivity[] + not?: NestedEnumAuditSensitivityFilter<$PrismaModel> | $Enums.AuditSensitivity + } + + export type NestedEnumAuditActionWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.AuditAction | EnumAuditActionFieldRefInput<$PrismaModel> + in?: $Enums.AuditAction[] + notIn?: $Enums.AuditAction[] + not?: NestedEnumAuditActionWithAggregatesFilter<$PrismaModel> | $Enums.AuditAction + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumAuditActionFilter<$PrismaModel> + _max?: NestedEnumAuditActionFilter<$PrismaModel> + } + + export type NestedEnumAuditSensitivityWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> + in?: $Enums.AuditSensitivity[] + notIn?: $Enums.AuditSensitivity[] + not?: NestedEnumAuditSensitivityWithAggregatesFilter<$PrismaModel> | $Enums.AuditSensitivity + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumAuditSensitivityFilter<$PrismaModel> + _max?: NestedEnumAuditSensitivityFilter<$PrismaModel> + } + + export type NestedEnumConsentTypeFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentType | EnumConsentTypeFieldRefInput<$PrismaModel> + in?: $Enums.ConsentType[] + notIn?: $Enums.ConsentType[] + not?: NestedEnumConsentTypeFilter<$PrismaModel> | $Enums.ConsentType + } + + export type NestedEnumConsentStatusFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentStatus | EnumConsentStatusFieldRefInput<$PrismaModel> + in?: $Enums.ConsentStatus[] + notIn?: $Enums.ConsentStatus[] + not?: NestedEnumConsentStatusFilter<$PrismaModel> | $Enums.ConsentStatus + } + + export type NestedEnumConsentTypeWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentType | EnumConsentTypeFieldRefInput<$PrismaModel> + in?: $Enums.ConsentType[] + notIn?: $Enums.ConsentType[] + not?: NestedEnumConsentTypeWithAggregatesFilter<$PrismaModel> | $Enums.ConsentType + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumConsentTypeFilter<$PrismaModel> + _max?: NestedEnumConsentTypeFilter<$PrismaModel> + } + + export type NestedEnumConsentStatusWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.ConsentStatus | EnumConsentStatusFieldRefInput<$PrismaModel> + in?: $Enums.ConsentStatus[] + notIn?: $Enums.ConsentStatus[] + not?: NestedEnumConsentStatusWithAggregatesFilter<$PrismaModel> | $Enums.ConsentStatus + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumConsentStatusFilter<$PrismaModel> + _max?: NestedEnumConsentStatusFilter<$PrismaModel> + } + + export type NestedEnumDeletionRequestStatusFilter<$PrismaModel = never> = { + equals?: $Enums.DeletionRequestStatus | EnumDeletionRequestStatusFieldRefInput<$PrismaModel> + in?: $Enums.DeletionRequestStatus[] + notIn?: $Enums.DeletionRequestStatus[] + not?: NestedEnumDeletionRequestStatusFilter<$PrismaModel> | $Enums.DeletionRequestStatus + } + + export type NestedEnumDeletionRequestStatusWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.DeletionRequestStatus | EnumDeletionRequestStatusFieldRefInput<$PrismaModel> + in?: $Enums.DeletionRequestStatus[] + notIn?: $Enums.DeletionRequestStatus[] + not?: NestedEnumDeletionRequestStatusWithAggregatesFilter<$PrismaModel> | $Enums.DeletionRequestStatus + _count?: NestedIntFilter<$PrismaModel> + _min?: NestedEnumDeletionRequestStatusFilter<$PrismaModel> + _max?: NestedEnumDeletionRequestStatusFilter<$PrismaModel> + } + + export type NestedEnumAuditSensitivityNullableFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> | null + in?: $Enums.AuditSensitivity[] | null + notIn?: $Enums.AuditSensitivity[] | null + not?: NestedEnumAuditSensitivityNullableFilter<$PrismaModel> | $Enums.AuditSensitivity | null + } + + export type NestedEnumAuditSensitivityNullableWithAggregatesFilter<$PrismaModel = never> = { + equals?: $Enums.AuditSensitivity | EnumAuditSensitivityFieldRefInput<$PrismaModel> | null + in?: $Enums.AuditSensitivity[] | null + notIn?: $Enums.AuditSensitivity[] | null + not?: NestedEnumAuditSensitivityNullableWithAggregatesFilter<$PrismaModel> | $Enums.AuditSensitivity | null + _count?: NestedIntNullableFilter<$PrismaModel> + _min?: NestedEnumAuditSensitivityNullableFilter<$PrismaModel> + _max?: NestedEnumAuditSensitivityNullableFilter<$PrismaModel> + } + export type CustomerCreateWithoutUserInput = { customerNumber: string type?: $Enums.CustomerType @@ -51336,6 +60679,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -51352,6 +60696,9 @@ export namespace Prisma { contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutUserInput = { @@ -51373,6 +60720,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -51389,6 +60737,9 @@ export namespace Prisma { contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutUserInput = { @@ -51443,6 +60794,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -51459,6 +60811,9 @@ export namespace Prisma { contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutUserInput = { @@ -51480,6 +60835,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -51496,6 +60852,9 @@ export namespace Prisma { contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type UserRoleUpsertWithWhereUniqueWithoutUserInput = { @@ -51727,6 +61086,9 @@ export namespace Prisma { lastName: string isActive?: boolean tokenInvalidatedAt?: Date | string | null + whatsappNumber?: string | null + telegramUsername?: string | null + signalNumber?: string | null createdAt?: Date | string updatedAt?: Date | string customer?: CustomerCreateNestedOneWithoutUserInput @@ -51740,6 +61102,9 @@ export namespace Prisma { lastName: string isActive?: boolean tokenInvalidatedAt?: Date | string | null + whatsappNumber?: string | null + telegramUsername?: string | null + signalNumber?: string | null customerId?: number | null createdAt?: Date | string updatedAt?: Date | string @@ -51790,6 +61155,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string customer?: CustomerUpdateOneWithoutUserNestedInput @@ -51803,6 +61171,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null customerId?: NullableIntFieldUpdateOperationsInput | number | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string @@ -51843,6 +61214,9 @@ export namespace Prisma { lastName: string isActive?: boolean tokenInvalidatedAt?: Date | string | null + whatsappNumber?: string | null + telegramUsername?: string | null + signalNumber?: string | null createdAt?: Date | string updatedAt?: Date | string roles?: UserRoleCreateNestedManyWithoutUserInput @@ -51856,6 +61230,9 @@ export namespace Prisma { lastName: string isActive?: boolean tokenInvalidatedAt?: Date | string | null + whatsappNumber?: string | null + telegramUsername?: string | null + signalNumber?: string | null createdAt?: Date | string updatedAt?: Date | string roles?: UserRoleUncheckedCreateNestedManyWithoutUserInput @@ -52230,6 +61607,115 @@ export namespace Prisma { skipDuplicates?: boolean } + export type RepresentativeAuthorizationCreateWithoutCustomerInput = { + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + representative: CustomerCreateNestedOneWithoutAuthorizationsReceivedInput + } + + export type RepresentativeAuthorizationUncheckedCreateWithoutCustomerInput = { + id?: number + representativeId: number + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type RepresentativeAuthorizationCreateOrConnectWithoutCustomerInput = { + where: RepresentativeAuthorizationWhereUniqueInput + create: XOR + } + + export type RepresentativeAuthorizationCreateManyCustomerInputEnvelope = { + data: RepresentativeAuthorizationCreateManyCustomerInput | RepresentativeAuthorizationCreateManyCustomerInput[] + skipDuplicates?: boolean + } + + export type RepresentativeAuthorizationCreateWithoutRepresentativeInput = { + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + customer: CustomerCreateNestedOneWithoutAuthorizationsGivenInput + } + + export type RepresentativeAuthorizationUncheckedCreateWithoutRepresentativeInput = { + id?: number + customerId: number + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type RepresentativeAuthorizationCreateOrConnectWithoutRepresentativeInput = { + where: RepresentativeAuthorizationWhereUniqueInput + create: XOR + } + + export type RepresentativeAuthorizationCreateManyRepresentativeInputEnvelope = { + data: RepresentativeAuthorizationCreateManyRepresentativeInput | RepresentativeAuthorizationCreateManyRepresentativeInput[] + skipDuplicates?: boolean + } + + export type CustomerConsentCreateWithoutCustomerInput = { + consentType: $Enums.ConsentType + status?: $Enums.ConsentStatus + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + version?: string | null + ipAddress?: string | null + createdBy: string + createdAt?: Date | string + updatedAt?: Date | string + } + + export type CustomerConsentUncheckedCreateWithoutCustomerInput = { + id?: number + consentType: $Enums.ConsentType + status?: $Enums.ConsentStatus + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + version?: string | null + ipAddress?: string | null + createdBy: string + createdAt?: Date | string + updatedAt?: Date | string + } + + export type CustomerConsentCreateOrConnectWithoutCustomerInput = { + where: CustomerConsentWhereUniqueInput + create: XOR + } + + export type CustomerConsentCreateManyCustomerInputEnvelope = { + data: CustomerConsentCreateManyCustomerInput | CustomerConsentCreateManyCustomerInput[] + skipDuplicates?: boolean + } + export type UserUpsertWithoutCustomerInput = { update: XOR create: XOR @@ -52248,6 +61734,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string roles?: UserRoleUpdateManyWithoutUserNestedInput @@ -52261,6 +61750,9 @@ export namespace Prisma { lastName?: StringFieldUpdateOperationsInput | string isActive?: BoolFieldUpdateOperationsInput | boolean tokenInvalidatedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + whatsappNumber?: NullableStringFieldUpdateOperationsInput | string | null + telegramUsername?: NullableStringFieldUpdateOperationsInput | string | null + signalNumber?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string roles?: UserRoleUncheckedUpdateManyWithoutUserNestedInput @@ -52542,6 +62034,90 @@ export namespace Prisma { data: XOR } + export type RepresentativeAuthorizationUpsertWithWhereUniqueWithoutCustomerInput = { + where: RepresentativeAuthorizationWhereUniqueInput + update: XOR + create: XOR + } + + export type RepresentativeAuthorizationUpdateWithWhereUniqueWithoutCustomerInput = { + where: RepresentativeAuthorizationWhereUniqueInput + data: XOR + } + + export type RepresentativeAuthorizationUpdateManyWithWhereWithoutCustomerInput = { + where: RepresentativeAuthorizationScalarWhereInput + data: XOR + } + + export type RepresentativeAuthorizationScalarWhereInput = { + AND?: RepresentativeAuthorizationScalarWhereInput | RepresentativeAuthorizationScalarWhereInput[] + OR?: RepresentativeAuthorizationScalarWhereInput[] + NOT?: RepresentativeAuthorizationScalarWhereInput | RepresentativeAuthorizationScalarWhereInput[] + id?: IntFilter<"RepresentativeAuthorization"> | number + customerId?: IntFilter<"RepresentativeAuthorization"> | number + representativeId?: IntFilter<"RepresentativeAuthorization"> | number + isGranted?: BoolFilter<"RepresentativeAuthorization"> | boolean + grantedAt?: DateTimeNullableFilter<"RepresentativeAuthorization"> | Date | string | null + withdrawnAt?: DateTimeNullableFilter<"RepresentativeAuthorization"> | Date | string | null + source?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + documentPath?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + notes?: StringNullableFilter<"RepresentativeAuthorization"> | string | null + createdAt?: DateTimeFilter<"RepresentativeAuthorization"> | Date | string + updatedAt?: DateTimeFilter<"RepresentativeAuthorization"> | Date | string + } + + export type RepresentativeAuthorizationUpsertWithWhereUniqueWithoutRepresentativeInput = { + where: RepresentativeAuthorizationWhereUniqueInput + update: XOR + create: XOR + } + + export type RepresentativeAuthorizationUpdateWithWhereUniqueWithoutRepresentativeInput = { + where: RepresentativeAuthorizationWhereUniqueInput + data: XOR + } + + export type RepresentativeAuthorizationUpdateManyWithWhereWithoutRepresentativeInput = { + where: RepresentativeAuthorizationScalarWhereInput + data: XOR + } + + export type CustomerConsentUpsertWithWhereUniqueWithoutCustomerInput = { + where: CustomerConsentWhereUniqueInput + update: XOR + create: XOR + } + + export type CustomerConsentUpdateWithWhereUniqueWithoutCustomerInput = { + where: CustomerConsentWhereUniqueInput + data: XOR + } + + export type CustomerConsentUpdateManyWithWhereWithoutCustomerInput = { + where: CustomerConsentScalarWhereInput + data: XOR + } + + export type CustomerConsentScalarWhereInput = { + AND?: CustomerConsentScalarWhereInput | CustomerConsentScalarWhereInput[] + OR?: CustomerConsentScalarWhereInput[] + NOT?: CustomerConsentScalarWhereInput | CustomerConsentScalarWhereInput[] + id?: IntFilter<"CustomerConsent"> | number + customerId?: IntFilter<"CustomerConsent"> | number + consentType?: EnumConsentTypeFilter<"CustomerConsent"> | $Enums.ConsentType + status?: EnumConsentStatusFilter<"CustomerConsent"> | $Enums.ConsentStatus + grantedAt?: DateTimeNullableFilter<"CustomerConsent"> | Date | string | null + withdrawnAt?: DateTimeNullableFilter<"CustomerConsent"> | Date | string | null + source?: StringNullableFilter<"CustomerConsent"> | string | null + documentPath?: StringNullableFilter<"CustomerConsent"> | string | null + version?: StringNullableFilter<"CustomerConsent"> | string | null + ipAddress?: StringNullableFilter<"CustomerConsent"> | string | null + createdBy?: StringFilter<"CustomerConsent"> | string + createdAt?: DateTimeFilter<"CustomerConsent"> | Date | string + updatedAt?: DateTimeFilter<"CustomerConsent"> | Date | string + } + export type CustomerCreateWithoutRepresentedByInput = { customerNumber: string type?: $Enums.CustomerType @@ -52560,6 +62136,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -52576,6 +62153,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailCreateNestedManyWithoutCustomerInput contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutRepresentedByInput = { @@ -52597,6 +62177,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -52613,6 +62194,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUncheckedCreateNestedManyWithoutCustomerInput contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutRepresentedByInput = { @@ -52638,6 +62222,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -52654,6 +62239,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailCreateNestedManyWithoutCustomerInput contracts?: ContractCreateNestedManyWithoutCustomerInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutRepresentingForInput = { @@ -52675,6 +62263,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -52691,6 +62280,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUncheckedCreateNestedManyWithoutCustomerInput contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutRepresentingForInput = { @@ -52727,6 +62319,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -52743,6 +62336,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUpdateManyWithoutCustomerNestedInput contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutRepresentedByInput = { @@ -52764,6 +62360,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -52780,6 +62377,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUncheckedUpdateManyWithoutCustomerNestedInput contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type CustomerUpsertWithoutRepresentingForInput = { @@ -52811,6 +62411,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -52827,6 +62428,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUpdateManyWithoutCustomerNestedInput contracts?: ContractUpdateManyWithoutCustomerNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutRepresentingForInput = { @@ -52848,6 +62452,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -52864,6 +62469,365 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUncheckedUpdateManyWithoutCustomerNestedInput contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput + } + + export type CustomerCreateWithoutAuthorizationsGivenInput = { + customerNumber: string + type?: $Enums.CustomerType + salutation?: string | null + firstName: string + lastName: string + companyName?: string | null + foundingDate?: Date | string | null + birthDate?: Date | string | null + birthPlace?: string | null + email?: string | null + phone?: string | null + mobile?: string | null + taxNumber?: string | null + businessRegistrationPath?: string | null + commercialRegisterPath?: string | null + commercialRegisterNumber?: string | null + privacyPolicyPath?: string | null + consentHash?: string | null + notes?: string | null + portalEnabled?: boolean + portalEmail?: string | null + portalPasswordHash?: string | null + portalPasswordEncrypted?: string | null + portalLastLogin?: Date | string | null + createdAt?: Date | string + updatedAt?: Date | string + user?: UserCreateNestedOneWithoutCustomerInput + addresses?: AddressCreateNestedManyWithoutCustomerInput + bankCards?: BankCardCreateNestedManyWithoutCustomerInput + identityDocuments?: IdentityDocumentCreateNestedManyWithoutCustomerInput + meters?: MeterCreateNestedManyWithoutCustomerInput + stressfreiEmails?: StressfreiEmailCreateNestedManyWithoutCustomerInput + contracts?: ContractCreateNestedManyWithoutCustomerInput + representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput + representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput + } + + export type CustomerUncheckedCreateWithoutAuthorizationsGivenInput = { + id?: number + customerNumber: string + type?: $Enums.CustomerType + salutation?: string | null + firstName: string + lastName: string + companyName?: string | null + foundingDate?: Date | string | null + birthDate?: Date | string | null + birthPlace?: string | null + email?: string | null + phone?: string | null + mobile?: string | null + taxNumber?: string | null + businessRegistrationPath?: string | null + commercialRegisterPath?: string | null + commercialRegisterNumber?: string | null + privacyPolicyPath?: string | null + consentHash?: string | null + notes?: string | null + portalEnabled?: boolean + portalEmail?: string | null + portalPasswordHash?: string | null + portalPasswordEncrypted?: string | null + portalLastLogin?: Date | string | null + createdAt?: Date | string + updatedAt?: Date | string + user?: UserUncheckedCreateNestedOneWithoutCustomerInput + addresses?: AddressUncheckedCreateNestedManyWithoutCustomerInput + bankCards?: BankCardUncheckedCreateNestedManyWithoutCustomerInput + identityDocuments?: IdentityDocumentUncheckedCreateNestedManyWithoutCustomerInput + meters?: MeterUncheckedCreateNestedManyWithoutCustomerInput + stressfreiEmails?: StressfreiEmailUncheckedCreateNestedManyWithoutCustomerInput + contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput + representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput + representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput + } + + export type CustomerCreateOrConnectWithoutAuthorizationsGivenInput = { + where: CustomerWhereUniqueInput + create: XOR + } + + export type CustomerCreateWithoutAuthorizationsReceivedInput = { + customerNumber: string + type?: $Enums.CustomerType + salutation?: string | null + firstName: string + lastName: string + companyName?: string | null + foundingDate?: Date | string | null + birthDate?: Date | string | null + birthPlace?: string | null + email?: string | null + phone?: string | null + mobile?: string | null + taxNumber?: string | null + businessRegistrationPath?: string | null + commercialRegisterPath?: string | null + commercialRegisterNumber?: string | null + privacyPolicyPath?: string | null + consentHash?: string | null + notes?: string | null + portalEnabled?: boolean + portalEmail?: string | null + portalPasswordHash?: string | null + portalPasswordEncrypted?: string | null + portalLastLogin?: Date | string | null + createdAt?: Date | string + updatedAt?: Date | string + user?: UserCreateNestedOneWithoutCustomerInput + addresses?: AddressCreateNestedManyWithoutCustomerInput + bankCards?: BankCardCreateNestedManyWithoutCustomerInput + identityDocuments?: IdentityDocumentCreateNestedManyWithoutCustomerInput + meters?: MeterCreateNestedManyWithoutCustomerInput + stressfreiEmails?: StressfreiEmailCreateNestedManyWithoutCustomerInput + contracts?: ContractCreateNestedManyWithoutCustomerInput + representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput + representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput + } + + export type CustomerUncheckedCreateWithoutAuthorizationsReceivedInput = { + id?: number + customerNumber: string + type?: $Enums.CustomerType + salutation?: string | null + firstName: string + lastName: string + companyName?: string | null + foundingDate?: Date | string | null + birthDate?: Date | string | null + birthPlace?: string | null + email?: string | null + phone?: string | null + mobile?: string | null + taxNumber?: string | null + businessRegistrationPath?: string | null + commercialRegisterPath?: string | null + commercialRegisterNumber?: string | null + privacyPolicyPath?: string | null + consentHash?: string | null + notes?: string | null + portalEnabled?: boolean + portalEmail?: string | null + portalPasswordHash?: string | null + portalPasswordEncrypted?: string | null + portalLastLogin?: Date | string | null + createdAt?: Date | string + updatedAt?: Date | string + user?: UserUncheckedCreateNestedOneWithoutCustomerInput + addresses?: AddressUncheckedCreateNestedManyWithoutCustomerInput + bankCards?: BankCardUncheckedCreateNestedManyWithoutCustomerInput + identityDocuments?: IdentityDocumentUncheckedCreateNestedManyWithoutCustomerInput + meters?: MeterUncheckedCreateNestedManyWithoutCustomerInput + stressfreiEmails?: StressfreiEmailUncheckedCreateNestedManyWithoutCustomerInput + contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput + representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput + representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput + } + + export type CustomerCreateOrConnectWithoutAuthorizationsReceivedInput = { + where: CustomerWhereUniqueInput + create: XOR + } + + export type CustomerUpsertWithoutAuthorizationsGivenInput = { + update: XOR + create: XOR + where?: CustomerWhereInput + } + + export type CustomerUpdateToOneWithWhereWithoutAuthorizationsGivenInput = { + where?: CustomerWhereInput + data: XOR + } + + export type CustomerUpdateWithoutAuthorizationsGivenInput = { + customerNumber?: StringFieldUpdateOperationsInput | string + type?: EnumCustomerTypeFieldUpdateOperationsInput | $Enums.CustomerType + salutation?: NullableStringFieldUpdateOperationsInput | string | null + firstName?: StringFieldUpdateOperationsInput | string + lastName?: StringFieldUpdateOperationsInput | string + companyName?: NullableStringFieldUpdateOperationsInput | string | null + foundingDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthPlace?: NullableStringFieldUpdateOperationsInput | string | null + email?: NullableStringFieldUpdateOperationsInput | string | null + phone?: NullableStringFieldUpdateOperationsInput | string | null + mobile?: NullableStringFieldUpdateOperationsInput | string | null + taxNumber?: NullableStringFieldUpdateOperationsInput | string | null + businessRegistrationPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null + privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + portalEnabled?: BoolFieldUpdateOperationsInput | boolean + portalEmail?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordHash?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null + portalLastLogin?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + user?: UserUpdateOneWithoutCustomerNestedInput + addresses?: AddressUpdateManyWithoutCustomerNestedInput + bankCards?: BankCardUpdateManyWithoutCustomerNestedInput + identityDocuments?: IdentityDocumentUpdateManyWithoutCustomerNestedInput + meters?: MeterUpdateManyWithoutCustomerNestedInput + stressfreiEmails?: StressfreiEmailUpdateManyWithoutCustomerNestedInput + contracts?: ContractUpdateManyWithoutCustomerNestedInput + representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput + representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput + } + + export type CustomerUncheckedUpdateWithoutAuthorizationsGivenInput = { + id?: IntFieldUpdateOperationsInput | number + customerNumber?: StringFieldUpdateOperationsInput | string + type?: EnumCustomerTypeFieldUpdateOperationsInput | $Enums.CustomerType + salutation?: NullableStringFieldUpdateOperationsInput | string | null + firstName?: StringFieldUpdateOperationsInput | string + lastName?: StringFieldUpdateOperationsInput | string + companyName?: NullableStringFieldUpdateOperationsInput | string | null + foundingDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthPlace?: NullableStringFieldUpdateOperationsInput | string | null + email?: NullableStringFieldUpdateOperationsInput | string | null + phone?: NullableStringFieldUpdateOperationsInput | string | null + mobile?: NullableStringFieldUpdateOperationsInput | string | null + taxNumber?: NullableStringFieldUpdateOperationsInput | string | null + businessRegistrationPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null + privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + portalEnabled?: BoolFieldUpdateOperationsInput | boolean + portalEmail?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordHash?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null + portalLastLogin?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + user?: UserUncheckedUpdateOneWithoutCustomerNestedInput + addresses?: AddressUncheckedUpdateManyWithoutCustomerNestedInput + bankCards?: BankCardUncheckedUpdateManyWithoutCustomerNestedInput + identityDocuments?: IdentityDocumentUncheckedUpdateManyWithoutCustomerNestedInput + meters?: MeterUncheckedUpdateManyWithoutCustomerNestedInput + stressfreiEmails?: StressfreiEmailUncheckedUpdateManyWithoutCustomerNestedInput + contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput + representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput + representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput + } + + export type CustomerUpsertWithoutAuthorizationsReceivedInput = { + update: XOR + create: XOR + where?: CustomerWhereInput + } + + export type CustomerUpdateToOneWithWhereWithoutAuthorizationsReceivedInput = { + where?: CustomerWhereInput + data: XOR + } + + export type CustomerUpdateWithoutAuthorizationsReceivedInput = { + customerNumber?: StringFieldUpdateOperationsInput | string + type?: EnumCustomerTypeFieldUpdateOperationsInput | $Enums.CustomerType + salutation?: NullableStringFieldUpdateOperationsInput | string | null + firstName?: StringFieldUpdateOperationsInput | string + lastName?: StringFieldUpdateOperationsInput | string + companyName?: NullableStringFieldUpdateOperationsInput | string | null + foundingDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthPlace?: NullableStringFieldUpdateOperationsInput | string | null + email?: NullableStringFieldUpdateOperationsInput | string | null + phone?: NullableStringFieldUpdateOperationsInput | string | null + mobile?: NullableStringFieldUpdateOperationsInput | string | null + taxNumber?: NullableStringFieldUpdateOperationsInput | string | null + businessRegistrationPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null + privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + portalEnabled?: BoolFieldUpdateOperationsInput | boolean + portalEmail?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordHash?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null + portalLastLogin?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + user?: UserUpdateOneWithoutCustomerNestedInput + addresses?: AddressUpdateManyWithoutCustomerNestedInput + bankCards?: BankCardUpdateManyWithoutCustomerNestedInput + identityDocuments?: IdentityDocumentUpdateManyWithoutCustomerNestedInput + meters?: MeterUpdateManyWithoutCustomerNestedInput + stressfreiEmails?: StressfreiEmailUpdateManyWithoutCustomerNestedInput + contracts?: ContractUpdateManyWithoutCustomerNestedInput + representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput + representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput + } + + export type CustomerUncheckedUpdateWithoutAuthorizationsReceivedInput = { + id?: IntFieldUpdateOperationsInput | number + customerNumber?: StringFieldUpdateOperationsInput | string + type?: EnumCustomerTypeFieldUpdateOperationsInput | $Enums.CustomerType + salutation?: NullableStringFieldUpdateOperationsInput | string | null + firstName?: StringFieldUpdateOperationsInput | string + lastName?: StringFieldUpdateOperationsInput | string + companyName?: NullableStringFieldUpdateOperationsInput | string | null + foundingDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthPlace?: NullableStringFieldUpdateOperationsInput | string | null + email?: NullableStringFieldUpdateOperationsInput | string | null + phone?: NullableStringFieldUpdateOperationsInput | string | null + mobile?: NullableStringFieldUpdateOperationsInput | string | null + taxNumber?: NullableStringFieldUpdateOperationsInput | string | null + businessRegistrationPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null + privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + portalEnabled?: BoolFieldUpdateOperationsInput | boolean + portalEmail?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordHash?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null + portalLastLogin?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + user?: UserUncheckedUpdateOneWithoutCustomerNestedInput + addresses?: AddressUncheckedUpdateManyWithoutCustomerNestedInput + bankCards?: BankCardUncheckedUpdateManyWithoutCustomerNestedInput + identityDocuments?: IdentityDocumentUncheckedUpdateManyWithoutCustomerNestedInput + meters?: MeterUncheckedUpdateManyWithoutCustomerNestedInput + stressfreiEmails?: StressfreiEmailUncheckedUpdateManyWithoutCustomerNestedInput + contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput + representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput + representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type CustomerCreateWithoutAddressesInput = { @@ -52884,6 +62848,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -52900,6 +62865,9 @@ export namespace Prisma { contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutAddressesInput = { @@ -52921,6 +62889,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -52937,6 +62906,9 @@ export namespace Prisma { contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutAddressesInput = { @@ -53207,6 +63179,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -53223,6 +63196,9 @@ export namespace Prisma { contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutAddressesInput = { @@ -53244,6 +63220,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -53260,6 +63237,9 @@ export namespace Prisma { contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type ContractUpsertWithWhereUniqueWithoutAddressInput = { @@ -53312,6 +63292,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -53328,6 +63309,9 @@ export namespace Prisma { contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutBankCardsInput = { @@ -53349,6 +63333,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -53365,6 +63350,9 @@ export namespace Prisma { contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutBankCardsInput = { @@ -53518,6 +63506,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -53534,6 +63523,9 @@ export namespace Prisma { contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutBankCardsInput = { @@ -53555,6 +63547,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -53571,6 +63564,9 @@ export namespace Prisma { contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type ContractUpsertWithWhereUniqueWithoutBankCardInput = { @@ -53607,6 +63603,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -53623,6 +63620,9 @@ export namespace Prisma { contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutIdentityDocumentsInput = { @@ -53644,6 +63644,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -53660,6 +63661,9 @@ export namespace Prisma { contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutIdentityDocumentsInput = { @@ -53813,6 +63817,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -53829,6 +63834,9 @@ export namespace Prisma { contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutIdentityDocumentsInput = { @@ -53850,6 +63858,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -53866,6 +63875,9 @@ export namespace Prisma { contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type ContractUpsertWithWhereUniqueWithoutIdentityDocumentInput = { @@ -53902,6 +63914,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -53918,6 +63931,9 @@ export namespace Prisma { contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutStressfreiEmailsInput = { @@ -53939,6 +63955,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -53955,6 +63972,9 @@ export namespace Prisma { contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutStressfreiEmailsInput = { @@ -54171,6 +64191,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -54187,6 +64208,9 @@ export namespace Prisma { contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutStressfreiEmailsInput = { @@ -54208,6 +64232,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -54224,6 +64249,9 @@ export namespace Prisma { contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type ContractUpsertWithWhereUniqueWithoutStressfreiEmailInput = { @@ -54619,6 +64647,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -54635,6 +64664,9 @@ export namespace Prisma { contracts?: ContractCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutMetersInput = { @@ -54656,6 +64688,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -54672,6 +64705,9 @@ export namespace Prisma { contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutMetersInput = { @@ -54684,6 +64720,10 @@ export namespace Prisma { value: number unit?: string notes?: string | null + reportedBy?: string | null + status?: $Enums.MeterReadingStatus + transferredAt?: Date | string | null + transferredBy?: string | null createdAt?: Date | string } @@ -54693,6 +64733,10 @@ export namespace Prisma { value: number unit?: string notes?: string | null + reportedBy?: string | null + status?: $Enums.MeterReadingStatus + transferredAt?: Date | string | null + transferredBy?: string | null createdAt?: Date | string } @@ -54772,6 +64816,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -54788,6 +64833,9 @@ export namespace Prisma { contracts?: ContractUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutMetersInput = { @@ -54809,6 +64857,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -54825,6 +64874,9 @@ export namespace Prisma { contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type MeterReadingUpsertWithWhereUniqueWithoutMeterInput = { @@ -54853,6 +64905,10 @@ export namespace Prisma { value?: FloatFilter<"MeterReading"> | number unit?: StringFilter<"MeterReading"> | string notes?: StringNullableFilter<"MeterReading"> | string | null + reportedBy?: StringNullableFilter<"MeterReading"> | string | null + status?: EnumMeterReadingStatusFilter<"MeterReading"> | $Enums.MeterReadingStatus + transferredAt?: DateTimeNullableFilter<"MeterReading"> | Date | string | null + transferredBy?: StringNullableFilter<"MeterReading"> | string | null createdAt?: DateTimeFilter<"MeterReading"> | Date | string } @@ -56021,6 +66077,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -56037,6 +66094,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentCreateNestedManyWithoutCustomerInput } export type CustomerUncheckedCreateWithoutContractsInput = { @@ -56058,6 +66118,7 @@ export namespace Prisma { commercialRegisterPath?: string | null commercialRegisterNumber?: string | null privacyPolicyPath?: string | null + consentHash?: string | null notes?: string | null portalEnabled?: boolean portalEmail?: string | null @@ -56074,6 +66135,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUncheckedCreateNestedManyWithoutCustomerInput representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + consents?: CustomerConsentUncheckedCreateNestedManyWithoutCustomerInput } export type CustomerCreateOrConnectWithoutContractsInput = { @@ -56957,6 +67021,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -56973,6 +67038,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUpdateManyWithoutCustomerNestedInput } export type CustomerUncheckedUpdateWithoutContractsInput = { @@ -56994,6 +67062,7 @@ export namespace Prisma { commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null notes?: NullableStringFieldUpdateOperationsInput | string | null portalEnabled?: BoolFieldUpdateOperationsInput | boolean portalEmail?: NullableStringFieldUpdateOperationsInput | string | null @@ -57010,6 +67079,9 @@ export namespace Prisma { stressfreiEmails?: StressfreiEmailUncheckedUpdateManyWithoutCustomerNestedInput representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + consents?: CustomerConsentUncheckedUpdateManyWithoutCustomerNestedInput } export type ContractCategoryUpsertWithoutContractsInput = { @@ -60108,6 +70180,184 @@ export namespace Prisma { historyEntries?: ContractHistoryEntryUncheckedUpdateManyWithoutContractNestedInput } + export type CustomerCreateWithoutConsentsInput = { + customerNumber: string + type?: $Enums.CustomerType + salutation?: string | null + firstName: string + lastName: string + companyName?: string | null + foundingDate?: Date | string | null + birthDate?: Date | string | null + birthPlace?: string | null + email?: string | null + phone?: string | null + mobile?: string | null + taxNumber?: string | null + businessRegistrationPath?: string | null + commercialRegisterPath?: string | null + commercialRegisterNumber?: string | null + privacyPolicyPath?: string | null + consentHash?: string | null + notes?: string | null + portalEnabled?: boolean + portalEmail?: string | null + portalPasswordHash?: string | null + portalPasswordEncrypted?: string | null + portalLastLogin?: Date | string | null + createdAt?: Date | string + updatedAt?: Date | string + user?: UserCreateNestedOneWithoutCustomerInput + addresses?: AddressCreateNestedManyWithoutCustomerInput + bankCards?: BankCardCreateNestedManyWithoutCustomerInput + identityDocuments?: IdentityDocumentCreateNestedManyWithoutCustomerInput + meters?: MeterCreateNestedManyWithoutCustomerInput + stressfreiEmails?: StressfreiEmailCreateNestedManyWithoutCustomerInput + contracts?: ContractCreateNestedManyWithoutCustomerInput + representingFor?: CustomerRepresentativeCreateNestedManyWithoutRepresentativeInput + representedBy?: CustomerRepresentativeCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationCreateNestedManyWithoutRepresentativeInput + } + + export type CustomerUncheckedCreateWithoutConsentsInput = { + id?: number + customerNumber: string + type?: $Enums.CustomerType + salutation?: string | null + firstName: string + lastName: string + companyName?: string | null + foundingDate?: Date | string | null + birthDate?: Date | string | null + birthPlace?: string | null + email?: string | null + phone?: string | null + mobile?: string | null + taxNumber?: string | null + businessRegistrationPath?: string | null + commercialRegisterPath?: string | null + commercialRegisterNumber?: string | null + privacyPolicyPath?: string | null + consentHash?: string | null + notes?: string | null + portalEnabled?: boolean + portalEmail?: string | null + portalPasswordHash?: string | null + portalPasswordEncrypted?: string | null + portalLastLogin?: Date | string | null + createdAt?: Date | string + updatedAt?: Date | string + user?: UserUncheckedCreateNestedOneWithoutCustomerInput + addresses?: AddressUncheckedCreateNestedManyWithoutCustomerInput + bankCards?: BankCardUncheckedCreateNestedManyWithoutCustomerInput + identityDocuments?: IdentityDocumentUncheckedCreateNestedManyWithoutCustomerInput + meters?: MeterUncheckedCreateNestedManyWithoutCustomerInput + stressfreiEmails?: StressfreiEmailUncheckedCreateNestedManyWithoutCustomerInput + contracts?: ContractUncheckedCreateNestedManyWithoutCustomerInput + representingFor?: CustomerRepresentativeUncheckedCreateNestedManyWithoutRepresentativeInput + representedBy?: CustomerRepresentativeUncheckedCreateNestedManyWithoutCustomerInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutCustomerInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedCreateNestedManyWithoutRepresentativeInput + } + + export type CustomerCreateOrConnectWithoutConsentsInput = { + where: CustomerWhereUniqueInput + create: XOR + } + + export type CustomerUpsertWithoutConsentsInput = { + update: XOR + create: XOR + where?: CustomerWhereInput + } + + export type CustomerUpdateToOneWithWhereWithoutConsentsInput = { + where?: CustomerWhereInput + data: XOR + } + + export type CustomerUpdateWithoutConsentsInput = { + customerNumber?: StringFieldUpdateOperationsInput | string + type?: EnumCustomerTypeFieldUpdateOperationsInput | $Enums.CustomerType + salutation?: NullableStringFieldUpdateOperationsInput | string | null + firstName?: StringFieldUpdateOperationsInput | string + lastName?: StringFieldUpdateOperationsInput | string + companyName?: NullableStringFieldUpdateOperationsInput | string | null + foundingDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthPlace?: NullableStringFieldUpdateOperationsInput | string | null + email?: NullableStringFieldUpdateOperationsInput | string | null + phone?: NullableStringFieldUpdateOperationsInput | string | null + mobile?: NullableStringFieldUpdateOperationsInput | string | null + taxNumber?: NullableStringFieldUpdateOperationsInput | string | null + businessRegistrationPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null + privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + portalEnabled?: BoolFieldUpdateOperationsInput | boolean + portalEmail?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordHash?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null + portalLastLogin?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + user?: UserUpdateOneWithoutCustomerNestedInput + addresses?: AddressUpdateManyWithoutCustomerNestedInput + bankCards?: BankCardUpdateManyWithoutCustomerNestedInput + identityDocuments?: IdentityDocumentUpdateManyWithoutCustomerNestedInput + meters?: MeterUpdateManyWithoutCustomerNestedInput + stressfreiEmails?: StressfreiEmailUpdateManyWithoutCustomerNestedInput + contracts?: ContractUpdateManyWithoutCustomerNestedInput + representingFor?: CustomerRepresentativeUpdateManyWithoutRepresentativeNestedInput + representedBy?: CustomerRepresentativeUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUpdateManyWithoutRepresentativeNestedInput + } + + export type CustomerUncheckedUpdateWithoutConsentsInput = { + id?: IntFieldUpdateOperationsInput | number + customerNumber?: StringFieldUpdateOperationsInput | string + type?: EnumCustomerTypeFieldUpdateOperationsInput | $Enums.CustomerType + salutation?: NullableStringFieldUpdateOperationsInput | string | null + firstName?: StringFieldUpdateOperationsInput | string + lastName?: StringFieldUpdateOperationsInput | string + companyName?: NullableStringFieldUpdateOperationsInput | string | null + foundingDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthDate?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + birthPlace?: NullableStringFieldUpdateOperationsInput | string | null + email?: NullableStringFieldUpdateOperationsInput | string | null + phone?: NullableStringFieldUpdateOperationsInput | string | null + mobile?: NullableStringFieldUpdateOperationsInput | string | null + taxNumber?: NullableStringFieldUpdateOperationsInput | string | null + businessRegistrationPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterPath?: NullableStringFieldUpdateOperationsInput | string | null + commercialRegisterNumber?: NullableStringFieldUpdateOperationsInput | string | null + privacyPolicyPath?: NullableStringFieldUpdateOperationsInput | string | null + consentHash?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + portalEnabled?: BoolFieldUpdateOperationsInput | boolean + portalEmail?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordHash?: NullableStringFieldUpdateOperationsInput | string | null + portalPasswordEncrypted?: NullableStringFieldUpdateOperationsInput | string | null + portalLastLogin?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + user?: UserUncheckedUpdateOneWithoutCustomerNestedInput + addresses?: AddressUncheckedUpdateManyWithoutCustomerNestedInput + bankCards?: BankCardUncheckedUpdateManyWithoutCustomerNestedInput + identityDocuments?: IdentityDocumentUncheckedUpdateManyWithoutCustomerNestedInput + meters?: MeterUncheckedUpdateManyWithoutCustomerNestedInput + stressfreiEmails?: StressfreiEmailUncheckedUpdateManyWithoutCustomerNestedInput + contracts?: ContractUncheckedUpdateManyWithoutCustomerNestedInput + representingFor?: CustomerRepresentativeUncheckedUpdateManyWithoutRepresentativeNestedInput + representedBy?: CustomerRepresentativeUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsGiven?: RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerNestedInput + authorizationsReceived?: RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeNestedInput + } + export type UserRoleCreateManyUserInput = { roleId: number } @@ -60301,6 +70551,47 @@ export namespace Prisma { updatedAt?: Date | string } + export type RepresentativeAuthorizationCreateManyCustomerInput = { + id?: number + representativeId: number + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type RepresentativeAuthorizationCreateManyRepresentativeInput = { + id?: number + customerId: number + isGranted?: boolean + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + notes?: string | null + createdAt?: Date | string + updatedAt?: Date | string + } + + export type CustomerConsentCreateManyCustomerInput = { + id?: number + consentType: $Enums.ConsentType + status?: $Enums.ConsentStatus + grantedAt?: Date | string | null + withdrawnAt?: Date | string | null + source?: string | null + documentPath?: string | null + version?: string | null + ipAddress?: string | null + createdBy: string + createdAt?: Date | string + updatedAt?: Date | string + } + export type AddressUpdateWithoutCustomerInput = { type?: EnumAddressTypeFieldUpdateOperationsInput | $Enums.AddressType street?: StringFieldUpdateOperationsInput | string @@ -60714,6 +71005,126 @@ export namespace Prisma { updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string } + export type RepresentativeAuthorizationUpdateWithoutCustomerInput = { + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + representative?: CustomerUpdateOneRequiredWithoutAuthorizationsReceivedNestedInput + } + + export type RepresentativeAuthorizationUncheckedUpdateWithoutCustomerInput = { + id?: IntFieldUpdateOperationsInput | number + representativeId?: IntFieldUpdateOperationsInput | number + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type RepresentativeAuthorizationUncheckedUpdateManyWithoutCustomerInput = { + id?: IntFieldUpdateOperationsInput | number + representativeId?: IntFieldUpdateOperationsInput | number + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type RepresentativeAuthorizationUpdateWithoutRepresentativeInput = { + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + customer?: CustomerUpdateOneRequiredWithoutAuthorizationsGivenNestedInput + } + + export type RepresentativeAuthorizationUncheckedUpdateWithoutRepresentativeInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type RepresentativeAuthorizationUncheckedUpdateManyWithoutRepresentativeInput = { + id?: IntFieldUpdateOperationsInput | number + customerId?: IntFieldUpdateOperationsInput | number + isGranted?: BoolFieldUpdateOperationsInput | boolean + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + notes?: NullableStringFieldUpdateOperationsInput | string | null + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type CustomerConsentUpdateWithoutCustomerInput = { + consentType?: EnumConsentTypeFieldUpdateOperationsInput | $Enums.ConsentType + status?: EnumConsentStatusFieldUpdateOperationsInput | $Enums.ConsentStatus + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + version?: NullableStringFieldUpdateOperationsInput | string | null + ipAddress?: NullableStringFieldUpdateOperationsInput | string | null + createdBy?: StringFieldUpdateOperationsInput | string + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type CustomerConsentUncheckedUpdateWithoutCustomerInput = { + id?: IntFieldUpdateOperationsInput | number + consentType?: EnumConsentTypeFieldUpdateOperationsInput | $Enums.ConsentType + status?: EnumConsentStatusFieldUpdateOperationsInput | $Enums.ConsentStatus + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + version?: NullableStringFieldUpdateOperationsInput | string | null + ipAddress?: NullableStringFieldUpdateOperationsInput | string | null + createdBy?: StringFieldUpdateOperationsInput | string + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + + export type CustomerConsentUncheckedUpdateManyWithoutCustomerInput = { + id?: IntFieldUpdateOperationsInput | number + consentType?: EnumConsentTypeFieldUpdateOperationsInput | $Enums.ConsentType + status?: EnumConsentStatusFieldUpdateOperationsInput | $Enums.ConsentStatus + grantedAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + withdrawnAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + source?: NullableStringFieldUpdateOperationsInput | string | null + documentPath?: NullableStringFieldUpdateOperationsInput | string | null + version?: NullableStringFieldUpdateOperationsInput | string | null + ipAddress?: NullableStringFieldUpdateOperationsInput | string | null + createdBy?: StringFieldUpdateOperationsInput | string + createdAt?: DateTimeFieldUpdateOperationsInput | Date | string + updatedAt?: DateTimeFieldUpdateOperationsInput | Date | string + } + export type ContractCreateManyAddressInput = { id?: number contractNumber: string @@ -61812,6 +72223,10 @@ export namespace Prisma { value: number unit?: string notes?: string | null + reportedBy?: string | null + status?: $Enums.MeterReadingStatus + transferredAt?: Date | string | null + transferredBy?: string | null createdAt?: Date | string } @@ -61833,6 +72248,10 @@ export namespace Prisma { value?: FloatFieldUpdateOperationsInput | number unit?: StringFieldUpdateOperationsInput | string notes?: NullableStringFieldUpdateOperationsInput | string | null + reportedBy?: NullableStringFieldUpdateOperationsInput | string | null + status?: EnumMeterReadingStatusFieldUpdateOperationsInput | $Enums.MeterReadingStatus + transferredAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + transferredBy?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string } @@ -61842,6 +72261,10 @@ export namespace Prisma { value?: FloatFieldUpdateOperationsInput | number unit?: StringFieldUpdateOperationsInput | string notes?: NullableStringFieldUpdateOperationsInput | string | null + reportedBy?: NullableStringFieldUpdateOperationsInput | string | null + status?: EnumMeterReadingStatusFieldUpdateOperationsInput | $Enums.MeterReadingStatus + transferredAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + transferredBy?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string } @@ -61851,6 +72274,10 @@ export namespace Prisma { value?: FloatFieldUpdateOperationsInput | number unit?: StringFieldUpdateOperationsInput | string notes?: NullableStringFieldUpdateOperationsInput | string | null + reportedBy?: NullableStringFieldUpdateOperationsInput | string | null + status?: EnumMeterReadingStatusFieldUpdateOperationsInput | $Enums.MeterReadingStatus + transferredAt?: NullableDateTimeFieldUpdateOperationsInput | Date | string | null + transferredBy?: NullableStringFieldUpdateOperationsInput | string | null createdAt?: DateTimeFieldUpdateOperationsInput | Date | string } @@ -63742,6 +74169,10 @@ export namespace Prisma { * @deprecated Use MobileContractDetailsCountOutputTypeDefaultArgs instead */ export type MobileContractDetailsCountOutputTypeArgs = MobileContractDetailsCountOutputTypeDefaultArgs + /** + * @deprecated Use EmailLogDefaultArgs instead + */ + export type EmailLogArgs = EmailLogDefaultArgs /** * @deprecated Use AppSettingDefaultArgs instead */ @@ -63774,6 +74205,10 @@ export namespace Prisma { * @deprecated Use CustomerRepresentativeDefaultArgs instead */ export type CustomerRepresentativeArgs = CustomerRepresentativeDefaultArgs + /** + * @deprecated Use RepresentativeAuthorizationDefaultArgs instead + */ + export type RepresentativeAuthorizationArgs = RepresentativeAuthorizationDefaultArgs /** * @deprecated Use AddressDefaultArgs instead */ @@ -63878,6 +74313,22 @@ export namespace Prisma { * @deprecated Use CarInsuranceDetailsDefaultArgs instead */ export type CarInsuranceDetailsArgs = CarInsuranceDetailsDefaultArgs + /** + * @deprecated Use AuditLogDefaultArgs instead + */ + export type AuditLogArgs = AuditLogDefaultArgs + /** + * @deprecated Use CustomerConsentDefaultArgs instead + */ + export type CustomerConsentArgs = CustomerConsentDefaultArgs + /** + * @deprecated Use DataDeletionRequestDefaultArgs instead + */ + export type DataDeletionRequestArgs = DataDeletionRequestDefaultArgs + /** + * @deprecated Use AuditRetentionPolicyDefaultArgs instead + */ + export type AuditRetentionPolicyArgs = AuditRetentionPolicyDefaultArgs /** * Batch Payload for updateMany & deleteMany & createMany diff --git a/backend/node_modules/.prisma/client/index.js b/backend/node_modules/.prisma/client/index.js index 72111583..20fa4ab6 100644 --- a/backend/node_modules/.prisma/client/index.js +++ b/backend/node_modules/.prisma/client/index.js @@ -91,6 +91,25 @@ exports.Prisma.TransactionIsolationLevel = makeStrictEnum({ Serializable: 'Serializable' }); +exports.Prisma.EmailLogScalarFieldEnum = { + id: 'id', + fromAddress: 'fromAddress', + toAddress: 'toAddress', + subject: 'subject', + context: 'context', + customerId: 'customerId', + triggeredBy: 'triggeredBy', + smtpServer: 'smtpServer', + smtpPort: 'smtpPort', + smtpEncryption: 'smtpEncryption', + smtpUser: 'smtpUser', + success: 'success', + messageId: 'messageId', + errorMessage: 'errorMessage', + smtpResponse: 'smtpResponse', + sentAt: 'sentAt' +}; + exports.Prisma.AppSettingScalarFieldEnum = { id: 'id', key: 'key', @@ -107,6 +126,9 @@ exports.Prisma.UserScalarFieldEnum = { lastName: 'lastName', isActive: 'isActive', tokenInvalidatedAt: 'tokenInvalidatedAt', + whatsappNumber: 'whatsappNumber', + telegramUsername: 'telegramUsername', + signalNumber: 'signalNumber', customerId: 'customerId', createdAt: 'createdAt', updatedAt: 'updatedAt' @@ -155,6 +177,7 @@ exports.Prisma.CustomerScalarFieldEnum = { commercialRegisterPath: 'commercialRegisterPath', commercialRegisterNumber: 'commercialRegisterNumber', privacyPolicyPath: 'privacyPolicyPath', + consentHash: 'consentHash', notes: 'notes', portalEnabled: 'portalEnabled', portalEmail: 'portalEmail', @@ -175,6 +198,20 @@ exports.Prisma.CustomerRepresentativeScalarFieldEnum = { updatedAt: 'updatedAt' }; +exports.Prisma.RepresentativeAuthorizationScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + representativeId: 'representativeId', + isGranted: 'isGranted', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + notes: 'notes', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.AddressScalarFieldEnum = { id: 'id', customerId: 'customerId', @@ -236,6 +273,8 @@ exports.Prisma.EmailProviderConfigScalarFieldEnum = { imapEncryption: 'imapEncryption', smtpEncryption: 'smtpEncryption', allowSelfSignedCerts: 'allowSelfSignedCerts', + systemEmailAddress: 'systemEmailAddress', + systemEmailPasswordEncrypted: 'systemEmailPasswordEncrypted', isActive: 'isActive', isDefault: 'isDefault', createdAt: 'createdAt', @@ -304,6 +343,10 @@ exports.Prisma.MeterReadingScalarFieldEnum = { value: 'value', unit: 'unit', notes: 'notes', + reportedBy: 'reportedBy', + status: 'status', + transferredAt: 'transferredAt', + transferredBy: 'transferredBy', createdAt: 'createdAt' }; @@ -546,6 +589,80 @@ exports.Prisma.CarInsuranceDetailsScalarFieldEnum = { previousInsurer: 'previousInsurer' }; +exports.Prisma.AuditLogScalarFieldEnum = { + id: 'id', + userId: 'userId', + userEmail: 'userEmail', + userRole: 'userRole', + customerId: 'customerId', + isCustomerPortal: 'isCustomerPortal', + action: 'action', + sensitivity: 'sensitivity', + resourceType: 'resourceType', + resourceId: 'resourceId', + resourceLabel: 'resourceLabel', + endpoint: 'endpoint', + httpMethod: 'httpMethod', + ipAddress: 'ipAddress', + userAgent: 'userAgent', + changesBefore: 'changesBefore', + changesAfter: 'changesAfter', + changesEncrypted: 'changesEncrypted', + dataSubjectId: 'dataSubjectId', + legalBasis: 'legalBasis', + success: 'success', + errorMessage: 'errorMessage', + durationMs: 'durationMs', + createdAt: 'createdAt', + hash: 'hash', + previousHash: 'previousHash' +}; + +exports.Prisma.CustomerConsentScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + consentType: 'consentType', + status: 'status', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + version: 'version', + ipAddress: 'ipAddress', + createdBy: 'createdBy', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.DataDeletionRequestScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + status: 'status', + requestedAt: 'requestedAt', + requestSource: 'requestSource', + requestedBy: 'requestedBy', + processedAt: 'processedAt', + processedBy: 'processedBy', + deletedData: 'deletedData', + retainedData: 'retainedData', + retentionReason: 'retentionReason', + proofDocument: 'proofDocument', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.AuditRetentionPolicyScalarFieldEnum = { + id: 'id', + resourceType: 'resourceType', + sensitivity: 'sensitivity', + retentionDays: 'retentionDays', + description: 'description', + legalBasis: 'legalBasis', + isActive: 'isActive', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.SortOrder = { asc: 'asc', desc: 'desc' @@ -594,6 +711,12 @@ exports.MeterType = exports.$Enums.MeterType = { GAS: 'GAS' }; +exports.MeterReadingStatus = exports.$Enums.MeterReadingStatus = { + RECORDED: 'RECORDED', + REPORTED: 'REPORTED', + TRANSFERRED: 'TRANSFERRED' +}; + exports.ContractType = exports.$Enums.ContractType = { ELECTRICITY: 'ELECTRICITY', GAS: 'GAS', @@ -631,7 +754,48 @@ exports.InsuranceType = exports.$Enums.InsuranceType = { FULL: 'FULL' }; +exports.AuditAction = exports.$Enums.AuditAction = { + CREATE: 'CREATE', + READ: 'READ', + UPDATE: 'UPDATE', + DELETE: 'DELETE', + EXPORT: 'EXPORT', + ANONYMIZE: 'ANONYMIZE', + LOGIN: 'LOGIN', + LOGOUT: 'LOGOUT', + LOGIN_FAILED: 'LOGIN_FAILED' +}; + +exports.AuditSensitivity = exports.$Enums.AuditSensitivity = { + LOW: 'LOW', + MEDIUM: 'MEDIUM', + HIGH: 'HIGH', + CRITICAL: 'CRITICAL' +}; + +exports.ConsentType = exports.$Enums.ConsentType = { + DATA_PROCESSING: 'DATA_PROCESSING', + MARKETING_EMAIL: 'MARKETING_EMAIL', + MARKETING_PHONE: 'MARKETING_PHONE', + DATA_SHARING_PARTNER: 'DATA_SHARING_PARTNER' +}; + +exports.ConsentStatus = exports.$Enums.ConsentStatus = { + GRANTED: 'GRANTED', + WITHDRAWN: 'WITHDRAWN', + PENDING: 'PENDING' +}; + +exports.DeletionRequestStatus = exports.$Enums.DeletionRequestStatus = { + PENDING: 'PENDING', + IN_PROGRESS: 'IN_PROGRESS', + COMPLETED: 'COMPLETED', + PARTIALLY_COMPLETED: 'PARTIALLY_COMPLETED', + REJECTED: 'REJECTED' +}; + exports.Prisma.ModelName = { + EmailLog: 'EmailLog', AppSetting: 'AppSetting', User: 'User', Role: 'Role', @@ -640,6 +804,7 @@ exports.Prisma.ModelName = { UserRole: 'UserRole', Customer: 'Customer', CustomerRepresentative: 'CustomerRepresentative', + RepresentativeAuthorization: 'RepresentativeAuthorization', Address: 'Address', BankCard: 'BankCard', IdentityDocument: 'IdentityDocument', @@ -665,7 +830,11 @@ exports.Prisma.ModelName = { MobileContractDetails: 'MobileContractDetails', SimCard: 'SimCard', TvContractDetails: 'TvContractDetails', - CarInsuranceDetails: 'CarInsuranceDetails' + CarInsuranceDetails: 'CarInsuranceDetails', + AuditLog: 'AuditLog', + CustomerConsent: 'CustomerConsent', + DataDeletionRequest: 'DataDeletionRequest', + AuditRetentionPolicy: 'AuditRetentionPolicy' }; /** * Create the Client @@ -705,6 +874,7 @@ const config = { "db" ], "activeProvider": "mysql", + "postinstall": false, "inlineDatasources": { "db": { "url": { @@ -713,8 +883,8 @@ const config = { } } }, - "inlineSchema": "generator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ==================== APP SETTINGS ====================\n\nmodel AppSetting {\n id Int @id @default(autoincrement())\n key String @unique\n value String @db.Text\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== USERS & AUTH ====================\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n password String\n firstName String\n lastName String\n isActive Boolean @default(true)\n tokenInvalidatedAt DateTime? // Zeitpunkt ab dem alle Tokens ungültig sind (für Zwangslogout bei Rechteänderung)\n customerId Int? @unique\n customer Customer? @relation(fields: [customerId], references: [id])\n roles UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Role {\n id Int @id @default(autoincrement())\n name String @unique\n description String?\n permissions RolePermission[]\n users UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Permission {\n id Int @id @default(autoincrement())\n resource String\n action String\n roles RolePermission[]\n\n @@unique([resource, action])\n}\n\nmodel RolePermission {\n roleId Int\n permissionId Int\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)\n\n @@id([roleId, permissionId])\n}\n\nmodel UserRole {\n userId Int\n roleId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n\n @@id([userId, roleId])\n}\n\n// ==================== CUSTOMERS ====================\n\nenum CustomerType {\n PRIVATE\n BUSINESS\n}\n\nmodel Customer {\n id Int @id @default(autoincrement())\n customerNumber String @unique\n type CustomerType @default(PRIVATE)\n salutation String?\n firstName String\n lastName String\n companyName String?\n foundingDate DateTime? // Gründungsdatum (für Firmen)\n birthDate DateTime?\n birthPlace String?\n email String?\n phone String?\n mobile String?\n taxNumber String?\n businessRegistrationPath String? // PDF-Pfad zur Gewerbeanmeldung\n commercialRegisterPath String? // PDF-Pfad zum Handelsregisterauszug\n commercialRegisterNumber String? // Handelsregisternummer (Text)\n privacyPolicyPath String? // PDF-Pfad zur Datenschutzerklärung (für alle Kunden)\n notes String? @db.Text\n\n // ===== Portal-Zugangsdaten =====\n portalEnabled Boolean @default(false) // Portal aktiviert?\n portalEmail String? @unique // Portal-Login E-Mail\n portalPasswordHash String? // Gehashtes Passwort (für Login)\n portalPasswordEncrypted String? // Verschlüsseltes Passwort (für Anzeige)\n portalLastLogin DateTime? // Letzte Anmeldung\n\n user User?\n addresses Address[]\n bankCards BankCard[]\n identityDocuments IdentityDocument[]\n meters Meter[]\n stressfreiEmails StressfreiEmail[]\n contracts Contract[]\n\n // Vertreter-Beziehungen (Kunde kann für andere Kunden handeln)\n representingFor CustomerRepresentative[] @relation(\"RepresentativeCustomer\")\n representedBy CustomerRepresentative[] @relation(\"RepresentedCustomer\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CUSTOMER REPRESENTATIVES ====================\n// Vertretungsbeziehung: Ein Kunde kann die Verträge eines anderen Kunden einsehen\n// z.B. Sohn (representativeId) kann Verträge der Mutter (customerId) sehen\n\nmodel CustomerRepresentative {\n id Int @id @default(autoincrement())\n customerId Int // Der Kunde, dessen Verträge eingesehen werden (z.B. Mutter)\n customer Customer @relation(\"RepresentedCustomer\", fields: [customerId], references: [id], onDelete: Cascade)\n representativeId Int // Der Kunde, der einsehen darf (z.B. Sohn)\n representative Customer @relation(\"RepresentativeCustomer\", fields: [representativeId], references: [id], onDelete: Cascade)\n notes String? // Notizen zur Vertretung\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, representativeId]) // Keine doppelten Einträge\n}\n\n// ==================== ADDRESSES ====================\n\nenum AddressType {\n DELIVERY_RESIDENCE\n BILLING\n}\n\nmodel Address {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type AddressType @default(DELIVERY_RESIDENCE)\n street String\n houseNumber String\n postalCode String\n city String\n country String @default(\"Deutschland\")\n isDefault Boolean @default(false)\n contractsAsDelivery Contract[] @relation(\"DeliveryAddress\")\n contractsAsBilling Contract[] @relation(\"BillingAddress\")\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== BANK CARDS ====================\n\nmodel BankCard {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n accountHolder String\n iban String\n bic String?\n bankName String?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== IDENTITY DOCUMENTS ====================\n\nenum DocumentType {\n ID_CARD\n PASSPORT\n DRIVERS_LICENSE\n OTHER\n}\n\nmodel IdentityDocument {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type DocumentType @default(ID_CARD)\n documentNumber String\n issuingAuthority String?\n issueDate DateTime?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n // Führerschein-spezifische Felder\n licenseClasses String? // z.B. \"B, BE, AM, L\" - kommasepariert\n licenseIssueDate DateTime? // Datum des Führerscheinerwerbs (Klasse B)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== EMAIL PROVIDER CONFIG (Plesk, cPanel etc.) ====================\n\nenum EmailProviderType {\n PLESK\n CPANEL\n DIRECTADMIN\n}\n\n// Verschlüsselungstyp für E-Mail-Verbindungen\nenum MailEncryption {\n SSL // Implicit SSL/TLS (Ports 465/993) - Verschlüsselung von Anfang an\n STARTTLS // STARTTLS (Ports 587/143) - Startet unverschlüsselt, dann Upgrade\n NONE // Keine Verschlüsselung (Ports 25/143)\n}\n\nmodel EmailProviderConfig {\n id Int @id @default(autoincrement())\n name String @unique // z.B. \"Plesk Hauptserver\"\n type EmailProviderType\n apiUrl String // API-URL (z.B. https://server.de:8443)\n apiKey String? // API-Key (verschlüsselt)\n username String? // Benutzername für API\n passwordEncrypted String? // Passwort (verschlüsselt)\n domain String // Domain für E-Mails (z.B. stressfrei-wechseln.de)\n defaultForwardEmail String? // Standard-Weiterleitungsadresse (unsere eigene)\n\n // IMAP/SMTP-Server für E-Mail-Client (optional, default: mail.{domain})\n imapServer String? // z.B. \"mail.stressfrei-wechseln.de\"\n imapPort Int? @default(993)\n smtpServer String?\n smtpPort Int? @default(465)\n\n // Verschlüsselungs-Einstellungen\n imapEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n smtpEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n allowSelfSignedCerts Boolean @default(false) // Selbstsignierte Zertifikate erlauben\n\n isActive Boolean @default(true)\n isDefault Boolean @default(false) // Standard-Provider\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== STRESSFREI-WECHSELN EMAIL ADDRESSES ====================\n\nmodel StressfreiEmail {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n email String // Die Weiterleitungs-E-Mail-Adresse\n platform String? // Für welche Plattform (z.B. \"Freenet\", \"Klarmobil\")\n notes String? @db.Text // Optionale Notizen\n isActive Boolean @default(true)\n isProvisioned Boolean @default(false) // Wurde bei Provider angelegt?\n provisionedAt DateTime? // Wann wurde provisioniert?\n provisionError String? @db.Text // Fehlermeldung falls Provisionierung fehlschlug\n\n // Mailbox-Zugangsdaten (für IMAP/SMTP-Zugang)\n hasMailbox Boolean @default(false) // Hat echte Mailbox (nicht nur Weiterleitung)?\n emailPasswordEncrypted String? // Verschlüsseltes Mailbox-Passwort (AES-256-GCM)\n\n contracts Contract[] // Verträge die diese E-Mail als Benutzername verwenden\n cachedEmails CachedEmail[] // Gecachte E-Mails aus dieser Mailbox\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CACHED EMAILS (E-Mail-Client) ====================\n\nenum EmailFolder {\n INBOX\n SENT\n}\n\nmodel CachedEmail {\n id Int @id @default(autoincrement())\n stressfreiEmailId Int\n stressfreiEmail StressfreiEmail @relation(fields: [stressfreiEmailId], references: [id], onDelete: Cascade)\n\n // Ordner (Posteingang oder Gesendet)\n folder EmailFolder @default(INBOX)\n\n // IMAP-Identifikation\n messageId String // RFC 5322 Message-ID\n uid Int // IMAP UID (für Synchronisierung, bei SENT = 0)\n\n // E-Mail-Metadaten\n subject String?\n fromAddress String\n fromName String?\n toAddresses String @db.Text // JSON Array\n ccAddresses String? @db.Text // JSON Array\n receivedAt DateTime\n\n // Inhalt\n textBody String? @db.LongText\n htmlBody String? @db.LongText\n hasAttachments Boolean @default(false)\n attachmentNames String? @db.Text // JSON Array\n\n // Vertragszuordnung\n contractId Int?\n contract Contract? @relation(fields: [contractId], references: [id], onDelete: SetNull)\n assignedAt DateTime?\n assignedBy Int? // User ID der die Zuordnung gemacht hat\n isAutoAssigned Boolean @default(false) // true = automatisch beim Senden aus Vertrag\n\n // Flags\n isRead Boolean @default(false)\n isStarred Boolean @default(false)\n\n // Papierkorb\n isDeleted Boolean @default(false) // Im Papierkorb?\n deletedAt DateTime? // Wann gelöscht?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([stressfreiEmailId, messageId, folder]) // Folder hinzugefügt: gleiche MessageID kann in INBOX und SENT existieren\n @@index([contractId])\n @@index([stressfreiEmailId, folder, receivedAt])\n @@index([stressfreiEmailId, isDeleted]) // Für Papierkorb-Abfragen\n}\n\n// ==================== METERS (Energy) ====================\n\nenum MeterType {\n ELECTRICITY\n GAS\n}\n\nmodel Meter {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n meterNumber String\n type MeterType\n location String?\n isActive Boolean @default(true)\n readings MeterReading[]\n energyDetails EnergyContractDetails[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel MeterReading {\n id Int @id @default(autoincrement())\n meterId Int\n meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade)\n readingDate DateTime\n value Float\n unit String @default(\"kWh\")\n notes String?\n createdAt DateTime @default(now())\n}\n\n// ==================== SALES PLATFORMS ====================\n\nmodel SalesPlatform {\n id Int @id @default(autoincrement())\n name String @unique\n contactInfo String? @db.Text\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CANCELLATION PERIODS ====================\n\nmodel CancellationPeriod {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"14T\", \"1M\", \"3M\", \"12M\", \"1J\"\n description String // z.B. \"14 Tage\", \"1 Monat\", \"3 Monate\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT DURATIONS ====================\n\nmodel ContractDuration {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"12M\", \"24M\", \"1J\", \"2J\"\n description String // z.B. \"12 Monate\", \"24 Monate\", \"1 Jahr\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== PROVIDERS (Anbieter) ====================\n\nmodel Provider {\n id Int @id @default(autoincrement())\n name String @unique // Anbietername\n portalUrl String? // Kundenkontourl (Login-Seite)\n usernameFieldName String? // Benutzernamefeld (z.B. \"email\", \"username\")\n passwordFieldName String? // Kennwortfeld (z.B. \"password\", \"pwd\")\n isActive Boolean @default(true)\n tariffs Tariff[]\n contracts Contract[]\n previousContracts Contract[] @relation(\"PreviousProvider\") // Verträge wo dieser Provider Altanbieter ist\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TARIFFS (Tarife) ====================\n\nmodel Tariff {\n id Int @id @default(autoincrement())\n providerId Int\n provider Provider @relation(fields: [providerId], references: [id], onDelete: Cascade)\n name String // Tarifname\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([providerId, name]) // Eindeutiger Tarif pro Anbieter\n}\n\n// ==================== CONTRACT CATEGORIES ====================\n\nmodel ContractCategory {\n id Int @id @default(autoincrement())\n code String @unique // Technischer Code (z.B. ELECTRICITY, GAS)\n name String // Anzeigename (z.B. Strom, Gas)\n icon String? // Icon-Name für UI (z.B. \"Zap\", \"Flame\")\n color String? // Farbe für UI (z.B. \"#FFC107\")\n sortOrder Int @default(0)\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACTS ====================\n\n// Legacy Enum - wird durch ContractCategory ersetzt\nenum ContractType {\n ELECTRICITY\n GAS\n DSL\n CABLE\n FIBER\n MOBILE\n TV\n CAR_INSURANCE\n}\n\nenum ContractStatus {\n DRAFT\n PENDING\n ACTIVE\n CANCELLED\n EXPIRED\n DEACTIVATED\n}\n\nmodel Contract {\n id Int @id @default(autoincrement())\n contractNumber String @unique\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type ContractType\n status ContractStatus @default(DRAFT)\n\n // Neue konfigurierbare Kategorie (ersetzt langfristig das type-Enum)\n contractCategoryId Int?\n contractCategory ContractCategory? @relation(fields: [contractCategoryId], references: [id])\n\n // Lieferadresse\n addressId Int?\n address Address? @relation(\"DeliveryAddress\", fields: [addressId], references: [id])\n\n // Rechnungsadresse (falls leer, wird Lieferadresse verwendet)\n billingAddressId Int?\n billingAddress Address? @relation(\"BillingAddress\", fields: [billingAddressId], references: [id])\n\n bankCardId Int?\n bankCard BankCard? @relation(fields: [bankCardId], references: [id])\n\n identityDocumentId Int?\n identityDocument IdentityDocument? @relation(fields: [identityDocumentId], references: [id])\n\n salesPlatformId Int?\n salesPlatform SalesPlatform? @relation(fields: [salesPlatformId], references: [id])\n\n cancellationPeriodId Int?\n cancellationPeriod CancellationPeriod? @relation(fields: [cancellationPeriodId], references: [id])\n\n contractDurationId Int?\n contractDuration ContractDuration? @relation(fields: [contractDurationId], references: [id])\n\n previousContractId Int? @unique\n previousContract Contract? @relation(\"ContractHistory\", fields: [previousContractId], references: [id])\n followUpContract Contract? @relation(\"ContractHistory\")\n\n // Altanbieter-Daten (nur wenn kein Vorgängervertrag existiert)\n previousProviderId Int?\n previousProvider Provider? @relation(\"PreviousProvider\", fields: [previousProviderId], references: [id])\n previousCustomerNumber String? // Kundennummer beim Altanbieter\n previousContractNumber String? // Vertragsnummer beim Altanbieter\n\n // Anbieter & Tarif (neue Verknüpfung)\n providerId Int?\n provider Provider? @relation(fields: [providerId], references: [id])\n tariffId Int?\n tariff Tariff? @relation(fields: [tariffId], references: [id])\n\n // Legacy-Felder (für Abwärtskompatibilität)\n providerName String?\n tariffName String?\n customerNumberAtProvider String?\n contractNumberAtProvider String? // Vertragsnummer beim Anbieter\n priceFirst12Months String? // Preis erste 12 Monate\n priceFrom13Months String? // Preis ab 13. Monat\n priceAfter24Months String? // Preis nach 24 Monaten\n\n startDate DateTime?\n endDate DateTime? // Wird aus startDate + contractDuration berechnet\n commission Float?\n\n // Kündigungsdokumente\n cancellationLetterPath String? // Kündigungsschreiben PDF\n cancellationConfirmationPath String? // Kündigungsbestätigung PDF\n cancellationLetterOptionsPath String? // Kündigungsschreiben Optionen PDF\n cancellationConfirmationOptionsPath String? // Kündigungsbestätigung Optionen PDF\n\n // Kündigungsdaten\n cancellationConfirmationDate DateTime? // Kündigungsbestätigungsdatum\n cancellationConfirmationOptionsDate DateTime? // Kündigungsbestätigungsoptionendatum\n wasSpecialCancellation Boolean @default(false) // Wurde sondergekündigt?\n\n portalUsername String?\n portalPasswordEncrypted String?\n\n // Stressfrei-Wechseln E-Mail als Benutzername (Alternative zu portalUsername)\n stressfreiEmailId Int?\n stressfreiEmail StressfreiEmail? @relation(fields: [stressfreiEmailId], references: [id])\n\n // Snooze: Vertrag zurückstellen bis Datum (für Cockpit)\n nextReviewDate DateTime? // Erneute Prüfung am\n\n notes String? @db.Text\n\n energyDetails EnergyContractDetails?\n internetDetails InternetContractDetails?\n mobileDetails MobileContractDetails?\n tvDetails TvContractDetails?\n carInsuranceDetails CarInsuranceDetails?\n\n tasks ContractTask[]\n assignedEmails CachedEmail[] // Zugeordnete E-Mails aus dem E-Mail-Client\n historyEntries ContractHistoryEntry[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT HISTORY ====================\n\nmodel ContractHistoryEntry {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String // Kurzbeschreibung (z.B. \"Folgevertrag erstellt\", \"kWh auf 18000 erhöht\")\n description String? @db.Text // Längere Beschreibung (optional)\n isAutomatic Boolean @default(false) // true = automatisch erstellt, false = manuell\n createdBy String // E-Mail des Erstellers\n createdAt DateTime @default(now())\n}\n\n// ==================== CONTRACT TASKS ====================\n\nenum ContractTaskStatus {\n OPEN\n COMPLETED\n}\n\nmodel ContractTask {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String\n description String? @db.Text\n status ContractTaskStatus @default(OPEN)\n visibleInPortal Boolean @default(false)\n createdBy String? // Name des Erstellers\n completedAt DateTime?\n subtasks ContractTaskSubtask[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel ContractTaskSubtask {\n id Int @id @default(autoincrement())\n taskId Int\n task ContractTask @relation(fields: [taskId], references: [id], onDelete: Cascade)\n title String\n status ContractTaskStatus @default(OPEN)\n createdBy String?\n completedAt DateTime?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== ENERGY CONTRACT DETAILS ====================\n\nenum InvoiceType {\n INTERIM // Zwischenrechnung\n FINAL // Schlussrechnung\n NOT_AVAILABLE // Rechnung nicht mehr zu bekommen\n}\n\nmodel EnergyContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n meterId Int?\n meter Meter? @relation(fields: [meterId], references: [id])\n maloId String? // Marktlokations-ID\n annualConsumption Float? // kWh für Strom, m³ für Gas\n annualConsumptionKwh Float? // kWh für Gas (zusätzlich zu m³)\n basePrice Float? // €/Monat\n unitPrice Float? // €/kWh (Arbeitspreis)\n bonus Float?\n previousProviderName String?\n previousCustomerNumber String?\n invoices Invoice[] // Rechnungen\n}\n\nmodel Invoice {\n id Int @id @default(autoincrement())\n energyContractDetailsId Int\n energyContractDetails EnergyContractDetails @relation(fields: [energyContractDetailsId], references: [id], onDelete: Cascade)\n invoiceDate DateTime\n invoiceType InvoiceType\n documentPath String? // Pflicht, außer bei NOT_AVAILABLE\n notes String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([energyContractDetailsId])\n}\n\n// ==================== INTERNET CONTRACT DETAILS ====================\n\nmodel InternetContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n downloadSpeed Int?\n uploadSpeed Int?\n routerModel String?\n routerSerialNumber String?\n installationDate DateTime?\n // Internet-Zugangsdaten\n internetUsername String?\n internetPasswordEncrypted String? // Verschlüsselt gespeichert\n // Glasfaser-spezifisch\n homeId String?\n // Vodafone DSL/Kabel spezifisch\n activationCode String?\n phoneNumbers PhoneNumber[]\n}\n\nmodel PhoneNumber {\n id Int @id @default(autoincrement())\n internetContractDetailsId Int\n internetDetails InternetContractDetails @relation(fields: [internetContractDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String\n isMain Boolean @default(false)\n // SIP-Zugangsdaten\n sipUsername String?\n sipPasswordEncrypted String? // Verschlüsselt gespeichert\n sipServer String?\n}\n\n// ==================== MOBILE CONTRACT DETAILS ====================\n\nmodel MobileContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n requiresMultisim Boolean @default(false) // Multisim erforderlich?\n dataVolume Float?\n includedMinutes Int?\n includedSMS Int?\n deviceModel String?\n deviceImei String?\n simCards SimCard[]\n // Legacy-Felder (für Abwärtskompatibilität, werden durch simCards ersetzt)\n phoneNumber String?\n simCardNumber String?\n}\n\nmodel SimCard {\n id Int @id @default(autoincrement())\n mobileDetailsId Int\n mobileDetails MobileContractDetails @relation(fields: [mobileDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String? // Rufnummer\n simCardNumber String? // SIM-Kartennummer\n pin String? // PIN (verschlüsselt gespeichert)\n puk String? // PUK (verschlüsselt gespeichert)\n isMultisim Boolean @default(false) // Ist dies eine Multisim-Karte?\n isMain Boolean @default(false) // Ist dies die Hauptkarte?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TV CONTRACT DETAILS ====================\n\nmodel TvContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n receiverModel String?\n smartcardNumber String?\n package String?\n}\n\n// ==================== CAR INSURANCE DETAILS ====================\n\nenum InsuranceType {\n LIABILITY\n PARTIAL\n FULL\n}\n\nmodel CarInsuranceDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n licensePlate String?\n hsn String?\n tsn String?\n vin String?\n vehicleType String?\n firstRegistration DateTime?\n noClaimsClass String?\n insuranceType InsuranceType @default(LIABILITY)\n deductiblePartial Float?\n deductibleFull Float?\n policyNumber String?\n previousInsurer String?\n}\n", - "inlineSchemaHash": "78e1ffc1151c8ed5044757206fc5cc6883ede2dea13cc396805b105375e30f1c", + "inlineSchema": "generator client {\n provider = \"prisma-client-js\"\n}\n\ndatasource db {\n provider = \"mysql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ==================== EMAIL LOG ====================\n\nmodel EmailLog {\n id Int @id @default(autoincrement())\n // Absender & Empfänger\n fromAddress String // Absender-E-Mail\n toAddress String // Empfänger-E-Mail\n subject String // Betreff\n // Versand-Kontext\n context String // z.B. \"consent-link\", \"authorization-request\", \"customer-email\"\n customerId Int? // Zugehöriger Kunde (falls vorhanden)\n triggeredBy String? // Wer hat den Versand ausgelöst (User-Email)\n // SMTP-Details\n smtpServer String // SMTP-Server\n smtpPort Int // SMTP-Port\n smtpEncryption String // SSL, STARTTLS, NONE\n smtpUser String // SMTP-Benutzername\n // Ergebnis\n success Boolean // Erfolgreich?\n messageId String? // Message-ID aus SMTP-Antwort\n errorMessage String? @db.Text // Fehlermeldung bei Fehler\n smtpResponse String? @db.Text // SMTP-Server-Antwort\n // Zeitstempel\n sentAt DateTime @default(now())\n\n @@index([sentAt])\n @@index([customerId])\n @@index([success])\n}\n\n// ==================== APP SETTINGS ====================\n\nmodel AppSetting {\n id Int @id @default(autoincrement())\n key String @unique\n value String @db.Text\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== USERS & AUTH ====================\n\nmodel User {\n id Int @id @default(autoincrement())\n email String @unique\n password String\n firstName String\n lastName String\n isActive Boolean @default(true)\n tokenInvalidatedAt DateTime? // Zeitpunkt ab dem alle Tokens ungültig sind (für Zwangslogout bei Rechteänderung)\n\n // Messaging-Kanäle (für Datenschutz-Link-Versand)\n whatsappNumber String?\n telegramUsername String?\n signalNumber String?\n\n customerId Int? @unique\n customer Customer? @relation(fields: [customerId], references: [id])\n roles UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Role {\n id Int @id @default(autoincrement())\n name String @unique\n description String?\n permissions RolePermission[]\n users UserRole[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel Permission {\n id Int @id @default(autoincrement())\n resource String\n action String\n roles RolePermission[]\n\n @@unique([resource, action])\n}\n\nmodel RolePermission {\n roleId Int\n permissionId Int\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)\n\n @@id([roleId, permissionId])\n}\n\nmodel UserRole {\n userId Int\n roleId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)\n\n @@id([userId, roleId])\n}\n\n// ==================== CUSTOMERS ====================\n\nenum CustomerType {\n PRIVATE\n BUSINESS\n}\n\nmodel Customer {\n id Int @id @default(autoincrement())\n customerNumber String @unique\n type CustomerType @default(PRIVATE)\n salutation String?\n firstName String\n lastName String\n companyName String?\n foundingDate DateTime? // Gründungsdatum (für Firmen)\n birthDate DateTime?\n birthPlace String?\n email String?\n phone String?\n mobile String?\n taxNumber String?\n businessRegistrationPath String? // PDF-Pfad zur Gewerbeanmeldung\n commercialRegisterPath String? // PDF-Pfad zum Handelsregisterauszug\n commercialRegisterNumber String? // Handelsregisternummer (Text)\n privacyPolicyPath String? // PDF-Pfad zur Datenschutzerklärung (für alle Kunden)\n consentHash String? @unique // Permanenter Hash für öffentlichen Einwilligungslink /datenschutz/\n notes String? @db.Text\n\n // ===== Portal-Zugangsdaten =====\n portalEnabled Boolean @default(false) // Portal aktiviert?\n portalEmail String? @unique // Portal-Login E-Mail\n portalPasswordHash String? // Gehashtes Passwort (für Login)\n portalPasswordEncrypted String? // Verschlüsseltes Passwort (für Anzeige)\n portalLastLogin DateTime? // Letzte Anmeldung\n\n user User?\n addresses Address[]\n bankCards BankCard[]\n identityDocuments IdentityDocument[]\n meters Meter[]\n stressfreiEmails StressfreiEmail[]\n contracts Contract[]\n\n // Vertreter-Beziehungen (Kunde kann für andere Kunden handeln)\n representingFor CustomerRepresentative[] @relation(\"RepresentativeCustomer\")\n representedBy CustomerRepresentative[] @relation(\"RepresentedCustomer\")\n\n // Vollmachten\n authorizationsGiven RepresentativeAuthorization[] @relation(\"AuthorizationCustomer\")\n authorizationsReceived RepresentativeAuthorization[] @relation(\"AuthorizationRepresentative\")\n\n // DSGVO: Einwilligungen\n consents CustomerConsent[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CUSTOMER REPRESENTATIVES ====================\n// Vertretungsbeziehung: Ein Kunde kann die Verträge eines anderen Kunden einsehen\n// z.B. Sohn (representativeId) kann Verträge der Mutter (customerId) sehen\n\nmodel CustomerRepresentative {\n id Int @id @default(autoincrement())\n customerId Int // Der Kunde, dessen Verträge eingesehen werden (z.B. Mutter)\n customer Customer @relation(\"RepresentedCustomer\", fields: [customerId], references: [id], onDelete: Cascade)\n representativeId Int // Der Kunde, der einsehen darf (z.B. Sohn)\n representative Customer @relation(\"RepresentativeCustomer\", fields: [representativeId], references: [id], onDelete: Cascade)\n notes String? // Notizen zur Vertretung\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, representativeId]) // Keine doppelten Einträge\n}\n\n// ==================== VOLLMACHTEN ====================\n// Vollmacht: Kunde B erteilt Kunde A die Vollmacht, seine Daten einzusehen\n// Ohne Vollmacht kann der Vertreter die Verträge des Kunden NICHT sehen\n\nmodel RepresentativeAuthorization {\n id Int @id @default(autoincrement())\n customerId Int // Der Kunde, der die Vollmacht erteilt (z.B. Mutter)\n customer Customer @relation(\"AuthorizationCustomer\", fields: [customerId], references: [id], onDelete: Cascade)\n representativeId Int // Der Vertreter, der Zugriff bekommt (z.B. Sohn)\n representative Customer @relation(\"AuthorizationRepresentative\", fields: [representativeId], references: [id], onDelete: Cascade)\n isGranted Boolean @default(false) // Vollmacht erteilt?\n grantedAt DateTime? // Wann erteilt\n withdrawnAt DateTime? // Wann widerrufen\n source String? // Quelle: 'portal', 'papier', 'crm-backend'\n documentPath String? // PDF-Upload der unterschriebenen Vollmacht\n notes String? @db.Text // Notizen\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, representativeId]) // Eine Vollmacht pro Paar\n}\n\n// ==================== ADDRESSES ====================\n\nenum AddressType {\n DELIVERY_RESIDENCE\n BILLING\n}\n\nmodel Address {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type AddressType @default(DELIVERY_RESIDENCE)\n street String\n houseNumber String\n postalCode String\n city String\n country String @default(\"Deutschland\")\n isDefault Boolean @default(false)\n contractsAsDelivery Contract[] @relation(\"DeliveryAddress\")\n contractsAsBilling Contract[] @relation(\"BillingAddress\")\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== BANK CARDS ====================\n\nmodel BankCard {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n accountHolder String\n iban String\n bic String?\n bankName String?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== IDENTITY DOCUMENTS ====================\n\nenum DocumentType {\n ID_CARD\n PASSPORT\n DRIVERS_LICENSE\n OTHER\n}\n\nmodel IdentityDocument {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type DocumentType @default(ID_CARD)\n documentNumber String\n issuingAuthority String?\n issueDate DateTime?\n expiryDate DateTime?\n documentPath String? // Pfad zur hochgeladenen PDF\n isActive Boolean @default(true)\n // Führerschein-spezifische Felder\n licenseClasses String? // z.B. \"B, BE, AM, L\" - kommasepariert\n licenseIssueDate DateTime? // Datum des Führerscheinerwerbs (Klasse B)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== EMAIL PROVIDER CONFIG (Plesk, cPanel etc.) ====================\n\nenum EmailProviderType {\n PLESK\n CPANEL\n DIRECTADMIN\n}\n\n// Verschlüsselungstyp für E-Mail-Verbindungen\nenum MailEncryption {\n SSL // Implicit SSL/TLS (Ports 465/993) - Verschlüsselung von Anfang an\n STARTTLS // STARTTLS (Ports 587/143) - Startet unverschlüsselt, dann Upgrade\n NONE // Keine Verschlüsselung (Ports 25/143)\n}\n\nmodel EmailProviderConfig {\n id Int @id @default(autoincrement())\n name String @unique // z.B. \"Plesk Hauptserver\"\n type EmailProviderType\n apiUrl String // API-URL (z.B. https://server.de:8443)\n apiKey String? // API-Key (verschlüsselt)\n username String? // Benutzername für API\n passwordEncrypted String? // Passwort (verschlüsselt)\n domain String // Domain für E-Mails (z.B. stressfrei-wechseln.de)\n defaultForwardEmail String? // Standard-Weiterleitungsadresse (unsere eigene)\n\n // IMAP/SMTP-Server für E-Mail-Client (optional, default: mail.{domain})\n imapServer String? // z.B. \"mail.stressfrei-wechseln.de\"\n imapPort Int? @default(993)\n smtpServer String?\n smtpPort Int? @default(465)\n\n // Verschlüsselungs-Einstellungen\n imapEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n smtpEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE\n allowSelfSignedCerts Boolean @default(false) // Selbstsignierte Zertifikate erlauben\n\n // System-E-Mail für automatisierte Nachrichten (z.B. DSGVO Consent-Links)\n systemEmailAddress String? // z.B. \"info@stressfrei-wechseln.de\"\n systemEmailPasswordEncrypted String? // Passwort (verschlüsselt)\n\n isActive Boolean @default(true)\n isDefault Boolean @default(false) // Standard-Provider\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== STRESSFREI-WECHSELN EMAIL ADDRESSES ====================\n\nmodel StressfreiEmail {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n email String // Die Weiterleitungs-E-Mail-Adresse\n platform String? // Für welche Plattform (z.B. \"Freenet\", \"Klarmobil\")\n notes String? @db.Text // Optionale Notizen\n isActive Boolean @default(true)\n isProvisioned Boolean @default(false) // Wurde bei Provider angelegt?\n provisionedAt DateTime? // Wann wurde provisioniert?\n provisionError String? @db.Text // Fehlermeldung falls Provisionierung fehlschlug\n\n // Mailbox-Zugangsdaten (für IMAP/SMTP-Zugang)\n hasMailbox Boolean @default(false) // Hat echte Mailbox (nicht nur Weiterleitung)?\n emailPasswordEncrypted String? // Verschlüsseltes Mailbox-Passwort (AES-256-GCM)\n\n contracts Contract[] // Verträge die diese E-Mail als Benutzername verwenden\n cachedEmails CachedEmail[] // Gecachte E-Mails aus dieser Mailbox\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CACHED EMAILS (E-Mail-Client) ====================\n\nenum EmailFolder {\n INBOX\n SENT\n}\n\nmodel CachedEmail {\n id Int @id @default(autoincrement())\n stressfreiEmailId Int\n stressfreiEmail StressfreiEmail @relation(fields: [stressfreiEmailId], references: [id], onDelete: Cascade)\n\n // Ordner (Posteingang oder Gesendet)\n folder EmailFolder @default(INBOX)\n\n // IMAP-Identifikation\n messageId String // RFC 5322 Message-ID\n uid Int // IMAP UID (für Synchronisierung, bei SENT = 0)\n\n // E-Mail-Metadaten\n subject String?\n fromAddress String\n fromName String?\n toAddresses String @db.Text // JSON Array\n ccAddresses String? @db.Text // JSON Array\n receivedAt DateTime\n\n // Inhalt\n textBody String? @db.LongText\n htmlBody String? @db.LongText\n hasAttachments Boolean @default(false)\n attachmentNames String? @db.Text // JSON Array\n\n // Vertragszuordnung\n contractId Int?\n contract Contract? @relation(fields: [contractId], references: [id], onDelete: SetNull)\n assignedAt DateTime?\n assignedBy Int? // User ID der die Zuordnung gemacht hat\n isAutoAssigned Boolean @default(false) // true = automatisch beim Senden aus Vertrag\n\n // Flags\n isRead Boolean @default(false)\n isStarred Boolean @default(false)\n\n // Papierkorb\n isDeleted Boolean @default(false) // Im Papierkorb?\n deletedAt DateTime? // Wann gelöscht?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([stressfreiEmailId, messageId, folder]) // Folder hinzugefügt: gleiche MessageID kann in INBOX und SENT existieren\n @@index([contractId])\n @@index([stressfreiEmailId, folder, receivedAt])\n @@index([stressfreiEmailId, isDeleted]) // Für Papierkorb-Abfragen\n}\n\n// ==================== METERS (Energy) ====================\n\nenum MeterType {\n ELECTRICITY\n GAS\n}\n\nmodel Meter {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n meterNumber String\n type MeterType\n location String?\n isActive Boolean @default(true)\n readings MeterReading[]\n energyDetails EnergyContractDetails[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel MeterReading {\n id Int @id @default(autoincrement())\n meterId Int\n meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade)\n readingDate DateTime\n value Float\n unit String @default(\"kWh\")\n notes String?\n // Meldung & Übertragung\n reportedBy String? // Wer hat gemeldet? (E-Mail des Portal-Kunden oder Mitarbeiter)\n status MeterReadingStatus @default(RECORDED)\n transferredAt DateTime? // Wann wurde der Stand an den Anbieter übertragen?\n transferredBy String? // Wer hat übertragen?\n createdAt DateTime @default(now())\n}\n\nenum MeterReadingStatus {\n RECORDED // Erfasst (vom Mitarbeiter)\n REPORTED // Vom Kunden gemeldet (Portal)\n TRANSFERRED // An Anbieter übertragen\n}\n\n// ==================== SALES PLATFORMS ====================\n\nmodel SalesPlatform {\n id Int @id @default(autoincrement())\n name String @unique\n contactInfo String? @db.Text\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CANCELLATION PERIODS ====================\n\nmodel CancellationPeriod {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"14T\", \"1M\", \"3M\", \"12M\", \"1J\"\n description String // z.B. \"14 Tage\", \"1 Monat\", \"3 Monate\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT DURATIONS ====================\n\nmodel ContractDuration {\n id Int @id @default(autoincrement())\n code String @unique // z.B. \"12M\", \"24M\", \"1J\", \"2J\"\n description String // z.B. \"12 Monate\", \"24 Monate\", \"1 Jahr\"\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== PROVIDERS (Anbieter) ====================\n\nmodel Provider {\n id Int @id @default(autoincrement())\n name String @unique // Anbietername\n portalUrl String? // Kundenkontourl (Login-Seite)\n usernameFieldName String? // Benutzernamefeld (z.B. \"email\", \"username\")\n passwordFieldName String? // Kennwortfeld (z.B. \"password\", \"pwd\")\n isActive Boolean @default(true)\n tariffs Tariff[]\n contracts Contract[]\n previousContracts Contract[] @relation(\"PreviousProvider\") // Verträge wo dieser Provider Altanbieter ist\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TARIFFS (Tarife) ====================\n\nmodel Tariff {\n id Int @id @default(autoincrement())\n providerId Int\n provider Provider @relation(fields: [providerId], references: [id], onDelete: Cascade)\n name String // Tarifname\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([providerId, name]) // Eindeutiger Tarif pro Anbieter\n}\n\n// ==================== CONTRACT CATEGORIES ====================\n\nmodel ContractCategory {\n id Int @id @default(autoincrement())\n code String @unique // Technischer Code (z.B. ELECTRICITY, GAS)\n name String // Anzeigename (z.B. Strom, Gas)\n icon String? // Icon-Name für UI (z.B. \"Zap\", \"Flame\")\n color String? // Farbe für UI (z.B. \"#FFC107\")\n sortOrder Int @default(0)\n isActive Boolean @default(true)\n contracts Contract[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACTS ====================\n\n// Legacy Enum - wird durch ContractCategory ersetzt\nenum ContractType {\n ELECTRICITY\n GAS\n DSL\n CABLE\n FIBER\n MOBILE\n TV\n CAR_INSURANCE\n}\n\nenum ContractStatus {\n DRAFT\n PENDING\n ACTIVE\n CANCELLED\n EXPIRED\n DEACTIVATED\n}\n\nmodel Contract {\n id Int @id @default(autoincrement())\n contractNumber String @unique\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n type ContractType\n status ContractStatus @default(DRAFT)\n\n // Neue konfigurierbare Kategorie (ersetzt langfristig das type-Enum)\n contractCategoryId Int?\n contractCategory ContractCategory? @relation(fields: [contractCategoryId], references: [id])\n\n // Lieferadresse\n addressId Int?\n address Address? @relation(\"DeliveryAddress\", fields: [addressId], references: [id])\n\n // Rechnungsadresse (falls leer, wird Lieferadresse verwendet)\n billingAddressId Int?\n billingAddress Address? @relation(\"BillingAddress\", fields: [billingAddressId], references: [id])\n\n bankCardId Int?\n bankCard BankCard? @relation(fields: [bankCardId], references: [id])\n\n identityDocumentId Int?\n identityDocument IdentityDocument? @relation(fields: [identityDocumentId], references: [id])\n\n salesPlatformId Int?\n salesPlatform SalesPlatform? @relation(fields: [salesPlatformId], references: [id])\n\n cancellationPeriodId Int?\n cancellationPeriod CancellationPeriod? @relation(fields: [cancellationPeriodId], references: [id])\n\n contractDurationId Int?\n contractDuration ContractDuration? @relation(fields: [contractDurationId], references: [id])\n\n previousContractId Int? @unique\n previousContract Contract? @relation(\"ContractHistory\", fields: [previousContractId], references: [id])\n followUpContract Contract? @relation(\"ContractHistory\")\n\n // Altanbieter-Daten (nur wenn kein Vorgängervertrag existiert)\n previousProviderId Int?\n previousProvider Provider? @relation(\"PreviousProvider\", fields: [previousProviderId], references: [id])\n previousCustomerNumber String? // Kundennummer beim Altanbieter\n previousContractNumber String? // Vertragsnummer beim Altanbieter\n\n // Anbieter & Tarif (neue Verknüpfung)\n providerId Int?\n provider Provider? @relation(fields: [providerId], references: [id])\n tariffId Int?\n tariff Tariff? @relation(fields: [tariffId], references: [id])\n\n // Legacy-Felder (für Abwärtskompatibilität)\n providerName String?\n tariffName String?\n customerNumberAtProvider String?\n contractNumberAtProvider String? // Vertragsnummer beim Anbieter\n priceFirst12Months String? // Preis erste 12 Monate\n priceFrom13Months String? // Preis ab 13. Monat\n priceAfter24Months String? // Preis nach 24 Monaten\n\n startDate DateTime?\n endDate DateTime? // Wird aus startDate + contractDuration berechnet\n commission Float?\n\n // Kündigungsdokumente\n cancellationLetterPath String? // Kündigungsschreiben PDF\n cancellationConfirmationPath String? // Kündigungsbestätigung PDF\n cancellationLetterOptionsPath String? // Kündigungsschreiben Optionen PDF\n cancellationConfirmationOptionsPath String? // Kündigungsbestätigung Optionen PDF\n\n // Kündigungsdaten\n cancellationConfirmationDate DateTime? // Kündigungsbestätigungsdatum\n cancellationConfirmationOptionsDate DateTime? // Kündigungsbestätigungsoptionendatum\n wasSpecialCancellation Boolean @default(false) // Wurde sondergekündigt?\n\n portalUsername String?\n portalPasswordEncrypted String?\n\n // Stressfrei-Wechseln E-Mail als Benutzername (Alternative zu portalUsername)\n stressfreiEmailId Int?\n stressfreiEmail StressfreiEmail? @relation(fields: [stressfreiEmailId], references: [id])\n\n // Snooze: Vertrag zurückstellen bis Datum (für Cockpit)\n nextReviewDate DateTime? // Erneute Prüfung am\n\n notes String? @db.Text\n\n energyDetails EnergyContractDetails?\n internetDetails InternetContractDetails?\n mobileDetails MobileContractDetails?\n tvDetails TvContractDetails?\n carInsuranceDetails CarInsuranceDetails?\n\n tasks ContractTask[]\n assignedEmails CachedEmail[] // Zugeordnete E-Mails aus dem E-Mail-Client\n historyEntries ContractHistoryEntry[]\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== CONTRACT HISTORY ====================\n\nmodel ContractHistoryEntry {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String // Kurzbeschreibung (z.B. \"Folgevertrag erstellt\", \"kWh auf 18000 erhöht\")\n description String? @db.Text // Längere Beschreibung (optional)\n isAutomatic Boolean @default(false) // true = automatisch erstellt, false = manuell\n createdBy String // E-Mail des Erstellers\n createdAt DateTime @default(now())\n}\n\n// ==================== CONTRACT TASKS ====================\n\nenum ContractTaskStatus {\n OPEN\n COMPLETED\n}\n\nmodel ContractTask {\n id Int @id @default(autoincrement())\n contractId Int\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n title String\n description String? @db.Text\n status ContractTaskStatus @default(OPEN)\n visibleInPortal Boolean @default(false)\n createdBy String? // Name des Erstellers\n completedAt DateTime?\n subtasks ContractTaskSubtask[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\nmodel ContractTaskSubtask {\n id Int @id @default(autoincrement())\n taskId Int\n task ContractTask @relation(fields: [taskId], references: [id], onDelete: Cascade)\n title String\n status ContractTaskStatus @default(OPEN)\n createdBy String?\n completedAt DateTime?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== ENERGY CONTRACT DETAILS ====================\n\nenum InvoiceType {\n INTERIM // Zwischenrechnung\n FINAL // Schlussrechnung\n NOT_AVAILABLE // Rechnung nicht mehr zu bekommen\n}\n\nmodel EnergyContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n meterId Int?\n meter Meter? @relation(fields: [meterId], references: [id])\n maloId String? // Marktlokations-ID\n annualConsumption Float? // kWh für Strom, m³ für Gas\n annualConsumptionKwh Float? // kWh für Gas (zusätzlich zu m³)\n basePrice Float? // €/Monat\n unitPrice Float? // €/kWh (Arbeitspreis)\n bonus Float?\n previousProviderName String?\n previousCustomerNumber String?\n invoices Invoice[] // Rechnungen\n}\n\nmodel Invoice {\n id Int @id @default(autoincrement())\n energyContractDetailsId Int\n energyContractDetails EnergyContractDetails @relation(fields: [energyContractDetailsId], references: [id], onDelete: Cascade)\n invoiceDate DateTime\n invoiceType InvoiceType\n documentPath String? // Pflicht, außer bei NOT_AVAILABLE\n notes String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([energyContractDetailsId])\n}\n\n// ==================== INTERNET CONTRACT DETAILS ====================\n\nmodel InternetContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n downloadSpeed Int?\n uploadSpeed Int?\n routerModel String?\n routerSerialNumber String?\n installationDate DateTime?\n // Internet-Zugangsdaten\n internetUsername String?\n internetPasswordEncrypted String? // Verschlüsselt gespeichert\n // Glasfaser-spezifisch\n homeId String?\n // Vodafone DSL/Kabel spezifisch\n activationCode String?\n phoneNumbers PhoneNumber[]\n}\n\nmodel PhoneNumber {\n id Int @id @default(autoincrement())\n internetContractDetailsId Int\n internetDetails InternetContractDetails @relation(fields: [internetContractDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String\n isMain Boolean @default(false)\n // SIP-Zugangsdaten\n sipUsername String?\n sipPasswordEncrypted String? // Verschlüsselt gespeichert\n sipServer String?\n}\n\n// ==================== MOBILE CONTRACT DETAILS ====================\n\nmodel MobileContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n requiresMultisim Boolean @default(false) // Multisim erforderlich?\n dataVolume Float?\n includedMinutes Int?\n includedSMS Int?\n deviceModel String?\n deviceImei String?\n simCards SimCard[]\n // Legacy-Felder (für Abwärtskompatibilität, werden durch simCards ersetzt)\n phoneNumber String?\n simCardNumber String?\n}\n\nmodel SimCard {\n id Int @id @default(autoincrement())\n mobileDetailsId Int\n mobileDetails MobileContractDetails @relation(fields: [mobileDetailsId], references: [id], onDelete: Cascade)\n phoneNumber String? // Rufnummer\n simCardNumber String? // SIM-Kartennummer\n pin String? // PIN (verschlüsselt gespeichert)\n puk String? // PUK (verschlüsselt gespeichert)\n isMultisim Boolean @default(false) // Ist dies eine Multisim-Karte?\n isMain Boolean @default(false) // Ist dies die Hauptkarte?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\n\n// ==================== TV CONTRACT DETAILS ====================\n\nmodel TvContractDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n receiverModel String?\n smartcardNumber String?\n package String?\n}\n\n// ==================== CAR INSURANCE DETAILS ====================\n\nenum InsuranceType {\n LIABILITY\n PARTIAL\n FULL\n}\n\nmodel CarInsuranceDetails {\n id Int @id @default(autoincrement())\n contractId Int @unique\n contract Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)\n licensePlate String?\n hsn String?\n tsn String?\n vin String?\n vehicleType String?\n firstRegistration DateTime?\n noClaimsClass String?\n insuranceType InsuranceType @default(LIABILITY)\n deductiblePartial Float?\n deductibleFull Float?\n policyNumber String?\n previousInsurer String?\n}\n\n// ==================== AUDIT LOGGING (DSGVO) ====================\n\nenum AuditAction {\n CREATE\n READ\n UPDATE\n DELETE\n EXPORT // DSGVO-Datenexport\n ANONYMIZE // Recht auf Vergessenwerden\n LOGIN\n LOGOUT\n LOGIN_FAILED\n}\n\nenum AuditSensitivity {\n LOW // Einstellungen, Plattformen\n MEDIUM // Verträge, Tarife\n HIGH // Kundendaten, Bankdaten\n CRITICAL // Authentifizierung, Ausweisdokumente\n}\n\nmodel AuditLog {\n id Int @id @default(autoincrement())\n\n // Wer\n userId Int? // Staff User (null bei Kundenportal/System)\n userEmail String\n userRole String? @db.Text // Rolle zum Zeitpunkt der Aktion\n customerId Int? // Bei Kundenportal-Zugriff\n isCustomerPortal Boolean @default(false)\n\n // Was\n action AuditAction\n sensitivity AuditSensitivity @default(MEDIUM)\n\n // Welche Ressource\n resourceType String // Prisma Model Name\n resourceId String? // ID des Datensatzes\n resourceLabel String? // Lesbare Bezeichnung\n\n // Kontext\n endpoint String // API-Pfad\n httpMethod String // GET, POST, PUT, DELETE\n ipAddress String\n userAgent String? @db.Text\n\n // Änderungen (JSON, bei sensiblen Daten verschlüsselt)\n changesBefore String? @db.LongText\n changesAfter String? @db.LongText\n changesEncrypted Boolean @default(false)\n\n // DSGVO\n dataSubjectId Int? // Betroffene Person (für Reports)\n legalBasis String? // Rechtsgrundlage\n\n // Status\n success Boolean @default(true)\n errorMessage String? @db.Text\n durationMs Int?\n\n // Unveränderlichkeit (Hash-Kette)\n createdAt DateTime @default(now())\n hash String? // SHA-256 Hash des Eintrags\n previousHash String? // Hash des vorherigen Eintrags\n\n @@index([userId])\n @@index([customerId])\n @@index([resourceType, resourceId])\n @@index([dataSubjectId])\n @@index([action])\n @@index([createdAt])\n @@index([sensitivity])\n}\n\n// ==================== CONSENT MANAGEMENT (DSGVO) ====================\n\nenum ConsentType {\n DATA_PROCESSING // Grundlegende Datenverarbeitung\n MARKETING_EMAIL // E-Mail-Marketing\n MARKETING_PHONE // Telefon-Marketing\n DATA_SHARING_PARTNER // Weitergabe an Partner\n}\n\nenum ConsentStatus {\n GRANTED\n WITHDRAWN\n PENDING\n}\n\nmodel CustomerConsent {\n id Int @id @default(autoincrement())\n customerId Int\n customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)\n\n consentType ConsentType\n status ConsentStatus @default(PENDING)\n\n grantedAt DateTime?\n withdrawnAt DateTime?\n source String? // \"portal\", \"telefon\", \"papier\", \"email\"\n documentPath String? // Unterschriebenes Dokument\n version String? // Version der Datenschutzerklärung\n ipAddress String?\n\n createdBy String // User der die Einwilligung erfasst hat\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([customerId, consentType])\n @@index([customerId])\n @@index([consentType])\n @@index([status])\n}\n\n// ==================== DATA DELETION REQUESTS (DSGVO) ====================\n\nenum DeletionRequestStatus {\n PENDING // Anfrage eingegangen\n IN_PROGRESS // Wird bearbeitet\n COMPLETED // Abgeschlossen\n PARTIALLY_COMPLETED // Teildaten behalten (rechtliche Gründe)\n REJECTED // Abgelehnt\n}\n\nmodel DataDeletionRequest {\n id Int @id @default(autoincrement())\n customerId Int\n\n status DeletionRequestStatus @default(PENDING)\n requestedAt DateTime @default(now())\n requestSource String // \"email\", \"portal\", \"brief\"\n requestedBy String // Wer hat angefragt\n\n processedAt DateTime?\n processedBy String? // Mitarbeiter der bearbeitet hat\n\n deletedData String? @db.LongText // JSON: Was wurde gelöscht\n retainedData String? @db.LongText // JSON: Was wurde behalten + Grund\n retentionReason String? @db.Text // Begründung für Aufbewahrung\n\n proofDocument String? // Pfad zum Löschnachweis-PDF\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([customerId])\n @@index([status])\n @@index([requestedAt])\n}\n\n// ==================== AUDIT RETENTION POLICIES ====================\n\nmodel AuditRetentionPolicy {\n id Int @id @default(autoincrement())\n resourceType String // \"*\" für Standard, oder spezifischer Model-Name\n sensitivity AuditSensitivity?\n retentionDays Int // Aufbewahrungsfrist in Tagen (z.B. 3650 = 10 Jahre)\n description String?\n legalBasis String? // Gesetzliche Grundlage (z.B. \"AO §147\", \"HGB §257\")\n isActive Boolean @default(true)\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([resourceType, sensitivity])\n}\n", + "inlineSchemaHash": "63bbf34a125be87986e47fb5fb85acd2762dfb44da1ec90d4d1c15dc2c2a2083", "copyEngine": true } @@ -735,7 +905,7 @@ if (!fs.existsSync(path.join(__dirname, 'schema.prisma'))) { config.isBundled = true } -config.runtimeDataModel = JSON.parse("{\"models\":{\"AppSetting\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"key\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"User\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"password\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tokenInvalidatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Role\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissions\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"users\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Permission\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resource\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"action\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[[\"resource\",\"action\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"resource\",\"action\"]}],\"isGenerated\":false},\"RolePermission\":{\"dbName\":null,\"fields\":[{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissionId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permission\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Permission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[\"permissionId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"roleId\",\"permissionId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"UserRole\":{\"dbName\":null,\"fields\":[{\"name\":\"userId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[\"userId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"userId\",\"roleId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Customer\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"CustomerType\",\"default\":\"PRIVATE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salutation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"companyName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"foundingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthPlace\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phone\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobile\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taxNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"businessRegistrationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"privacyPolicyPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEnabled\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalLastLogin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addresses\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocuments\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meters\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representingFor\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representedBy\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CustomerRepresentative\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representativeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representative\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[\"representativeId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"representativeId\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"representativeId\"]}],\"isGenerated\":false},\"Address\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"AddressType\",\"default\":\"DELIVERY_RESIDENCE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"street\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"houseNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"postalCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"city\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"country\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"Deutschland\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsDelivery\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsBilling\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"BankCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"accountHolder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"iban\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"IdentityDocument\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DocumentType\",\"default\":\"ID_CARD\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issuingAuthority\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseClasses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseIssueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EmailProviderConfig\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EmailProviderType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"username\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"domain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"defaultForwardEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":993,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":465,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"allowSelfSignedCerts\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"StressfreiEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"platform\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isProvisioned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionError\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasMailbox\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"emailPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cachedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CachedEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"folder\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"EmailFolder\",\"default\":\"INBOX\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"messageId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uid\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subject\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"toAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ccAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receivedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"textBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"htmlBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasAttachments\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"attachmentNames\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"SetNull\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutoAssigned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isRead\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isStarred\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDeleted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deletedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"stressfreiEmailId\",\"messageId\",\"folder\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"stressfreiEmailId\",\"messageId\",\"folder\"]}],\"isGenerated\":false},\"Meter\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"location\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readings\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterReading\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MeterReading\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unit\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"kWh\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SalesPlatform\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contactInfo\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CancellationPeriod\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractDuration\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Provider\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"usernameFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffs\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Tariff\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"providerId\",\"name\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"providerId\",\"name\"]}],\"isGenerated\":false},\"ContractCategory\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"icon\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"color\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":0,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Contract\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractStatus\",\"default\":\"DRAFT\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategoryId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategory\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractCategory\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[\"contractCategoryId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"address\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[\"addressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddress\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[\"billingAddressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCardId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCard\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[\"bankCardId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocumentId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocument\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[\"identityDocumentId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatformId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatform\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SalesPlatform\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[\"salesPlatformId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriodId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriod\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CancellationPeriod\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[\"cancellationPeriodId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDurationId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDuration\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractDuration\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[\"contractDurationId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[\"previousContractId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"followUpContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProvider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[\"previousProviderId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariff\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[\"tariffId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFirst12Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFrom13Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceAfter24Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"startDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"endDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commission\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"wasSpecialCancellation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"nextReviewDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tvDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"TvContractDetails\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"carInsuranceDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CarInsuranceDetails\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"historyEntries\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractHistoryEntry\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractHistoryEntry\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutomatic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"visibleInPortal\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subtasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTaskSubtask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTaskSubtask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taskId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"task\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[\"taskId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EnergyContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"maloId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumption\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumptionKwh\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"basePrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unitPrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bonus\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoices\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Invoice\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Invoice\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[\"energyContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InvoiceType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"InternetContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"downloadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uploadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerSerialNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"installationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"homeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"activationCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumbers\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"PhoneNumber\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"PhoneNumber\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[\"internetContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MobileContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requiresMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"dataVolume\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedMinutes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedSMS\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceImei\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SimCard\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SimCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[\"mobileDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"pin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"puk\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"TvContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receiverModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smartcardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"package\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CarInsuranceDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licensePlate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vehicleType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstRegistration\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"noClaimsClass\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"insuranceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"InsuranceType\",\"default\":\"LIABILITY\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductiblePartial\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductibleFull\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"policyNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousInsurer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false}},\"enums\":{\"CustomerType\":{\"values\":[{\"name\":\"PRIVATE\",\"dbName\":null},{\"name\":\"BUSINESS\",\"dbName\":null}],\"dbName\":null},\"AddressType\":{\"values\":[{\"name\":\"DELIVERY_RESIDENCE\",\"dbName\":null},{\"name\":\"BILLING\",\"dbName\":null}],\"dbName\":null},\"DocumentType\":{\"values\":[{\"name\":\"ID_CARD\",\"dbName\":null},{\"name\":\"PASSPORT\",\"dbName\":null},{\"name\":\"DRIVERS_LICENSE\",\"dbName\":null},{\"name\":\"OTHER\",\"dbName\":null}],\"dbName\":null},\"EmailProviderType\":{\"values\":[{\"name\":\"PLESK\",\"dbName\":null},{\"name\":\"CPANEL\",\"dbName\":null},{\"name\":\"DIRECTADMIN\",\"dbName\":null}],\"dbName\":null},\"MailEncryption\":{\"values\":[{\"name\":\"SSL\",\"dbName\":null},{\"name\":\"STARTTLS\",\"dbName\":null},{\"name\":\"NONE\",\"dbName\":null}],\"dbName\":null},\"EmailFolder\":{\"values\":[{\"name\":\"INBOX\",\"dbName\":null},{\"name\":\"SENT\",\"dbName\":null}],\"dbName\":null},\"MeterType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null}],\"dbName\":null},\"ContractType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null},{\"name\":\"DSL\",\"dbName\":null},{\"name\":\"CABLE\",\"dbName\":null},{\"name\":\"FIBER\",\"dbName\":null},{\"name\":\"MOBILE\",\"dbName\":null},{\"name\":\"TV\",\"dbName\":null},{\"name\":\"CAR_INSURANCE\",\"dbName\":null}],\"dbName\":null},\"ContractStatus\":{\"values\":[{\"name\":\"DRAFT\",\"dbName\":null},{\"name\":\"PENDING\",\"dbName\":null},{\"name\":\"ACTIVE\",\"dbName\":null},{\"name\":\"CANCELLED\",\"dbName\":null},{\"name\":\"EXPIRED\",\"dbName\":null},{\"name\":\"DEACTIVATED\",\"dbName\":null}],\"dbName\":null},\"ContractTaskStatus\":{\"values\":[{\"name\":\"OPEN\",\"dbName\":null},{\"name\":\"COMPLETED\",\"dbName\":null}],\"dbName\":null},\"InvoiceType\":{\"values\":[{\"name\":\"INTERIM\",\"dbName\":null},{\"name\":\"FINAL\",\"dbName\":null},{\"name\":\"NOT_AVAILABLE\",\"dbName\":null}],\"dbName\":null},\"InsuranceType\":{\"values\":[{\"name\":\"LIABILITY\",\"dbName\":null},{\"name\":\"PARTIAL\",\"dbName\":null},{\"name\":\"FULL\",\"dbName\":null}],\"dbName\":null}},\"types\":{}}") +config.runtimeDataModel = JSON.parse("{\"models\":{\"EmailLog\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"toAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subject\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"context\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"triggeredBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpEncryption\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpUser\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"success\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Boolean\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"messageId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"errorMessage\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpResponse\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sentAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"AppSetting\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"key\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"User\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"password\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tokenInvalidatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"whatsappNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"telegramUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"signalNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Role\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissions\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"users\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"UserRole\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Permission\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resource\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"action\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roles\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RolePermission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[[\"resource\",\"action\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"resource\",\"action\"]}],\"isGenerated\":false},\"RolePermission\":{\"dbName\":null,\"fields\":[{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permissionId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToRolePermission\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"permission\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Permission\",\"relationName\":\"PermissionToRolePermission\",\"relationFromFields\":[\"permissionId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"roleId\",\"permissionId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"UserRole\":{\"dbName\":null,\"fields\":[{\"name\":\"userId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"roleId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"UserToUserRole\",\"relationFromFields\":[\"userId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"role\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Role\",\"relationName\":\"RoleToUserRole\",\"relationFromFields\":[\"roleId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":{\"name\":null,\"fields\":[\"userId\",\"roleId\"]},\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Customer\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"CustomerType\",\"default\":\"PRIVATE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salutation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"lastName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"companyName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"foundingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"birthPlace\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phone\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobile\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taxNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"businessRegistrationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commercialRegisterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"privacyPolicyPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"consentHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEnabled\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalLastLogin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"user\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"User\",\"relationName\":\"CustomerToUser\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addresses\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocuments\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meters\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representingFor\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representedBy\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerRepresentative\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"authorizationsGiven\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RepresentativeAuthorization\",\"relationName\":\"AuthorizationCustomer\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"authorizationsReceived\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"RepresentativeAuthorization\",\"relationName\":\"AuthorizationRepresentative\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"consents\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CustomerConsent\",\"relationName\":\"CustomerToCustomerConsent\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CustomerRepresentative\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentedCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representativeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representative\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"RepresentativeCustomer\",\"relationFromFields\":[\"representativeId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"representativeId\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"representativeId\"]}],\"isGenerated\":false},\"RepresentativeAuthorization\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AuthorizationCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representativeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"representative\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AuthorizationRepresentative\",\"relationFromFields\":[\"representativeId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isGranted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"grantedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"withdrawnAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"source\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"representativeId\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"representativeId\"]}],\"isGenerated\":false},\"Address\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"AddressToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"AddressType\",\"default\":\"DELIVERY_RESIDENCE\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"street\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"houseNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"postalCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"city\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"country\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"Deutschland\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsDelivery\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractsAsBilling\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"BankCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"BankCardToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"accountHolder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"iban\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"IdentityDocument\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToIdentityDocument\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DocumentType\",\"default\":\"ID_CARD\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issuingAuthority\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"issueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"expiryDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseClasses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licenseIssueDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EmailProviderConfig\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EmailProviderType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"username\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"domain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"defaultForwardEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":993,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpPort\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":465,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"imapEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smtpEncryption\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MailEncryption\",\"default\":\"SSL\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"allowSelfSignedCerts\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"systemEmailAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"systemEmailPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDefault\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"StressfreiEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToStressfreiEmail\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"email\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"platform\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isProvisioned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provisionError\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasMailbox\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"emailPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cachedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CachedEmail\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"CachedEmailToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"folder\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"EmailFolder\",\"default\":\"INBOX\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"messageId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uid\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subject\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"fromName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"toAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ccAddresses\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receivedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"textBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"htmlBody\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hasAttachments\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"attachmentNames\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"SetNull\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutoAssigned\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isRead\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isStarred\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isDeleted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deletedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"stressfreiEmailId\",\"messageId\",\"folder\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"stressfreiEmailId\",\"messageId\",\"folder\"]}],\"isGenerated\":false},\"Meter\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToMeter\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"location\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readings\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MeterReading\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MeterReading\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"MeterToMeterReading\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"readingDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"value\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unit\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"String\",\"default\":\"kWh\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"reportedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"MeterReadingStatus\",\"default\":\"RECORDED\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"transferredAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"transferredBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SalesPlatform\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contactInfo\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CancellationPeriod\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractDuration\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Provider\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUrl\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"usernameFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"passwordFieldName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffs\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Tariff\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ProviderToTariff\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"providerId\",\"name\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"providerId\",\"name\"]}],\"isGenerated\":false},\"ContractCategory\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"code\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"name\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"icon\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"color\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":0,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contracts\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Contract\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"ContractToCustomer\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"type\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractStatus\",\"default\":\"DRAFT\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategoryId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractCategory\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractCategory\",\"relationName\":\"ContractToContractCategory\",\"relationFromFields\":[\"contractCategoryId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"addressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"address\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"DeliveryAddress\",\"relationFromFields\":[\"addressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddressId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"billingAddress\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Address\",\"relationName\":\"BillingAddress\",\"relationFromFields\":[\"billingAddressId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCardId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bankCard\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"BankCard\",\"relationName\":\"BankCardToContract\",\"relationFromFields\":[\"bankCardId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocumentId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"identityDocument\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"IdentityDocument\",\"relationName\":\"ContractToIdentityDocument\",\"relationFromFields\":[\"identityDocumentId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatformId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"salesPlatform\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SalesPlatform\",\"relationName\":\"ContractToSalesPlatform\",\"relationFromFields\":[\"salesPlatformId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriodId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationPeriod\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CancellationPeriod\",\"relationName\":\"CancellationPeriodToContract\",\"relationFromFields\":[\"cancellationPeriodId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDurationId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractDuration\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractDuration\",\"relationName\":\"ContractToContractDuration\",\"relationFromFields\":[\"contractDurationId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[\"previousContractId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"followUpContract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractHistory\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProvider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"PreviousProvider\",\"relationFromFields\":[\"previousProviderId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousContractNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"provider\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Provider\",\"relationName\":\"ContractToProvider\",\"relationFromFields\":[\"providerId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariff\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Tariff\",\"relationName\":\"ContractToTariff\",\"relationFromFields\":[\"tariffId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"providerName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tariffName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractNumberAtProvider\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFirst12Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceFrom13Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"priceAfter24Months\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"startDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"endDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"commission\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationLetterOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"cancellationConfirmationOptionsDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"wasSpecialCancellation\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"portalPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmailId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"stressfreiEmail\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"StressfreiEmail\",\"relationName\":\"ContractToStressfreiEmail\",\"relationFromFields\":[\"stressfreiEmailId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"nextReviewDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tvDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"TvContractDetails\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"carInsuranceDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CarInsuranceDetails\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"assignedEmails\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"CachedEmail\",\"relationName\":\"CachedEmailToContract\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"historyEntries\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractHistoryEntry\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractHistoryEntry\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractHistoryEntry\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isAutomatic\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToContractTask\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"visibleInPortal\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"subtasks\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTaskSubtask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"ContractTaskSubtask\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"taskId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"task\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ContractTask\",\"relationName\":\"ContractTaskToContractTaskSubtask\",\"relationFromFields\":[\"taskId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"title\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ContractTaskStatus\",\"default\":\"OPEN\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"EnergyContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToEnergyContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meterId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"meter\",\"kind\":\"object\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Meter\",\"relationName\":\"EnergyContractDetailsToMeter\",\"relationFromFields\":[\"meterId\"],\"relationToFields\":[\"id\"],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"maloId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumption\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"annualConsumptionKwh\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"basePrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"unitPrice\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"bonus\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousProviderName\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousCustomerNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoices\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Invoice\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"Invoice\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"energyContractDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"EnergyContractDetails\",\"relationName\":\"EnergyContractDetailsToInvoice\",\"relationFromFields\":[\"energyContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"invoiceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InvoiceType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"notes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"InternetContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToInternetContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"downloadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"uploadSpeed\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"routerSerialNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"installationDate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"homeId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"activationCode\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumbers\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"PhoneNumber\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"PhoneNumber\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetContractDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"internetDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"InternetContractDetails\",\"relationName\":\"InternetContractDetailsToPhoneNumber\",\"relationFromFields\":[\"internetContractDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipUsername\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipPasswordEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sipServer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"MobileContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToMobileContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requiresMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"dataVolume\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedMinutes\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"includedSMS\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deviceImei\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCards\",\"kind\":\"object\",\"isList\":true,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"SimCard\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[],\"relationToFields\":[],\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"SimCard\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetailsId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"mobileDetails\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"MobileContractDetails\",\"relationName\":\"MobileContractDetailsToSimCard\",\"relationFromFields\":[\"mobileDetailsId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"simCardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"pin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"puk\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMultisim\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isMain\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"TvContractDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"ContractToTvContractDetails\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"receiverModel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"smartcardNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"package\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CarInsuranceDetails\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contractId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":true,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"contract\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Contract\",\"relationName\":\"CarInsuranceDetailsToContract\",\"relationFromFields\":[\"contractId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"licensePlate\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"tsn\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vin\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"vehicleType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"firstRegistration\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"noClaimsClass\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"insuranceType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"InsuranceType\",\"default\":\"LIABILITY\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductiblePartial\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deductibleFull\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Float\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"policyNumber\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousInsurer\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"AuditLog\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userEmail\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userRole\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isCustomerPortal\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"action\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"AuditAction\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sensitivity\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"AuditSensitivity\",\"default\":\"MEDIUM\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceLabel\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"endpoint\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"httpMethod\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ipAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"userAgent\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"changesBefore\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"changesAfter\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"changesEncrypted\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":false,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"dataSubjectId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"legalBasis\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"success\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"errorMessage\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"durationMs\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"hash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"previousHash\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"CustomerConsent\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":true,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customer\",\"kind\":\"object\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Customer\",\"relationName\":\"CustomerToCustomerConsent\",\"relationFromFields\":[\"customerId\"],\"relationToFields\":[\"id\"],\"relationOnDelete\":\"Cascade\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"consentType\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"ConsentType\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"ConsentStatus\",\"default\":\"PENDING\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"grantedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"withdrawnAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"source\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"documentPath\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"version\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"ipAddress\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"customerId\",\"consentType\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"customerId\",\"consentType\"]}],\"isGenerated\":false},\"DataDeletionRequest\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"customerId\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"status\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DeletionRequestStatus\",\"default\":\"PENDING\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requestedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requestSource\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"requestedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"processedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"processedBy\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"deletedData\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"retainedData\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"retentionReason\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"proofDocument\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[],\"uniqueIndexes\":[],\"isGenerated\":false},\"AuditRetentionPolicy\":{\"dbName\":null,\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":true,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Int\",\"default\":{\"name\":\"autoincrement\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"resourceType\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"sensitivity\",\"kind\":\"enum\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"AuditSensitivity\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"retentionDays\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"Int\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"description\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"legalBasis\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":false,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"String\",\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"isActive\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"Boolean\",\"default\":true,\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":true,\"type\":\"DateTime\",\"default\":{\"name\":\"now\",\"args\":[]},\"isGenerated\":false,\"isUpdatedAt\":false},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"isList\":false,\"isRequired\":true,\"isUnique\":false,\"isId\":false,\"isReadOnly\":false,\"hasDefaultValue\":false,\"type\":\"DateTime\",\"isGenerated\":false,\"isUpdatedAt\":true}],\"primaryKey\":null,\"uniqueFields\":[[\"resourceType\",\"sensitivity\"]],\"uniqueIndexes\":[{\"name\":null,\"fields\":[\"resourceType\",\"sensitivity\"]}],\"isGenerated\":false}},\"enums\":{\"CustomerType\":{\"values\":[{\"name\":\"PRIVATE\",\"dbName\":null},{\"name\":\"BUSINESS\",\"dbName\":null}],\"dbName\":null},\"AddressType\":{\"values\":[{\"name\":\"DELIVERY_RESIDENCE\",\"dbName\":null},{\"name\":\"BILLING\",\"dbName\":null}],\"dbName\":null},\"DocumentType\":{\"values\":[{\"name\":\"ID_CARD\",\"dbName\":null},{\"name\":\"PASSPORT\",\"dbName\":null},{\"name\":\"DRIVERS_LICENSE\",\"dbName\":null},{\"name\":\"OTHER\",\"dbName\":null}],\"dbName\":null},\"EmailProviderType\":{\"values\":[{\"name\":\"PLESK\",\"dbName\":null},{\"name\":\"CPANEL\",\"dbName\":null},{\"name\":\"DIRECTADMIN\",\"dbName\":null}],\"dbName\":null},\"MailEncryption\":{\"values\":[{\"name\":\"SSL\",\"dbName\":null},{\"name\":\"STARTTLS\",\"dbName\":null},{\"name\":\"NONE\",\"dbName\":null}],\"dbName\":null},\"EmailFolder\":{\"values\":[{\"name\":\"INBOX\",\"dbName\":null},{\"name\":\"SENT\",\"dbName\":null}],\"dbName\":null},\"MeterType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null}],\"dbName\":null},\"MeterReadingStatus\":{\"values\":[{\"name\":\"RECORDED\",\"dbName\":null},{\"name\":\"REPORTED\",\"dbName\":null},{\"name\":\"TRANSFERRED\",\"dbName\":null}],\"dbName\":null},\"ContractType\":{\"values\":[{\"name\":\"ELECTRICITY\",\"dbName\":null},{\"name\":\"GAS\",\"dbName\":null},{\"name\":\"DSL\",\"dbName\":null},{\"name\":\"CABLE\",\"dbName\":null},{\"name\":\"FIBER\",\"dbName\":null},{\"name\":\"MOBILE\",\"dbName\":null},{\"name\":\"TV\",\"dbName\":null},{\"name\":\"CAR_INSURANCE\",\"dbName\":null}],\"dbName\":null},\"ContractStatus\":{\"values\":[{\"name\":\"DRAFT\",\"dbName\":null},{\"name\":\"PENDING\",\"dbName\":null},{\"name\":\"ACTIVE\",\"dbName\":null},{\"name\":\"CANCELLED\",\"dbName\":null},{\"name\":\"EXPIRED\",\"dbName\":null},{\"name\":\"DEACTIVATED\",\"dbName\":null}],\"dbName\":null},\"ContractTaskStatus\":{\"values\":[{\"name\":\"OPEN\",\"dbName\":null},{\"name\":\"COMPLETED\",\"dbName\":null}],\"dbName\":null},\"InvoiceType\":{\"values\":[{\"name\":\"INTERIM\",\"dbName\":null},{\"name\":\"FINAL\",\"dbName\":null},{\"name\":\"NOT_AVAILABLE\",\"dbName\":null}],\"dbName\":null},\"InsuranceType\":{\"values\":[{\"name\":\"LIABILITY\",\"dbName\":null},{\"name\":\"PARTIAL\",\"dbName\":null},{\"name\":\"FULL\",\"dbName\":null}],\"dbName\":null},\"AuditAction\":{\"values\":[{\"name\":\"CREATE\",\"dbName\":null},{\"name\":\"READ\",\"dbName\":null},{\"name\":\"UPDATE\",\"dbName\":null},{\"name\":\"DELETE\",\"dbName\":null},{\"name\":\"EXPORT\",\"dbName\":null},{\"name\":\"ANONYMIZE\",\"dbName\":null},{\"name\":\"LOGIN\",\"dbName\":null},{\"name\":\"LOGOUT\",\"dbName\":null},{\"name\":\"LOGIN_FAILED\",\"dbName\":null}],\"dbName\":null},\"AuditSensitivity\":{\"values\":[{\"name\":\"LOW\",\"dbName\":null},{\"name\":\"MEDIUM\",\"dbName\":null},{\"name\":\"HIGH\",\"dbName\":null},{\"name\":\"CRITICAL\",\"dbName\":null}],\"dbName\":null},\"ConsentType\":{\"values\":[{\"name\":\"DATA_PROCESSING\",\"dbName\":null},{\"name\":\"MARKETING_EMAIL\",\"dbName\":null},{\"name\":\"MARKETING_PHONE\",\"dbName\":null},{\"name\":\"DATA_SHARING_PARTNER\",\"dbName\":null}],\"dbName\":null},\"ConsentStatus\":{\"values\":[{\"name\":\"GRANTED\",\"dbName\":null},{\"name\":\"WITHDRAWN\",\"dbName\":null},{\"name\":\"PENDING\",\"dbName\":null}],\"dbName\":null},\"DeletionRequestStatus\":{\"values\":[{\"name\":\"PENDING\",\"dbName\":null},{\"name\":\"IN_PROGRESS\",\"dbName\":null},{\"name\":\"COMPLETED\",\"dbName\":null},{\"name\":\"PARTIALLY_COMPLETED\",\"dbName\":null},{\"name\":\"REJECTED\",\"dbName\":null}],\"dbName\":null}},\"types\":{}}") defineDmmfProperty(exports.Prisma, config.runtimeDataModel) config.engineWasm = undefined diff --git a/backend/node_modules/.prisma/client/package.json b/backend/node_modules/.prisma/client/package.json index e06e0e9e..8c0bc32a 100644 --- a/backend/node_modules/.prisma/client/package.json +++ b/backend/node_modules/.prisma/client/package.json @@ -1,5 +1,5 @@ { - "name": "prisma-client-652f85dbf9d7be282ff4b16714e4689fe4701aade21c76f6bcc5db624157e639", + "name": "prisma-client-c6d54e22fa4d6137f643638da5d523e99ce84f9544cc793fd89163f1612953c6", "main": "index.js", "types": "index.d.ts", "browser": "index-browser.js", diff --git a/backend/node_modules/.prisma/client/schema.prisma b/backend/node_modules/.prisma/client/schema.prisma index 592b478f..029e8658 100644 --- a/backend/node_modules/.prisma/client/schema.prisma +++ b/backend/node_modules/.prisma/client/schema.prisma @@ -7,6 +7,36 @@ datasource db { url = env("DATABASE_URL") } +// ==================== EMAIL LOG ==================== + +model EmailLog { + id Int @id @default(autoincrement()) + // Absender & Empfänger + fromAddress String // Absender-E-Mail + toAddress String // Empfänger-E-Mail + subject String // Betreff + // Versand-Kontext + context String // z.B. "consent-link", "authorization-request", "customer-email" + customerId Int? // Zugehöriger Kunde (falls vorhanden) + triggeredBy String? // Wer hat den Versand ausgelöst (User-Email) + // SMTP-Details + smtpServer String // SMTP-Server + smtpPort Int // SMTP-Port + smtpEncryption String // SSL, STARTTLS, NONE + smtpUser String // SMTP-Benutzername + // Ergebnis + success Boolean // Erfolgreich? + messageId String? // Message-ID aus SMTP-Antwort + errorMessage String? @db.Text // Fehlermeldung bei Fehler + smtpResponse String? @db.Text // SMTP-Server-Antwort + // Zeitstempel + sentAt DateTime @default(now()) + + @@index([sentAt]) + @@index([customerId]) + @@index([success]) +} + // ==================== APP SETTINGS ==================== model AppSetting { @@ -20,18 +50,24 @@ model AppSetting { // ==================== USERS & AUTH ==================== model User { - id Int @id @default(autoincrement()) - email String @unique + id Int @id @default(autoincrement()) + email String @unique password String firstName String lastName String - isActive Boolean @default(true) + isActive Boolean @default(true) tokenInvalidatedAt DateTime? // Zeitpunkt ab dem alle Tokens ungültig sind (für Zwangslogout bei Rechteänderung) - customerId Int? @unique - customer Customer? @relation(fields: [customerId], references: [id]) - roles UserRole[] - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + + // Messaging-Kanäle (für Datenschutz-Link-Versand) + whatsappNumber String? + telegramUsername String? + signalNumber String? + + customerId Int? @unique + customer Customer? @relation(fields: [customerId], references: [id]) + roles UserRole[] + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt } model Role { @@ -97,6 +133,7 @@ model Customer { commercialRegisterPath String? // PDF-Pfad zum Handelsregisterauszug commercialRegisterNumber String? // Handelsregisternummer (Text) privacyPolicyPath String? // PDF-Pfad zur Datenschutzerklärung (für alle Kunden) + consentHash String? @unique // Permanenter Hash für öffentlichen Einwilligungslink /datenschutz/ notes String? @db.Text // ===== Portal-Zugangsdaten ===== @@ -118,6 +155,13 @@ model Customer { representingFor CustomerRepresentative[] @relation("RepresentativeCustomer") representedBy CustomerRepresentative[] @relation("RepresentedCustomer") + // Vollmachten + authorizationsGiven RepresentativeAuthorization[] @relation("AuthorizationCustomer") + authorizationsReceived RepresentativeAuthorization[] @relation("AuthorizationRepresentative") + + // DSGVO: Einwilligungen + consents CustomerConsent[] + createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } @@ -140,6 +184,28 @@ model CustomerRepresentative { @@unique([customerId, representativeId]) // Keine doppelten Einträge } +// ==================== VOLLMACHTEN ==================== +// Vollmacht: Kunde B erteilt Kunde A die Vollmacht, seine Daten einzusehen +// Ohne Vollmacht kann der Vertreter die Verträge des Kunden NICHT sehen + +model RepresentativeAuthorization { + id Int @id @default(autoincrement()) + customerId Int // Der Kunde, der die Vollmacht erteilt (z.B. Mutter) + customer Customer @relation("AuthorizationCustomer", fields: [customerId], references: [id], onDelete: Cascade) + representativeId Int // Der Vertreter, der Zugriff bekommt (z.B. Sohn) + representative Customer @relation("AuthorizationRepresentative", fields: [representativeId], references: [id], onDelete: Cascade) + isGranted Boolean @default(false) // Vollmacht erteilt? + grantedAt DateTime? // Wann erteilt + withdrawnAt DateTime? // Wann widerrufen + source String? // Quelle: 'portal', 'papier', 'crm-backend' + documentPath String? // PDF-Upload der unterschriebenen Vollmacht + notes String? @db.Text // Notizen + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([customerId, representativeId]) // Eine Vollmacht pro Paar +} + // ==================== ADDRESSES ==================== enum AddressType { @@ -247,6 +313,10 @@ model EmailProviderConfig { smtpEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE allowSelfSignedCerts Boolean @default(false) // Selbstsignierte Zertifikate erlauben + // System-E-Mail für automatisierte Nachrichten (z.B. DSGVO Consent-Links) + systemEmailAddress String? // z.B. "info@stressfrei-wechseln.de" + systemEmailPasswordEncrypted String? // Passwort (verschlüsselt) + isActive Boolean @default(true) isDefault Boolean @default(false) // Standard-Provider createdAt DateTime @default(now()) @@ -356,14 +426,25 @@ model Meter { } model MeterReading { - id Int @id @default(autoincrement()) - meterId Int - meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade) - readingDate DateTime - value Float - unit String @default("kWh") - notes String? - createdAt DateTime @default(now()) + id Int @id @default(autoincrement()) + meterId Int + meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade) + readingDate DateTime + value Float + unit String @default("kWh") + notes String? + // Meldung & Übertragung + reportedBy String? // Wer hat gemeldet? (E-Mail des Portal-Kunden oder Mitarbeiter) + status MeterReadingStatus @default(RECORDED) + transferredAt DateTime? // Wann wurde der Stand an den Anbieter übertragen? + transferredBy String? // Wer hat übertragen? + createdAt DateTime @default(now()) +} + +enum MeterReadingStatus { + RECORDED // Erfasst (vom Mitarbeiter) + REPORTED // Vom Kunden gemeldet (Portal) + TRANSFERRED // An Anbieter übertragen } // ==================== SALES PLATFORMS ==================== @@ -759,3 +840,170 @@ model CarInsuranceDetails { policyNumber String? previousInsurer String? } + +// ==================== AUDIT LOGGING (DSGVO) ==================== + +enum AuditAction { + CREATE + READ + UPDATE + DELETE + EXPORT // DSGVO-Datenexport + ANONYMIZE // Recht auf Vergessenwerden + LOGIN + LOGOUT + LOGIN_FAILED +} + +enum AuditSensitivity { + LOW // Einstellungen, Plattformen + MEDIUM // Verträge, Tarife + HIGH // Kundendaten, Bankdaten + CRITICAL // Authentifizierung, Ausweisdokumente +} + +model AuditLog { + id Int @id @default(autoincrement()) + + // Wer + userId Int? // Staff User (null bei Kundenportal/System) + userEmail String + userRole String? @db.Text // Rolle zum Zeitpunkt der Aktion + customerId Int? // Bei Kundenportal-Zugriff + isCustomerPortal Boolean @default(false) + + // Was + action AuditAction + sensitivity AuditSensitivity @default(MEDIUM) + + // Welche Ressource + resourceType String // Prisma Model Name + resourceId String? // ID des Datensatzes + resourceLabel String? // Lesbare Bezeichnung + + // Kontext + endpoint String // API-Pfad + httpMethod String // GET, POST, PUT, DELETE + ipAddress String + userAgent String? @db.Text + + // Änderungen (JSON, bei sensiblen Daten verschlüsselt) + changesBefore String? @db.LongText + changesAfter String? @db.LongText + changesEncrypted Boolean @default(false) + + // DSGVO + dataSubjectId Int? // Betroffene Person (für Reports) + legalBasis String? // Rechtsgrundlage + + // Status + success Boolean @default(true) + errorMessage String? @db.Text + durationMs Int? + + // Unveränderlichkeit (Hash-Kette) + createdAt DateTime @default(now()) + hash String? // SHA-256 Hash des Eintrags + previousHash String? // Hash des vorherigen Eintrags + + @@index([userId]) + @@index([customerId]) + @@index([resourceType, resourceId]) + @@index([dataSubjectId]) + @@index([action]) + @@index([createdAt]) + @@index([sensitivity]) +} + +// ==================== CONSENT MANAGEMENT (DSGVO) ==================== + +enum ConsentType { + DATA_PROCESSING // Grundlegende Datenverarbeitung + MARKETING_EMAIL // E-Mail-Marketing + MARKETING_PHONE // Telefon-Marketing + DATA_SHARING_PARTNER // Weitergabe an Partner +} + +enum ConsentStatus { + GRANTED + WITHDRAWN + PENDING +} + +model CustomerConsent { + id Int @id @default(autoincrement()) + customerId Int + customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade) + + consentType ConsentType + status ConsentStatus @default(PENDING) + + grantedAt DateTime? + withdrawnAt DateTime? + source String? // "portal", "telefon", "papier", "email" + documentPath String? // Unterschriebenes Dokument + version String? // Version der Datenschutzerklärung + ipAddress String? + + createdBy String // User der die Einwilligung erfasst hat + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([customerId, consentType]) + @@index([customerId]) + @@index([consentType]) + @@index([status]) +} + +// ==================== DATA DELETION REQUESTS (DSGVO) ==================== + +enum DeletionRequestStatus { + PENDING // Anfrage eingegangen + IN_PROGRESS // Wird bearbeitet + COMPLETED // Abgeschlossen + PARTIALLY_COMPLETED // Teildaten behalten (rechtliche Gründe) + REJECTED // Abgelehnt +} + +model DataDeletionRequest { + id Int @id @default(autoincrement()) + customerId Int + + status DeletionRequestStatus @default(PENDING) + requestedAt DateTime @default(now()) + requestSource String // "email", "portal", "brief" + requestedBy String // Wer hat angefragt + + processedAt DateTime? + processedBy String? // Mitarbeiter der bearbeitet hat + + deletedData String? @db.LongText // JSON: Was wurde gelöscht + retainedData String? @db.LongText // JSON: Was wurde behalten + Grund + retentionReason String? @db.Text // Begründung für Aufbewahrung + + proofDocument String? // Pfad zum Löschnachweis-PDF + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([customerId]) + @@index([status]) + @@index([requestedAt]) +} + +// ==================== AUDIT RETENTION POLICIES ==================== + +model AuditRetentionPolicy { + id Int @id @default(autoincrement()) + resourceType String // "*" für Standard, oder spezifischer Model-Name + sensitivity AuditSensitivity? + retentionDays Int // Aufbewahrungsfrist in Tagen (z.B. 3650 = 10 Jahre) + description String? + legalBasis String? // Gesetzliche Grundlage (z.B. "AO §147", "HGB §257") + isActive Boolean @default(true) + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([resourceType, sensitivity]) +} diff --git a/backend/node_modules/.prisma/client/wasm.js b/backend/node_modules/.prisma/client/wasm.js index 5dc32177..20470a77 100644 --- a/backend/node_modules/.prisma/client/wasm.js +++ b/backend/node_modules/.prisma/client/wasm.js @@ -122,6 +122,25 @@ exports.Prisma.TransactionIsolationLevel = makeStrictEnum({ Serializable: 'Serializable' }); +exports.Prisma.EmailLogScalarFieldEnum = { + id: 'id', + fromAddress: 'fromAddress', + toAddress: 'toAddress', + subject: 'subject', + context: 'context', + customerId: 'customerId', + triggeredBy: 'triggeredBy', + smtpServer: 'smtpServer', + smtpPort: 'smtpPort', + smtpEncryption: 'smtpEncryption', + smtpUser: 'smtpUser', + success: 'success', + messageId: 'messageId', + errorMessage: 'errorMessage', + smtpResponse: 'smtpResponse', + sentAt: 'sentAt' +}; + exports.Prisma.AppSettingScalarFieldEnum = { id: 'id', key: 'key', @@ -138,6 +157,9 @@ exports.Prisma.UserScalarFieldEnum = { lastName: 'lastName', isActive: 'isActive', tokenInvalidatedAt: 'tokenInvalidatedAt', + whatsappNumber: 'whatsappNumber', + telegramUsername: 'telegramUsername', + signalNumber: 'signalNumber', customerId: 'customerId', createdAt: 'createdAt', updatedAt: 'updatedAt' @@ -186,6 +208,7 @@ exports.Prisma.CustomerScalarFieldEnum = { commercialRegisterPath: 'commercialRegisterPath', commercialRegisterNumber: 'commercialRegisterNumber', privacyPolicyPath: 'privacyPolicyPath', + consentHash: 'consentHash', notes: 'notes', portalEnabled: 'portalEnabled', portalEmail: 'portalEmail', @@ -206,6 +229,20 @@ exports.Prisma.CustomerRepresentativeScalarFieldEnum = { updatedAt: 'updatedAt' }; +exports.Prisma.RepresentativeAuthorizationScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + representativeId: 'representativeId', + isGranted: 'isGranted', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + notes: 'notes', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.AddressScalarFieldEnum = { id: 'id', customerId: 'customerId', @@ -267,6 +304,8 @@ exports.Prisma.EmailProviderConfigScalarFieldEnum = { imapEncryption: 'imapEncryption', smtpEncryption: 'smtpEncryption', allowSelfSignedCerts: 'allowSelfSignedCerts', + systemEmailAddress: 'systemEmailAddress', + systemEmailPasswordEncrypted: 'systemEmailPasswordEncrypted', isActive: 'isActive', isDefault: 'isDefault', createdAt: 'createdAt', @@ -335,6 +374,10 @@ exports.Prisma.MeterReadingScalarFieldEnum = { value: 'value', unit: 'unit', notes: 'notes', + reportedBy: 'reportedBy', + status: 'status', + transferredAt: 'transferredAt', + transferredBy: 'transferredBy', createdAt: 'createdAt' }; @@ -577,6 +620,80 @@ exports.Prisma.CarInsuranceDetailsScalarFieldEnum = { previousInsurer: 'previousInsurer' }; +exports.Prisma.AuditLogScalarFieldEnum = { + id: 'id', + userId: 'userId', + userEmail: 'userEmail', + userRole: 'userRole', + customerId: 'customerId', + isCustomerPortal: 'isCustomerPortal', + action: 'action', + sensitivity: 'sensitivity', + resourceType: 'resourceType', + resourceId: 'resourceId', + resourceLabel: 'resourceLabel', + endpoint: 'endpoint', + httpMethod: 'httpMethod', + ipAddress: 'ipAddress', + userAgent: 'userAgent', + changesBefore: 'changesBefore', + changesAfter: 'changesAfter', + changesEncrypted: 'changesEncrypted', + dataSubjectId: 'dataSubjectId', + legalBasis: 'legalBasis', + success: 'success', + errorMessage: 'errorMessage', + durationMs: 'durationMs', + createdAt: 'createdAt', + hash: 'hash', + previousHash: 'previousHash' +}; + +exports.Prisma.CustomerConsentScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + consentType: 'consentType', + status: 'status', + grantedAt: 'grantedAt', + withdrawnAt: 'withdrawnAt', + source: 'source', + documentPath: 'documentPath', + version: 'version', + ipAddress: 'ipAddress', + createdBy: 'createdBy', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.DataDeletionRequestScalarFieldEnum = { + id: 'id', + customerId: 'customerId', + status: 'status', + requestedAt: 'requestedAt', + requestSource: 'requestSource', + requestedBy: 'requestedBy', + processedAt: 'processedAt', + processedBy: 'processedBy', + deletedData: 'deletedData', + retainedData: 'retainedData', + retentionReason: 'retentionReason', + proofDocument: 'proofDocument', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + +exports.Prisma.AuditRetentionPolicyScalarFieldEnum = { + id: 'id', + resourceType: 'resourceType', + sensitivity: 'sensitivity', + retentionDays: 'retentionDays', + description: 'description', + legalBasis: 'legalBasis', + isActive: 'isActive', + createdAt: 'createdAt', + updatedAt: 'updatedAt' +}; + exports.Prisma.SortOrder = { asc: 'asc', desc: 'desc' @@ -625,6 +742,12 @@ exports.MeterType = exports.$Enums.MeterType = { GAS: 'GAS' }; +exports.MeterReadingStatus = exports.$Enums.MeterReadingStatus = { + RECORDED: 'RECORDED', + REPORTED: 'REPORTED', + TRANSFERRED: 'TRANSFERRED' +}; + exports.ContractType = exports.$Enums.ContractType = { ELECTRICITY: 'ELECTRICITY', GAS: 'GAS', @@ -662,7 +785,48 @@ exports.InsuranceType = exports.$Enums.InsuranceType = { FULL: 'FULL' }; +exports.AuditAction = exports.$Enums.AuditAction = { + CREATE: 'CREATE', + READ: 'READ', + UPDATE: 'UPDATE', + DELETE: 'DELETE', + EXPORT: 'EXPORT', + ANONYMIZE: 'ANONYMIZE', + LOGIN: 'LOGIN', + LOGOUT: 'LOGOUT', + LOGIN_FAILED: 'LOGIN_FAILED' +}; + +exports.AuditSensitivity = exports.$Enums.AuditSensitivity = { + LOW: 'LOW', + MEDIUM: 'MEDIUM', + HIGH: 'HIGH', + CRITICAL: 'CRITICAL' +}; + +exports.ConsentType = exports.$Enums.ConsentType = { + DATA_PROCESSING: 'DATA_PROCESSING', + MARKETING_EMAIL: 'MARKETING_EMAIL', + MARKETING_PHONE: 'MARKETING_PHONE', + DATA_SHARING_PARTNER: 'DATA_SHARING_PARTNER' +}; + +exports.ConsentStatus = exports.$Enums.ConsentStatus = { + GRANTED: 'GRANTED', + WITHDRAWN: 'WITHDRAWN', + PENDING: 'PENDING' +}; + +exports.DeletionRequestStatus = exports.$Enums.DeletionRequestStatus = { + PENDING: 'PENDING', + IN_PROGRESS: 'IN_PROGRESS', + COMPLETED: 'COMPLETED', + PARTIALLY_COMPLETED: 'PARTIALLY_COMPLETED', + REJECTED: 'REJECTED' +}; + exports.Prisma.ModelName = { + EmailLog: 'EmailLog', AppSetting: 'AppSetting', User: 'User', Role: 'Role', @@ -671,6 +835,7 @@ exports.Prisma.ModelName = { UserRole: 'UserRole', Customer: 'Customer', CustomerRepresentative: 'CustomerRepresentative', + RepresentativeAuthorization: 'RepresentativeAuthorization', Address: 'Address', BankCard: 'BankCard', IdentityDocument: 'IdentityDocument', @@ -696,7 +861,11 @@ exports.Prisma.ModelName = { MobileContractDetails: 'MobileContractDetails', SimCard: 'SimCard', TvContractDetails: 'TvContractDetails', - CarInsuranceDetails: 'CarInsuranceDetails' + CarInsuranceDetails: 'CarInsuranceDetails', + AuditLog: 'AuditLog', + CustomerConsent: 'CustomerConsent', + DataDeletionRequest: 'DataDeletionRequest', + AuditRetentionPolicy: 'AuditRetentionPolicy' }; /** diff --git a/backend/prisma/migrations/20260208232823_add_gdpr_audit_logging/migration.sql b/backend/prisma/migrations/20260208232823_add_gdpr_audit_logging/migration.sql new file mode 100644 index 00000000..7ab3daec --- /dev/null +++ b/backend/prisma/migrations/20260208232823_add_gdpr_audit_logging/migration.sql @@ -0,0 +1,103 @@ +-- CreateTable +CREATE TABLE `AuditLog` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `userId` INTEGER NULL, + `userEmail` VARCHAR(191) NOT NULL, + `userRole` VARCHAR(191) NULL, + `customerId` INTEGER NULL, + `isCustomerPortal` BOOLEAN NOT NULL DEFAULT false, + `action` ENUM('CREATE', 'READ', 'UPDATE', 'DELETE', 'EXPORT', 'ANONYMIZE', 'LOGIN', 'LOGOUT', 'LOGIN_FAILED') NOT NULL, + `sensitivity` ENUM('LOW', 'MEDIUM', 'HIGH', 'CRITICAL') NOT NULL DEFAULT 'MEDIUM', + `resourceType` VARCHAR(191) NOT NULL, + `resourceId` VARCHAR(191) NULL, + `resourceLabel` VARCHAR(191) NULL, + `endpoint` VARCHAR(191) NOT NULL, + `httpMethod` VARCHAR(191) NOT NULL, + `ipAddress` VARCHAR(191) NOT NULL, + `userAgent` TEXT NULL, + `changesBefore` LONGTEXT NULL, + `changesAfter` LONGTEXT NULL, + `changesEncrypted` BOOLEAN NOT NULL DEFAULT false, + `dataSubjectId` INTEGER NULL, + `legalBasis` VARCHAR(191) NULL, + `success` BOOLEAN NOT NULL DEFAULT true, + `errorMessage` TEXT NULL, + `durationMs` INTEGER NULL, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `hash` VARCHAR(191) NULL, + `previousHash` VARCHAR(191) NULL, + + INDEX `AuditLog_userId_idx`(`userId`), + INDEX `AuditLog_customerId_idx`(`customerId`), + INDEX `AuditLog_resourceType_resourceId_idx`(`resourceType`, `resourceId`), + INDEX `AuditLog_dataSubjectId_idx`(`dataSubjectId`), + INDEX `AuditLog_action_idx`(`action`), + INDEX `AuditLog_createdAt_idx`(`createdAt`), + INDEX `AuditLog_sensitivity_idx`(`sensitivity`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `CustomerConsent` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `customerId` INTEGER NOT NULL, + `consentType` ENUM('DATA_PROCESSING', 'MARKETING_EMAIL', 'MARKETING_PHONE', 'DATA_SHARING_PARTNER') NOT NULL, + `status` ENUM('GRANTED', 'WITHDRAWN', 'PENDING') NOT NULL DEFAULT 'PENDING', + `grantedAt` DATETIME(3) NULL, + `withdrawnAt` DATETIME(3) NULL, + `source` VARCHAR(191) NULL, + `documentPath` VARCHAR(191) NULL, + `version` VARCHAR(191) NULL, + `ipAddress` VARCHAR(191) NULL, + `createdBy` VARCHAR(191) NOT NULL, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` DATETIME(3) NOT NULL, + + INDEX `CustomerConsent_customerId_idx`(`customerId`), + INDEX `CustomerConsent_consentType_idx`(`consentType`), + INDEX `CustomerConsent_status_idx`(`status`), + UNIQUE INDEX `CustomerConsent_customerId_consentType_key`(`customerId`, `consentType`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `DataDeletionRequest` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `customerId` INTEGER NOT NULL, + `status` ENUM('PENDING', 'IN_PROGRESS', 'COMPLETED', 'PARTIALLY_COMPLETED', 'REJECTED') NOT NULL DEFAULT 'PENDING', + `requestedAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `requestSource` VARCHAR(191) NOT NULL, + `requestedBy` VARCHAR(191) NOT NULL, + `processedAt` DATETIME(3) NULL, + `processedBy` VARCHAR(191) NULL, + `deletedData` LONGTEXT NULL, + `retainedData` LONGTEXT NULL, + `retentionReason` TEXT NULL, + `proofDocument` VARCHAR(191) NULL, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` DATETIME(3) NOT NULL, + + INDEX `DataDeletionRequest_customerId_idx`(`customerId`), + INDEX `DataDeletionRequest_status_idx`(`status`), + INDEX `DataDeletionRequest_requestedAt_idx`(`requestedAt`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- CreateTable +CREATE TABLE `AuditRetentionPolicy` ( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `resourceType` VARCHAR(191) NOT NULL, + `sensitivity` ENUM('LOW', 'MEDIUM', 'HIGH', 'CRITICAL') NULL, + `retentionDays` INTEGER NOT NULL, + `description` VARCHAR(191) NULL, + `legalBasis` VARCHAR(191) NULL, + `isActive` BOOLEAN NOT NULL DEFAULT true, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `updatedAt` DATETIME(3) NOT NULL, + + UNIQUE INDEX `AuditRetentionPolicy_resourceType_sensitivity_key`(`resourceType`, `sensitivity`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +-- AddForeignKey +ALTER TABLE `CustomerConsent` ADD CONSTRAINT `CustomerConsent_customerId_fkey` FOREIGN KEY (`customerId`) REFERENCES `Customer`(`id`) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/migrations/20260216_add_consent_hash_and_user_messaging/migration.sql b/backend/prisma/migrations/20260216_add_consent_hash_and_user_messaging/migration.sql new file mode 100644 index 00000000..22ce299b --- /dev/null +++ b/backend/prisma/migrations/20260216_add_consent_hash_and_user_messaging/migration.sql @@ -0,0 +1,10 @@ +-- AlterTable +ALTER TABLE `Customer` ADD COLUMN `consentHash` VARCHAR(191) NULL; + +-- AlterTable +ALTER TABLE `User` ADD COLUMN `whatsappNumber` VARCHAR(191) NULL, + ADD COLUMN `telegramUsername` VARCHAR(191) NULL, + ADD COLUMN `signalNumber` VARCHAR(191) NULL; + +-- CreateIndex +CREATE UNIQUE INDEX `Customer_consentHash_key` ON `Customer`(`consentHash`); diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 41ee4c56..d1bf43f8 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -7,6 +7,36 @@ datasource db { url = env("DATABASE_URL") } +// ==================== EMAIL LOG ==================== + +model EmailLog { + id Int @id @default(autoincrement()) + // Absender & Empfänger + fromAddress String // Absender-E-Mail + toAddress String // Empfänger-E-Mail + subject String // Betreff + // Versand-Kontext + context String // z.B. "consent-link", "authorization-request", "customer-email" + customerId Int? // Zugehöriger Kunde (falls vorhanden) + triggeredBy String? // Wer hat den Versand ausgelöst (User-Email) + // SMTP-Details + smtpServer String // SMTP-Server + smtpPort Int // SMTP-Port + smtpEncryption String // SSL, STARTTLS, NONE + smtpUser String // SMTP-Benutzername + // Ergebnis + success Boolean // Erfolgreich? + messageId String? // Message-ID aus SMTP-Antwort + errorMessage String? @db.Text // Fehlermeldung bei Fehler + smtpResponse String? @db.Text // SMTP-Server-Antwort + // Zeitstempel + sentAt DateTime @default(now()) + + @@index([sentAt]) + @@index([customerId]) + @@index([success]) +} + // ==================== APP SETTINGS ==================== model AppSetting { @@ -27,6 +57,12 @@ model User { lastName String isActive Boolean @default(true) tokenInvalidatedAt DateTime? // Zeitpunkt ab dem alle Tokens ungültig sind (für Zwangslogout bei Rechteänderung) + + // Messaging-Kanäle (für Datenschutz-Link-Versand) + whatsappNumber String? + telegramUsername String? + signalNumber String? + customerId Int? @unique customer Customer? @relation(fields: [customerId], references: [id]) roles UserRole[] @@ -97,6 +133,7 @@ model Customer { commercialRegisterPath String? // PDF-Pfad zum Handelsregisterauszug commercialRegisterNumber String? // Handelsregisternummer (Text) privacyPolicyPath String? // PDF-Pfad zur Datenschutzerklärung (für alle Kunden) + consentHash String? @unique // Permanenter Hash für öffentlichen Einwilligungslink /datenschutz/ notes String? @db.Text // ===== Portal-Zugangsdaten ===== @@ -118,6 +155,13 @@ model Customer { representingFor CustomerRepresentative[] @relation("RepresentativeCustomer") representedBy CustomerRepresentative[] @relation("RepresentedCustomer") + // Vollmachten + authorizationsGiven RepresentativeAuthorization[] @relation("AuthorizationCustomer") + authorizationsReceived RepresentativeAuthorization[] @relation("AuthorizationRepresentative") + + // DSGVO: Einwilligungen + consents CustomerConsent[] + createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } @@ -140,6 +184,28 @@ model CustomerRepresentative { @@unique([customerId, representativeId]) // Keine doppelten Einträge } +// ==================== VOLLMACHTEN ==================== +// Vollmacht: Kunde B erteilt Kunde A die Vollmacht, seine Daten einzusehen +// Ohne Vollmacht kann der Vertreter die Verträge des Kunden NICHT sehen + +model RepresentativeAuthorization { + id Int @id @default(autoincrement()) + customerId Int // Der Kunde, der die Vollmacht erteilt (z.B. Mutter) + customer Customer @relation("AuthorizationCustomer", fields: [customerId], references: [id], onDelete: Cascade) + representativeId Int // Der Vertreter, der Zugriff bekommt (z.B. Sohn) + representative Customer @relation("AuthorizationRepresentative", fields: [representativeId], references: [id], onDelete: Cascade) + isGranted Boolean @default(false) // Vollmacht erteilt? + grantedAt DateTime? // Wann erteilt + withdrawnAt DateTime? // Wann widerrufen + source String? // Quelle: 'portal', 'papier', 'crm-backend' + documentPath String? // PDF-Upload der unterschriebenen Vollmacht + notes String? @db.Text // Notizen + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([customerId, representativeId]) // Eine Vollmacht pro Paar +} + // ==================== ADDRESSES ==================== enum AddressType { @@ -247,6 +313,10 @@ model EmailProviderConfig { smtpEncryption MailEncryption @default(SSL) // SSL, STARTTLS oder NONE allowSelfSignedCerts Boolean @default(false) // Selbstsignierte Zertifikate erlauben + // System-E-Mail für automatisierte Nachrichten (z.B. DSGVO Consent-Links) + systemEmailAddress String? // z.B. "info@stressfrei-wechseln.de" + systemEmailPasswordEncrypted String? // Passwort (verschlüsselt) + isActive Boolean @default(true) isDefault Boolean @default(false) // Standard-Provider createdAt DateTime @default(now()) @@ -356,14 +426,25 @@ model Meter { } model MeterReading { - id Int @id @default(autoincrement()) + id Int @id @default(autoincrement()) meterId Int - meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade) + meter Meter @relation(fields: [meterId], references: [id], onDelete: Cascade) readingDate DateTime value Float - unit String @default("kWh") + unit String @default("kWh") notes String? - createdAt DateTime @default(now()) + // Meldung & Übertragung + reportedBy String? // Wer hat gemeldet? (E-Mail des Portal-Kunden oder Mitarbeiter) + status MeterReadingStatus @default(RECORDED) + transferredAt DateTime? // Wann wurde der Stand an den Anbieter übertragen? + transferredBy String? // Wer hat übertragen? + createdAt DateTime @default(now()) +} + +enum MeterReadingStatus { + RECORDED // Erfasst (vom Mitarbeiter) + REPORTED // Vom Kunden gemeldet (Portal) + TRANSFERRED // An Anbieter übertragen } // ==================== SALES PLATFORMS ==================== @@ -759,3 +840,170 @@ model CarInsuranceDetails { policyNumber String? previousInsurer String? } + +// ==================== AUDIT LOGGING (DSGVO) ==================== + +enum AuditAction { + CREATE + READ + UPDATE + DELETE + EXPORT // DSGVO-Datenexport + ANONYMIZE // Recht auf Vergessenwerden + LOGIN + LOGOUT + LOGIN_FAILED +} + +enum AuditSensitivity { + LOW // Einstellungen, Plattformen + MEDIUM // Verträge, Tarife + HIGH // Kundendaten, Bankdaten + CRITICAL // Authentifizierung, Ausweisdokumente +} + +model AuditLog { + id Int @id @default(autoincrement()) + + // Wer + userId Int? // Staff User (null bei Kundenportal/System) + userEmail String + userRole String? @db.Text // Rolle zum Zeitpunkt der Aktion + customerId Int? // Bei Kundenportal-Zugriff + isCustomerPortal Boolean @default(false) + + // Was + action AuditAction + sensitivity AuditSensitivity @default(MEDIUM) + + // Welche Ressource + resourceType String // Prisma Model Name + resourceId String? // ID des Datensatzes + resourceLabel String? // Lesbare Bezeichnung + + // Kontext + endpoint String // API-Pfad + httpMethod String // GET, POST, PUT, DELETE + ipAddress String + userAgent String? @db.Text + + // Änderungen (JSON, bei sensiblen Daten verschlüsselt) + changesBefore String? @db.LongText + changesAfter String? @db.LongText + changesEncrypted Boolean @default(false) + + // DSGVO + dataSubjectId Int? // Betroffene Person (für Reports) + legalBasis String? // Rechtsgrundlage + + // Status + success Boolean @default(true) + errorMessage String? @db.Text + durationMs Int? + + // Unveränderlichkeit (Hash-Kette) + createdAt DateTime @default(now()) + hash String? // SHA-256 Hash des Eintrags + previousHash String? // Hash des vorherigen Eintrags + + @@index([userId]) + @@index([customerId]) + @@index([resourceType, resourceId]) + @@index([dataSubjectId]) + @@index([action]) + @@index([createdAt]) + @@index([sensitivity]) +} + +// ==================== CONSENT MANAGEMENT (DSGVO) ==================== + +enum ConsentType { + DATA_PROCESSING // Grundlegende Datenverarbeitung + MARKETING_EMAIL // E-Mail-Marketing + MARKETING_PHONE // Telefon-Marketing + DATA_SHARING_PARTNER // Weitergabe an Partner +} + +enum ConsentStatus { + GRANTED + WITHDRAWN + PENDING +} + +model CustomerConsent { + id Int @id @default(autoincrement()) + customerId Int + customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade) + + consentType ConsentType + status ConsentStatus @default(PENDING) + + grantedAt DateTime? + withdrawnAt DateTime? + source String? // "portal", "telefon", "papier", "email" + documentPath String? // Unterschriebenes Dokument + version String? // Version der Datenschutzerklärung + ipAddress String? + + createdBy String // User der die Einwilligung erfasst hat + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([customerId, consentType]) + @@index([customerId]) + @@index([consentType]) + @@index([status]) +} + +// ==================== DATA DELETION REQUESTS (DSGVO) ==================== + +enum DeletionRequestStatus { + PENDING // Anfrage eingegangen + IN_PROGRESS // Wird bearbeitet + COMPLETED // Abgeschlossen + PARTIALLY_COMPLETED // Teildaten behalten (rechtliche Gründe) + REJECTED // Abgelehnt +} + +model DataDeletionRequest { + id Int @id @default(autoincrement()) + customerId Int + + status DeletionRequestStatus @default(PENDING) + requestedAt DateTime @default(now()) + requestSource String // "email", "portal", "brief" + requestedBy String // Wer hat angefragt + + processedAt DateTime? + processedBy String? // Mitarbeiter der bearbeitet hat + + deletedData String? @db.LongText // JSON: Was wurde gelöscht + retainedData String? @db.LongText // JSON: Was wurde behalten + Grund + retentionReason String? @db.Text // Begründung für Aufbewahrung + + proofDocument String? // Pfad zum Löschnachweis-PDF + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([customerId]) + @@index([status]) + @@index([requestedAt]) +} + +// ==================== AUDIT RETENTION POLICIES ==================== + +model AuditRetentionPolicy { + id Int @id @default(autoincrement()) + resourceType String // "*" für Standard, oder spezifischer Model-Name + sensitivity AuditSensitivity? + retentionDays Int // Aufbewahrungsfrist in Tagen (z.B. 3650 = 10 Jahre) + description String? + legalBasis String? // Gesetzliche Grundlage (z.B. "AO §147", "HGB §257") + isActive Boolean @default(true) + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@unique([resourceType, sensitivity]) +} diff --git a/backend/prisma/seed.ts b/backend/prisma/seed.ts index bf5ce4da..09af6f2f 100644 --- a/backend/prisma/seed.ts +++ b/backend/prisma/seed.ts @@ -1,5 +1,6 @@ import { PrismaClient } from '@prisma/client'; import bcrypt from 'bcryptjs'; +import crypto from 'crypto'; const prisma = new PrismaClient(); @@ -26,6 +27,9 @@ async function main() { // Spezial-Permissions developer: ['access'], emails: ['delete'], + // DSGVO & Audit + audit: ['read', 'export', 'admin'], + gdpr: ['export', 'delete', 'admin'], }; const permissions: { resource: string; action: string }[] = []; @@ -60,10 +64,42 @@ async function main() { (p) => p.resource === 'providers' && p.action === 'read' ); + // Helper: Sync permissions for a role (adds missing, removes excess) + async function syncRolePermissions(roleId: number, permissionIds: number[]) { + const existing = await prisma.rolePermission.findMany({ + where: { roleId }, + select: { permissionId: true }, + }); + const existingIds = new Set(existing.map((e) => e.permissionId)); + const targetIds = new Set(permissionIds); + + // Add missing permissions + const missing = permissionIds.filter((id) => !existingIds.has(id)); + if (missing.length > 0) { + await prisma.rolePermission.createMany({ + data: missing.map((permissionId) => ({ roleId, permissionId })), + skipDuplicates: true, + }); + console.log(` → ${missing.length} Permissions hinzugefügt für Rolle #${roleId}`); + } + + // Remove excess permissions + const excess = existing.filter((e) => !targetIds.has(e.permissionId)).map((e) => e.permissionId); + if (excess.length > 0) { + await prisma.rolePermission.deleteMany({ + where: { roleId, permissionId: { in: excess } }, + }); + console.log(` → ${excess.length} Permissions entfernt für Rolle #${roleId}`); + } + } + // Create roles - // Admin - all permissions EXCEPT developer:access (that's controlled separately) + // Admin - all permissions EXCEPT developer:access and audit/gdpr (controlled separately via checkboxes) const adminPermissions = allPermissions.filter( - (p) => !(p.resource === 'developer' && p.action === 'access') + (p) => + !(p.resource === 'developer' && p.action === 'access') && + p.resource !== 'audit' && + p.resource !== 'gdpr' ); const adminRole = await prisma.role.upsert({ where: { name: 'Admin' }, @@ -76,8 +112,10 @@ async function main() { }, }, }); + await syncRolePermissions(adminRole.id, adminPermissions.map((p) => p.id)); - // Developer - ALL permissions including developer:access + // Developer - ALL permissions (developer:access + alles andere) + const developerPermissions = allPermissions; const developerRole = await prisma.role.upsert({ where: { name: 'Developer' }, update: {}, @@ -85,10 +123,28 @@ async function main() { name: 'Developer', description: 'Voller Zugriff inkl. Entwickler-Tools', permissions: { - create: allPermissions.map((p) => ({ permissionId: p.id })), + create: developerPermissions.map((p) => ({ permissionId: p.id })), }, }, }); + await syncRolePermissions(developerRole.id, developerPermissions.map((p) => p.id)); + + // DSGVO - audit and gdpr permissions (hidden role, controlled via hasGdprAccess) + const gdprPermissions = allPermissions.filter( + (p) => p.resource === 'audit' || p.resource === 'gdpr' + ); + const gdprRole = await prisma.role.upsert({ + where: { name: 'DSGVO' }, + update: {}, + create: { + name: 'DSGVO', + description: 'DSGVO-Zugriff: Audit-Logs und Datenschutz-Verwaltung', + permissions: { + create: gdprPermissions.map((p) => ({ permissionId: p.id })), + }, + }, + }); + await syncRolePermissions(gdprRole.id, gdprPermissions.map((p) => p.id)); // Employee - full access to customers, contracts, read access to lookup tables const employeePermIds = allPermissions @@ -119,6 +175,7 @@ async function main() { }, }, }); + await syncRolePermissions(employeeRole.id, employeePermIds); // Read-only employee - read access to main entities and lookup tables const readOnlyResources = [ @@ -146,6 +203,7 @@ async function main() { }, }, }); + await syncRolePermissions(readOnlyRole.id, readOnlyPermIds); // Customer role - read own data only (handled in middleware) const customerRole = await prisma.role.upsert({ @@ -159,6 +217,7 @@ async function main() { }, }, }); + await syncRolePermissions(customerRole.id, readOnlyPermIds); console.log('Roles created'); @@ -346,6 +405,91 @@ async function main() { console.log('App settings created'); + // ==================== AUDIT RETENTION POLICIES (DSGVO) ==================== + // Standard-Policy (ohne Sensitivity) + const existingDefault = await prisma.auditRetentionPolicy.findFirst({ + where: { resourceType: '*', sensitivity: null }, + }); + if (!existingDefault) { + await prisma.auditRetentionPolicy.create({ + data: { + resourceType: '*', + sensitivity: null, + retentionDays: 3650, // 10 Jahre + description: 'Standard-Aufbewahrungsfrist', + legalBasis: 'AO §147, HGB §257', + }, + }); + } + + // Spezifische Policies mit Sensitivity + const specificPolicies = [ + { + resourceType: 'Authentication', + sensitivity: 'CRITICAL' as const, + retentionDays: 730, // 2 Jahre + description: 'Login-Versuche und Authentifizierung', + legalBasis: 'Sicherheitsanforderungen', + }, + { + resourceType: 'Customer', + sensitivity: 'HIGH' as const, + retentionDays: 3650, // 10 Jahre + description: 'Kundendaten-Zugriffe', + legalBasis: 'Steuerrecht (AO §147)', + }, + { + resourceType: 'Contract', + sensitivity: 'MEDIUM' as const, + retentionDays: 3650, // 10 Jahre + description: 'Vertragsdaten-Zugriffe', + legalBasis: 'Steuerrecht (AO §147)', + }, + { + resourceType: 'AppSetting', + sensitivity: 'LOW' as const, + retentionDays: 1095, // 3 Jahre + description: 'Allgemeine Einstellungen', + legalBasis: 'Verjährungsfrist (BGB §195)', + }, + ]; + + for (const policy of specificPolicies) { + await prisma.auditRetentionPolicy.upsert({ + where: { + resourceType_sensitivity: { + resourceType: policy.resourceType, + sensitivity: policy.sensitivity, + }, + }, + update: { + retentionDays: policy.retentionDays, + description: policy.description, + legalBasis: policy.legalBasis, + }, + create: policy, + }); + } + + console.log('Audit retention policies created'); + + // ==================== CONSENT HASH FÜR BESTEHENDE KUNDEN ==================== + const customersWithoutHash = await prisma.customer.findMany({ + where: { consentHash: null }, + select: { id: true }, + }); + + for (const c of customersWithoutHash) { + await prisma.customer.update({ + where: { id: c.id }, + data: { consentHash: crypto.randomUUID() }, + }); + } + + if (customersWithoutHash.length > 0) { + console.log(`ConsentHash für ${customersWithoutHash.length} Kunden generiert`); + } + console.log('Seeding completed!'); } diff --git a/backend/scripts/seed-privacy-policy.ts b/backend/scripts/seed-privacy-policy.ts new file mode 100644 index 00000000..f3fea5b7 --- /dev/null +++ b/backend/scripts/seed-privacy-policy.ts @@ -0,0 +1,223 @@ +/** + * Script: Datenschutzerklärung in die Datenbank einfügen + * Ausführen: npx tsx scripts/seed-privacy-policy.ts + */ +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); + +const privacyPolicyHtml = ` +

Datenschutzerklärung

+

gemäß EU-Datenschutz-Grundverordnung (DSGVO)

+ +
+

Hacker-Net Telekommunikation – Stefan Hacker

+

+ Am Wunderburgpark 5b, 26135 Oldenburg
+ Tel.: 01735837852 · E-Mail: info@hacker-net.de +

+
+ +

Sehr geehrte(r) {{anrede}} {{vorname}} {{nachname}},

+ +

der Schutz Ihrer persönlichen Daten ist uns ein wichtiges Anliegen. Nachfolgend informieren wir Sie darüber, wie wir Ihre Daten erheben, verarbeiten und schützen.

+ +
+ +

1. Verantwortlicher

+ +

Verantwortlich für die Datenverarbeitung im Sinne der DSGVO ist:

+ +

+ Hacker-Net Telekommunikation – Stefan Hacker
+ Am Wunderburgpark 5b, 26135 Oldenburg
+ Tel.: 01735837852
+ E-Mail: info@hacker-net.de +

+ +
+ +

2. Erhebung, Zweck und Speicherung Ihrer Daten

+ +

Welche Daten wir erheben

+ +

Wenn Sie uns beauftragen, erheben wir folgende personenbezogene Daten:

+ +
+
Anrede, Vorname, Nachname
+
Geburtsdatum, Geburtsort
+
Ausweisdaten
+
Bankdaten (IBAN, BIC)
+
E-Mail-Adresse
+
Anschrift / Lieferanschriften
+
Telefonnummer(n)
+
Vertragsdaten / Produkte
+
Zählernummern (Strom, Gas)
+
Fahrzeugschein- / Führerscheindaten
+
Domainnamen / E-Mail-Adressen
+
+ +
+

Personalisierte E-Mail-Adresse

+

+ Im Rahmen unserer Dienstleistung erstellen wir für Sie eine personalisierte E-Mail-Adresse mit der Endung @stressfrei-wechseln.de. +

+

+ Diese dient als Verteiler-Adresse zur Kommunikation mit Anbietern – sowohl Sie als auch wir erhalten darüber die relevante Korrespondenz. +

+

+ Die Adresse wird ausschließlich für diesen Zweck verwendet und nach Beendigung des Vertragsverhältnisses deaktiviert. +

+
+ +

Zweck der Datenerhebung

+ +

Die Erhebung dieser Daten erfolgt zu folgenden Zwecken:

+ +
    +
  • Identifikation als unser Kunde
  • +
  • Angemessene Beratung und Betreuung
  • +
  • Korrespondenz mit Ihnen und mit Anbietern in Ihrem Auftrag
  • +
  • Rechnungsstellung
  • +
  • Kündigung von Altverträgen und Abschluss neuer Verträge
  • +
+ +

Rechtsgrundlage

+ +

Die Datenverarbeitung erfolgt auf Grundlage von:

+ +
    +
  • Art. 6 Abs. 1 S. 1 lit. b DSGVO – Vertragserfüllung
  • +
  • Art. 6 Abs. 1 S. 1 lit. a DSGVO – Ihre Einwilligung, soweit erteilt
  • +
+ +

Speicherdauer

+ +

Ihre Daten werden für die Dauer des Vertragsverhältnisses gespeichert.

+ +

Nach Vertragsende bewahren wir Ihre Daten gemäß den gesetzlichen Aufbewahrungsfristen auf (10 Jahre gemäß §§ 147 AO, 257 HGB) und löschen sie anschließend, sofern keine darüber hinausgehende Einwilligung vorliegt.

+ +
+ +

3. Weitergabe von Daten an Dritte

+ +

Ihre personenbezogenen Daten werden nur weitergegeben, wenn dies für die Erfüllung unseres Vertrags mit Ihnen erforderlich ist (Art. 6 Abs. 1 S. 1 lit. b DSGVO).

+ +

Hierzu gehört insbesondere die Weitergabe an Produkt- und Dienstleistungsanbieter (z. B. Telekommunikations-, Strom-, Gas- und Versicherungsanbieter), da ohne diese Weitergabe keine Verträge gekündigt und/oder neue Verträge abgeschlossen werden können.

+ +

Die weitergegebenen Daten dürfen von den Empfängern ausschließlich zu den genannten Zwecken verwendet werden.

+ +

Eine darüber hinausgehende Weitergabe findet ohne Ihre ausdrückliche Einwilligung nicht statt.

+ +
+ +

4. Sicherheit Ihrer Daten

+ +

Wir setzen technische und organisatorische Maßnahmen ein, um Ihre Daten gegen Verlust, Zerstörung, Manipulation und unberechtigten Zugriff zu schützen:

+ +
+
+

Verschlüsselung

+

SSL/TLS-verschlüsselte Datenübertragung

+
+
+

Zugangskontrolle

+

Berechtigungssysteme und Passwortschutz

+
+
+

Updates

+

Regelmäßige Sicherheitsupdates unserer Systeme

+
+
+

Vertraulichkeit

+

Verpflichtung aller Mitarbeiter zur Verschwiegenheit

+
+
+ +
+ +

5. Ihre Rechte

+ +

Als betroffene Person stehen Ihnen gemäß DSGVO folgende Rechte zu:

+ +
+
+

Widerruf der Einwilligung (Art. 7 Abs. 3 DSGVO)

+

Sie können eine erteilte Einwilligung jederzeit widerrufen. Die Rechtmäßigkeit der bis zum Widerruf erfolgten Datenverarbeitung bleibt davon unberührt.

+
+ +
+

Auskunftsrecht (Art. 15 DSGVO)

+

Sie können Auskunft über Ihre von uns verarbeiteten Daten verlangen – einschließlich Verarbeitungszwecke, Kategorien, Empfänger, Speicherdauer und Herkunft.

+
+ +
+

Recht auf Berichtigung (Art. 16 DSGVO)

+

Sie können die Berichtigung unrichtiger oder die Vervollständigung unvollständiger Daten verlangen.

+
+ +
+

Recht auf Löschung (Art. 17 DSGVO)

+

Sie können die Löschung Ihrer Daten verlangen, sofern keine gesetzlichen Aufbewahrungspflichten entgegenstehen.

+
+ +
+

Recht auf Einschränkung (Art. 18 DSGVO)

+

Sie können unter bestimmten Voraussetzungen die Einschränkung der Verarbeitung verlangen.

+
+ +
+

Recht auf Datenübertragbarkeit (Art. 20 DSGVO)

+

Sie können Ihre Daten in einem strukturierten, gängigen und maschinenlesbaren Format erhalten oder an einen anderen Verantwortlichen übermitteln lassen.

+
+
+ +
+

Beschwerderecht (Art. 77 DSGVO)

+

+ Sie haben das Recht, sich bei der zuständigen Aufsichtsbehörde zu beschweren: +

+

+ Die Landesbeauftragte für den Datenschutz Niedersachsen
+ Prinzenstraße 5, 30159 Hannover
+ Tel.: 0511 120-4500
+ E-Mail: poststelle@lfd.niedersachsen.de +

+
+ +
+ +

6. Widerspruchsrecht

+ +

Sofern Ihre Daten auf Grundlage von berechtigten Interessen gemäß Art. 6 Abs. 1 S. 1 lit. f DSGVO verarbeitet werden, haben Sie das Recht, gemäß Art. 21 DSGVO Widerspruch gegen die Verarbeitung einzulegen, soweit Gründe vorliegen, die sich aus Ihrer besonderen Situation ergeben.

+ +
+

+ Möchten Sie eines Ihrer Rechte ausüben? +

+

+ Schreiben Sie uns einfach eine E-Mail an: +

+

+ info@hacker-net.de +

+
+ +
+ +

Stand: {{datum}} · Kundennummer: {{kundennummer}}

+`; + +async function main() { + await prisma.appSetting.upsert({ + where: { key: 'privacyPolicyHtml' }, + update: { value: privacyPolicyHtml }, + create: { key: 'privacyPolicyHtml', value: privacyPolicyHtml }, + }); + + console.log('Datenschutzerklärung erfolgreich gespeichert!'); +} + +main() + .catch(console.error) + .finally(() => prisma.$disconnect()); diff --git a/backend/src/controllers/auditLog.controller.ts b/backend/src/controllers/auditLog.controller.ts new file mode 100644 index 00000000..fd4bef08 --- /dev/null +++ b/backend/src/controllers/auditLog.controller.ts @@ -0,0 +1,201 @@ +import { Response } from 'express'; +import { AuthRequest } from '../types/index.js'; +import * as auditService from '../services/audit.service.js'; +import { AuditAction, AuditSensitivity } from '@prisma/client'; + +/** + * Audit-Logs mit Filtern abrufen + */ +export async function getAuditLogs(req: AuthRequest, res: Response) { + try { + const { + userId, + customerId, + dataSubjectId, + action, + sensitivity, + resourceType, + resourceId, + startDate, + endDate, + success, + search, + page, + limit, + } = req.query; + + const result = await auditService.searchAuditLogs({ + userId: userId ? parseInt(userId as string) : undefined, + customerId: customerId ? parseInt(customerId as string) : undefined, + dataSubjectId: dataSubjectId ? parseInt(dataSubjectId as string) : undefined, + action: action as AuditAction | undefined, + sensitivity: sensitivity as AuditSensitivity | undefined, + resourceType: resourceType as string | undefined, + resourceId: resourceId as string | undefined, + startDate: startDate ? new Date(startDate as string) : undefined, + endDate: endDate ? new Date(endDate as string) : undefined, + success: success !== undefined ? success === 'true' : undefined, + search: search as string | undefined, + page: page ? parseInt(page as string) : 1, + limit: limit ? parseInt(limit as string) : 50, + }); + + res.json({ success: true, ...result }); + } catch (error) { + console.error('Fehler beim Abrufen der Audit-Logs:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen der Audit-Logs' }); + } +} + +/** + * Einzelnes Audit-Log abrufen + */ +export async function getAuditLogById(req: AuthRequest, res: Response) { + try { + const id = parseInt(req.params.id); + const log = await auditService.getAuditLogById(id); + + if (!log) { + return res.status(404).json({ success: false, error: 'Audit-Log nicht gefunden' }); + } + + res.json({ success: true, data: log }); + } catch (error) { + console.error('Fehler beim Abrufen des Audit-Logs:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen des Audit-Logs' }); + } +} + +/** + * Audit-Logs für einen Kunden abrufen (DSGVO) + */ +export async function getAuditLogsByCustomer(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const logs = await auditService.getAuditLogsByDataSubject(customerId); + + res.json({ success: true, data: logs }); + } catch (error) { + console.error('Fehler beim Abrufen der Kunden-Audit-Logs:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen der Audit-Logs' }); + } +} + +/** + * Audit-Logs exportieren + */ +export async function exportAuditLogs(req: AuthRequest, res: Response) { + try { + const format = (req.query.format as 'json' | 'csv') || 'json'; + const { + action, + sensitivity, + resourceType, + startDate, + endDate, + } = req.query; + + const content = await auditService.exportAuditLogs( + { + action: action as AuditAction | undefined, + sensitivity: sensitivity as AuditSensitivity | undefined, + resourceType: resourceType as string | undefined, + startDate: startDate ? new Date(startDate as string) : undefined, + endDate: endDate ? new Date(endDate as string) : undefined, + }, + format + ); + + const contentType = format === 'csv' ? 'text/csv' : 'application/json'; + const filename = `audit-logs-${new Date().toISOString().split('T')[0]}.${format}`; + + res.setHeader('Content-Type', contentType); + res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); + res.send(content); + } catch (error) { + console.error('Fehler beim Exportieren der Audit-Logs:', error); + res.status(500).json({ success: false, error: 'Fehler beim Exportieren' }); + } +} + +/** + * Hash-Ketten-Integrität prüfen + */ +export async function verifyIntegrity(req: AuthRequest, res: Response) { + try { + const { fromId, toId } = req.query; + + const result = await auditService.verifyIntegrity( + fromId ? parseInt(fromId as string) : undefined, + toId ? parseInt(toId as string) : undefined + ); + + res.json({ + success: true, + data: { + valid: result.valid, + checkedCount: result.checkedCount, + invalidEntries: result.invalidEntries, + message: result.valid + ? 'Alle Einträge sind valide' + : `${result.invalidEntries.length} manipulierte Einträge gefunden`, + }, + }); + } catch (error) { + console.error('Fehler bei der Integritätsprüfung:', error); + res.status(500).json({ success: false, error: 'Fehler bei der Integritätsprüfung' }); + } +} + +/** + * Retention-Policies abrufen + */ +export async function getRetentionPolicies(req: AuthRequest, res: Response) { + try { + const policies = await auditService.getRetentionPolicies(); + res.json({ success: true, data: policies }); + } catch (error) { + console.error('Fehler beim Abrufen der Retention-Policies:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen der Policies' }); + } +} + +/** + * Retention-Policy aktualisieren + */ +export async function updateRetentionPolicy(req: AuthRequest, res: Response) { + try { + const id = parseInt(req.params.id); + const { retentionDays, description, legalBasis, isActive } = req.body; + + const policy = await auditService.updateRetentionPolicy(id, { + retentionDays, + description, + legalBasis, + isActive, + }); + + res.json({ success: true, data: policy }); + } catch (error) { + console.error('Fehler beim Aktualisieren der Retention-Policy:', error); + res.status(500).json({ success: false, error: 'Fehler beim Aktualisieren' }); + } +} + +/** + * Retention-Cleanup manuell ausführen + */ +export async function runRetentionCleanup(req: AuthRequest, res: Response) { + try { + const result = await auditService.runRetentionCleanup(); + + res.json({ + success: true, + data: result, + message: `${result.deletedCount} alte Audit-Logs wurden gelöscht`, + }); + } catch (error) { + console.error('Fehler beim Retention-Cleanup:', error); + res.status(500).json({ success: false, error: 'Fehler beim Cleanup' }); + } +} diff --git a/backend/src/controllers/cachedEmail.controller.ts b/backend/src/controllers/cachedEmail.controller.ts index 14a96e1a..6399a3bd 100644 --- a/backend/src/controllers/cachedEmail.controller.ts +++ b/backend/src/controllers/cachedEmail.controller.ts @@ -317,7 +317,12 @@ export async function sendEmailFromAccount(req: Request, res: Response): Promise }; // E-Mail senden - const result = await sendEmail(credentials, stressfreiEmail.email, emailParams); + const authReq = req as any; + const result = await sendEmail(credentials, stressfreiEmail.email, emailParams, { + context: 'customer-email', + customerId: stressfreiEmail.customerId, + triggeredBy: authReq.user?.email, + }); if (!result.success) { res.status(400).json({ diff --git a/backend/src/controllers/consent-public.controller.ts b/backend/src/controllers/consent-public.controller.ts new file mode 100644 index 00000000..05cedcc1 --- /dev/null +++ b/backend/src/controllers/consent-public.controller.ts @@ -0,0 +1,107 @@ +import { Request, Response } from 'express'; +import * as consentPublicService from '../services/consent-public.service.js'; +import { createAuditLog } from '../services/audit.service.js'; +import { CONSENT_TYPE_LABELS } from '../services/consent.service.js'; +import { ConsentType } from '@prisma/client'; + +/** + * Öffentliche Consent-Seite: Kundendaten + Datenschutztext + Status + */ +export async function getConsentPage(req: Request, res: Response) { + try { + const { hash } = req.params; + + const result = await consentPublicService.getCustomerByConsentHash(hash); + if (!result) { + return res.status(404).json({ success: false, error: 'Ungültiger Link' }); + } + + const privacyPolicyHtml = await consentPublicService.getPrivacyPolicyHtml(result.customer.id); + + // Consent-Status mit Labels + const consentsWithLabels = result.consents.map((c) => ({ + consentType: c.consentType, + status: c.status, + label: CONSENT_TYPE_LABELS[c.consentType as ConsentType]?.label || c.consentType, + description: CONSENT_TYPE_LABELS[c.consentType as ConsentType]?.description || '', + grantedAt: c.grantedAt, + })); + + res.json({ + success: true, + data: { + customer: { + firstName: result.customer.firstName, + lastName: result.customer.lastName, + customerNumber: result.customer.customerNumber, + }, + privacyPolicyHtml, + consents: consentsWithLabels, + allGranted: consentsWithLabels.every((c) => c.status === 'GRANTED'), + }, + }); + } catch (error) { + console.error('Fehler beim Laden der Consent-Seite:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden' }); + } +} + +/** + * Alle 4 Einwilligungen erteilen (öffentlicher Link) + */ +export async function grantAllConsents(req: Request, res: Response) { + try { + const { hash } = req.params; + const ipAddress = req.ip || req.socket.remoteAddress || 'unknown'; + + const results = await consentPublicService.grantAllConsentsPublic(hash, ipAddress); + + // Audit-Log (manuell, da keine Auth-Middleware) + const customer = await consentPublicService.getCustomerByConsentHash(hash); + if (customer) { + for (const type of Object.values(ConsentType)) { + await createAuditLog({ + userEmail: customer.customer.email || 'public-link', + action: 'UPDATE', + sensitivity: 'HIGH', + resourceType: 'CustomerConsent', + resourceId: `${customer.customer.id}:${type}`, + resourceLabel: `Einwilligung ${type} erteilt via Public-Link`, + endpoint: `/api/public/consent/${hash}/grant`, + httpMethod: 'POST', + ipAddress, + dataSubjectId: customer.customer.id, + legalBasis: 'DSGVO Art. 6 Abs. 1 lit. a', + }); + } + } + + res.json({ success: true, data: results }); + } catch (error: any) { + console.error('Fehler beim Erteilen der Einwilligungen:', error); + res.status(400).json({ success: false, error: error.message || 'Fehler beim Erteilen' }); + } +} + +/** + * Datenschutzerklärung als PDF + */ +export async function getConsentPdf(req: Request, res: Response) { + try { + const { hash } = req.params; + + const result = await consentPublicService.getCustomerByConsentHash(hash); + if (!result) { + return res.status(404).json({ success: false, error: 'Ungültiger Link' }); + } + + const pdfBuffer = await consentPublicService.generateConsentPdf(result.customer.id); + + res.setHeader('Content-Type', 'application/pdf'); + res.setHeader('Content-Disposition', 'inline; filename="datenschutzerklaerung.pdf"'); + res.send(pdfBuffer); + } catch (error) { + console.error('Fehler beim Generieren des PDFs:', error); + res.status(500).json({ success: false, error: 'Fehler beim Generieren' }); + } +} diff --git a/backend/src/controllers/contract.controller.ts b/backend/src/controllers/contract.controller.ts index 0371193a..8772639e 100644 --- a/backend/src/controllers/contract.controller.ts +++ b/backend/src/controllers/contract.controller.ts @@ -3,6 +3,7 @@ import { PrismaClient } from '@prisma/client'; import * as contractService from '../services/contract.service.js'; import * as contractCockpitService from '../services/contractCockpit.service.js'; import * as contractHistoryService from '../services/contractHistory.service.js'; +import * as authorizationService from '../services/authorization.service.js'; import { ApiResponse, AuthRequest } from '../types/index.js'; const prisma = new PrismaClient(); @@ -20,11 +21,19 @@ export async function getContracts(req: AuthRequest, res: Response): Promise { @@ -331,6 +334,98 @@ export async function deleteMeterReading(req: Request, res: Response): Promise { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' } as ApiResponse); + return; + } + + const meterId = parseInt(req.params.meterId); + const { value, readingDate, notes } = req.body; + + // Prüfe ob der Zähler zum Kunden gehört + const meter = await prisma.meter.findUnique({ + where: { id: meterId }, + select: { customerId: true }, + }); + + if (!meter || meter.customerId !== user.customerId) { + res.status(403).json({ success: false, error: 'Kein Zugriff auf diesen Zähler' } as ApiResponse); + return; + } + + const reading = await prisma.meterReading.create({ + data: { + meterId, + value: parseFloat(value), + readingDate: readingDate ? new Date(readingDate) : new Date(), + notes, + reportedBy: user.email, + status: 'REPORTED', + }, + }); + + res.status(201).json({ success: true, data: reading } as ApiResponse); + } catch (error) { + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Melden des Zählerstands', + } as ApiResponse); + } +} + +export async function getMyMeters(req: AuthRequest, res: Response): Promise { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' } as ApiResponse); + return; + } + + const meters = await prisma.meter.findMany({ + where: { customerId: user.customerId, isActive: true }, + include: { + readings: { + orderBy: { readingDate: 'desc' }, + take: 5, + }, + }, + orderBy: { createdAt: 'asc' }, + }); + + res.json({ success: true, data: meters } as ApiResponse); + } catch (error) { + res.status(500).json({ success: false, error: 'Fehler beim Laden der Zähler' } as ApiResponse); + } +} + +export async function markReadingTransferred(req: AuthRequest, res: Response): Promise { + try { + const meterId = parseInt(req.params.meterId); + const readingId = parseInt(req.params.readingId); + + const reading = await prisma.meterReading.update({ + where: { id: readingId }, + data: { + status: 'TRANSFERRED', + transferredAt: new Date(), + transferredBy: req.user?.email, + }, + }); + + res.json({ success: true, data: reading } as ApiResponse); + } catch (error) { + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Aktualisieren', + } as ApiResponse); + } +} + // ==================== PORTAL SETTINGS ==================== export async function getPortalSettings(req: Request, res: Response): Promise { diff --git a/backend/src/controllers/emailLog.controller.ts b/backend/src/controllers/emailLog.controller.ts new file mode 100644 index 00000000..da96e1b6 --- /dev/null +++ b/backend/src/controllers/emailLog.controller.ts @@ -0,0 +1,43 @@ +import { Response } from 'express'; +import { AuthRequest } from '../types/index.js'; +import * as emailLogService from '../services/emailLog.service.js'; + +export async function getEmailLogs(req: AuthRequest, res: Response) { + try { + const page = parseInt(req.query.page as string) || 1; + const limit = parseInt(req.query.limit as string) || 50; + const success = req.query.success !== undefined ? req.query.success === 'true' : undefined; + const search = req.query.search as string || undefined; + const context = req.query.context as string || undefined; + + const result = await emailLogService.getEmailLogs({ page, limit, success, search, context }); + res.json({ success: true, ...result }); + } catch (error) { + console.error('Fehler beim Laden der Email-Logs:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden' }); + } +} + +export async function getEmailLogStats(req: AuthRequest, res: Response) { + try { + const stats = await emailLogService.getEmailLogStats(); + res.json({ success: true, data: stats }); + } catch (error) { + console.error('Fehler beim Laden der Email-Log-Stats:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden' }); + } +} + +export async function getEmailLogDetail(req: AuthRequest, res: Response) { + try { + const id = parseInt(req.params.id); + const log = await emailLogService.getEmailLogById(id); + if (!log) { + return res.status(404).json({ success: false, error: 'Log-Eintrag nicht gefunden' }); + } + res.json({ success: true, data: log }); + } catch (error) { + console.error('Fehler beim Laden des Email-Log-Details:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden' }); + } +} diff --git a/backend/src/controllers/gdpr.controller.ts b/backend/src/controllers/gdpr.controller.ts new file mode 100644 index 00000000..852d6746 --- /dev/null +++ b/backend/src/controllers/gdpr.controller.ts @@ -0,0 +1,899 @@ +import { Response } from 'express'; +import { AuthRequest } from '../types/index.js'; +import * as gdprService from '../services/gdpr.service.js'; +import * as consentService from '../services/consent.service.js'; +import * as consentPublicService from '../services/consent-public.service.js'; +import * as appSettingService from '../services/appSetting.service.js'; +import { createAuditLog } from '../services/audit.service.js'; +import { ConsentType, DeletionRequestStatus, PrismaClient } from '@prisma/client'; +import path from 'path'; +import fs from 'fs'; +import { sendEmail, SmtpCredentials } from '../services/smtpService.js'; +import { getSystemEmailCredentials } from '../services/emailProvider/emailProviderService.js'; +import * as authorizationService from '../services/authorization.service.js'; + +const prisma = new PrismaClient(); + +/** + * Kundendaten exportieren (DSGVO Art. 15) + */ +export async function exportCustomerData(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const format = (req.query.format as string) || 'json'; + + const data = await gdprService.exportCustomerData(customerId); + + // Audit-Log für Export + await createAuditLog({ + userId: req.user?.userId, + userEmail: req.user?.email || 'unknown', + action: 'EXPORT', + resourceType: 'GDPR', + resourceId: customerId.toString(), + resourceLabel: `Datenexport für ${data.dataSubject.name}`, + endpoint: req.path, + httpMethod: req.method, + ipAddress: req.socket.remoteAddress || 'unknown', + dataSubjectId: customerId, + legalBasis: 'DSGVO Art. 15', + }); + + if (format === 'json') { + res.setHeader('Content-Type', 'application/json'); + res.setHeader( + 'Content-Disposition', + `attachment; filename="datenexport_${data.dataSubject.customerNumber}_${new Date().toISOString().split('T')[0]}.json"` + ); + res.json(data); + } else { + // Für PDF würde hier PDFKit verwendet werden + res.json({ success: true, data }); + } + } catch (error) { + console.error('Fehler beim Datenexport:', error); + res.status(500).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Datenexport', + }); + } +} + +/** + * Löschanfrage erstellen + */ +export async function createDeletionRequest(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.id); + const { requestSource } = req.body; + + const request = await gdprService.createDeletionRequest({ + customerId, + requestSource: requestSource || 'portal', + requestedBy: req.user?.email || 'unknown', + }); + + res.status(201).json({ success: true, data: request }); + } catch (error) { + console.error('Fehler beim Erstellen der Löschanfrage:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Erstellen', + }); + } +} + +/** + * Alle Löschanfragen abrufen + */ +export async function getDeletionRequests(req: AuthRequest, res: Response) { + try { + const { status, page, limit } = req.query; + + const result = await gdprService.getDeletionRequests({ + status: status as DeletionRequestStatus | undefined, + page: page ? parseInt(page as string) : 1, + limit: limit ? parseInt(limit as string) : 20, + }); + + res.json({ success: true, ...result }); + } catch (error) { + console.error('Fehler beim Abrufen der Löschanfragen:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen' }); + } +} + +/** + * Einzelne Löschanfrage abrufen + */ +export async function getDeletionRequest(req: AuthRequest, res: Response) { + try { + const id = parseInt(req.params.id); + const request = await gdprService.getDeletionRequest(id); + + if (!request) { + return res.status(404).json({ success: false, error: 'Löschanfrage nicht gefunden' }); + } + + res.json({ success: true, data: request }); + } catch (error) { + console.error('Fehler beim Abrufen der Löschanfrage:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen' }); + } +} + +/** + * Löschanfrage bearbeiten + */ +export async function processDeletionRequest(req: AuthRequest, res: Response) { + try { + const id = parseInt(req.params.id); + const { action, retentionReason } = req.body; + + if (!['complete', 'partial', 'reject'].includes(action)) { + return res.status(400).json({ + success: false, + error: 'Ungültige Aktion. Erlaubt: complete, partial, reject', + }); + } + + const result = await gdprService.processDeletionRequest(id, { + processedBy: req.user?.email || 'unknown', + action, + retentionReason, + }); + + // Audit-Log für Löschung + await createAuditLog({ + userId: req.user?.userId, + userEmail: req.user?.email || 'unknown', + action: 'ANONYMIZE', + resourceType: 'GDPR', + resourceId: id.toString(), + resourceLabel: `Löschanfrage ${action}`, + endpoint: req.path, + httpMethod: req.method, + ipAddress: req.socket.remoteAddress || 'unknown', + dataSubjectId: result.customerId, + legalBasis: 'DSGVO Art. 17', + }); + + res.json({ success: true, data: result }); + } catch (error) { + console.error('Fehler beim Bearbeiten der Löschanfrage:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Bearbeiten', + }); + } +} + +/** + * Löschnachweis-PDF herunterladen + */ +export async function getDeletionProof(req: AuthRequest, res: Response) { + try { + const id = parseInt(req.params.id); + const request = await gdprService.getDeletionRequest(id); + + if (!request) { + return res.status(404).json({ success: false, error: 'Löschanfrage nicht gefunden' }); + } + + if (!request.proofDocument) { + return res.status(404).json({ success: false, error: 'Kein Löschnachweis vorhanden' }); + } + + const filepath = path.join(process.cwd(), 'uploads', request.proofDocument); + + if (!fs.existsSync(filepath)) { + return res.status(404).json({ success: false, error: 'Datei nicht gefunden' }); + } + + res.download(filepath); + } catch (error) { + console.error('Fehler beim Download des Löschnachweises:', error); + res.status(500).json({ success: false, error: 'Fehler beim Download' }); + } +} + +/** + * DSGVO-Dashboard Statistiken + */ +export async function getDashboardStats(req: AuthRequest, res: Response) { + try { + const stats = await gdprService.getGDPRDashboardStats(); + res.json({ success: true, data: stats }); + } catch (error) { + console.error('Fehler beim Abrufen der Dashboard-Statistiken:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen' }); + } +} + +// ==================== CONSENT ENDPOINTS ==================== + +/** + * Einwilligungen eines Kunden abrufen + */ +export async function getCustomerConsents(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const consents = await consentService.getCustomerConsents(customerId); + + // Labels hinzufügen + const consentsWithLabels = consents.map((c) => ({ + ...c, + label: consentService.CONSENT_TYPE_LABELS[c.consentType as ConsentType]?.label, + description: consentService.CONSENT_TYPE_LABELS[c.consentType as ConsentType]?.description, + })); + + res.json({ success: true, data: consentsWithLabels }); + } catch (error) { + console.error('Fehler beim Abrufen der Einwilligungen:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen' }); + } +} + +/** + * Consent-Status prüfen (hat der Kunde vollständig zugestimmt?) + */ +export async function checkConsentStatus(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const result = await consentService.hasFullConsent(customerId); + res.json({ success: true, data: result }); + } catch (error) { + console.error('Fehler beim Consent-Check:', error); + res.status(500).json({ success: false, error: 'Fehler beim Consent-Check' }); + } +} + +/** + * Einwilligung aktualisieren (nur Kundenportal-Benutzer!) + */ +export async function updateCustomerConsent(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const consentType = req.params.consentType as ConsentType; + const { status, source, documentPath, version } = req.body; + + // Nur Kundenportal-Benutzer dürfen Einwilligungen ändern + if (!(req.user as any)?.isCustomerPortal) { + return res.status(403).json({ + success: false, + error: 'Nur Kunden können Einwilligungen ändern', + }); + } + + // Portal: nur eigene + vertretene Kunden + const allowed = [ + (req.user as any).customerId, + ...((req.user as any).representedCustomerIds || []), + ]; + if (!allowed.includes(customerId)) { + return res.status(403).json({ + success: false, + error: 'Keine Berechtigung für diesen Kunden', + }); + } + + if (!Object.values(ConsentType).includes(consentType)) { + return res.status(400).json({ success: false, error: 'Ungültiger Consent-Typ' }); + } + + const consent = await consentService.updateConsent(customerId, consentType, { + status, + source: source || 'portal', + documentPath, + version, + ipAddress: req.socket.remoteAddress, + createdBy: req.user?.email || 'unknown', + }); + + res.json({ success: true, data: consent }); + } catch (error) { + console.error('Fehler beim Aktualisieren der Einwilligung:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Aktualisieren', + }); + } +} + +/** + * Consent-Übersicht für Dashboard + */ +export async function getConsentOverview(req: AuthRequest, res: Response) { + try { + const overview = await consentService.getConsentOverview(); + + // Labels hinzufügen + const overviewWithLabels = Object.entries(overview).map(([type, stats]) => ({ + type, + label: consentService.CONSENT_TYPE_LABELS[type as ConsentType]?.label, + description: consentService.CONSENT_TYPE_LABELS[type as ConsentType]?.description, + ...stats, + })); + + res.json({ success: true, data: overviewWithLabels }); + } catch (error) { + console.error('Fehler beim Abrufen der Consent-Übersicht:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen' }); + } +} + +// ==================== PRIVACY POLICY ENDPOINTS ==================== + +/** + * Datenschutzerklärung abrufen (HTML) + */ +export async function getPrivacyPolicy(req: AuthRequest, res: Response) { + try { + const html = await appSettingService.getSetting('privacyPolicyHtml'); + res.json({ success: true, data: { html: html || '' } }); + } catch (error) { + console.error('Fehler beim Abrufen der Datenschutzerklärung:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen' }); + } +} + +/** + * Datenschutzerklärung speichern (HTML) + */ +export async function updatePrivacyPolicy(req: AuthRequest, res: Response) { + try { + const { html } = req.body; + + if (typeof html !== 'string') { + return res.status(400).json({ success: false, error: 'HTML-Inhalt erforderlich' }); + } + + await appSettingService.setSetting('privacyPolicyHtml', html); + + res.json({ success: true, message: 'Datenschutzerklärung gespeichert' }); + } catch (error) { + console.error('Fehler beim Speichern der Datenschutzerklärung:', error); + res.status(500).json({ success: false, error: 'Fehler beim Speichern' }); + } +} + +/** + * Vollmacht-Vorlage abrufen (HTML) + */ +export async function getAuthorizationTemplate(req: AuthRequest, res: Response) { + try { + const html = await appSettingService.getSetting('authorizationTemplateHtml'); + res.json({ success: true, data: { html: html || '' } }); + } catch (error) { + console.error('Fehler beim Abrufen der Vollmacht-Vorlage:', error); + res.status(500).json({ success: false, error: 'Fehler beim Abrufen' }); + } +} + +/** + * Vollmacht-Vorlage speichern (HTML) + */ +export async function updateAuthorizationTemplate(req: AuthRequest, res: Response) { + try { + const { html } = req.body; + + if (typeof html !== 'string') { + return res.status(400).json({ success: false, error: 'HTML-Inhalt erforderlich' }); + } + + await appSettingService.setSetting('authorizationTemplateHtml', html); + + res.json({ success: true, message: 'Vollmacht-Vorlage gespeichert' }); + } catch (error) { + console.error('Fehler beim Speichern der Vollmacht-Vorlage:', error); + res.status(500).json({ success: false, error: 'Fehler beim Speichern' }); + } +} + +// ==================== SEND CONSENT LINK ==================== + +/** + * Consent-Link an Kunden senden + */ +// ==================== PORTAL ENDPOINTS ==================== + +/** + * Portal: Eigene Datenschutzseite (Privacy Policy + Consent-Status) + */ +export async function getMyPrivacy(req: AuthRequest, res: Response) { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + return res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + } + + const customerId = user.customerId; + + const [privacyPolicyHtml, consents] = await Promise.all([ + consentPublicService.getPrivacyPolicyHtml(customerId), + consentService.getCustomerConsents(customerId), + ]); + + const consentsWithLabels = consents.map((c) => ({ + ...c, + label: consentService.CONSENT_TYPE_LABELS[c.consentType as ConsentType]?.label, + description: consentService.CONSENT_TYPE_LABELS[c.consentType as ConsentType]?.description, + })); + + res.json({ + success: true, + data: { + privacyPolicyHtml, + consents: consentsWithLabels, + }, + }); + } catch (error) { + console.error('Fehler beim Laden der Portal-Datenschutzseite:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden' }); + } +} + +/** + * Portal: Datenschutzerklärung als PDF + */ +export async function getMyPrivacyPdf(req: AuthRequest, res: Response) { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + return res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + } + + const pdfBuffer = await consentPublicService.generateConsentPdf(user.customerId); + + res.setHeader('Content-Type', 'application/pdf'); + res.setHeader('Content-Disposition', 'inline; filename="datenschutzerklaerung.pdf"'); + res.send(pdfBuffer); + } catch (error) { + console.error('Fehler beim Generieren des Portal-PDFs:', error); + res.status(500).json({ success: false, error: 'Fehler beim Generieren' }); + } +} + +/** + * Portal: Eigenen Consent-Status prüfen + */ +export async function getMyConsentStatus(req: AuthRequest, res: Response) { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + return res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + } + const result = await consentService.hasFullConsent(user.customerId); + res.json({ success: true, data: result }); + } catch (error) { + console.error('Fehler beim Consent-Status:', error); + res.status(500).json({ success: false, error: 'Fehler beim Consent-Status' }); + } +} + +export async function sendConsentLink(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const { channel } = req.body; // 'email', 'whatsapp', 'telegram', 'signal' + + // ConsentHash sicherstellen + const hash = await consentPublicService.ensureConsentHash(customerId); + const baseUrl = process.env.PUBLIC_URL || req.headers.origin || 'http://localhost:5173'; + const consentUrl = `${baseUrl}/datenschutz/${hash}`; + + // Bei E-Mail: tatsächlich senden + if (channel === 'email') { + // Kunde laden + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + select: { id: true, firstName: true, lastName: true, email: true }, + }); + + if (!customer?.email) { + return res.status(400).json({ + success: false, + error: 'Kunde hat keine E-Mail-Adresse hinterlegt', + }); + } + + // System-E-Mail-Credentials vom aktiven Provider holen + const systemEmail = await getSystemEmailCredentials(); + if (!systemEmail) { + return res.status(400).json({ + success: false, + error: 'Keine System-E-Mail konfiguriert. Bitte in den Email-Provider-Einstellungen eine System-E-Mail-Adresse und Passwort hinterlegen.', + }); + } + + const credentials: SmtpCredentials = { + host: systemEmail.smtpServer, + port: systemEmail.smtpPort, + user: systemEmail.emailAddress, + password: systemEmail.password, + encryption: systemEmail.smtpEncryption, + allowSelfSignedCerts: systemEmail.allowSelfSignedCerts, + }; + + // E-Mail zusammenstellen + const emailHtml = ` +
+

Datenschutzerklärung – Ihre Zustimmung

+

Sehr geehrte(r) ${customer.firstName} ${customer.lastName},

+

+ um Sie optimal beraten und betreuen zu können, benötigen wir Ihre Zustimmung zu unserer Datenschutzerklärung. +

+

+ Bitte klicken Sie auf den folgenden Button, um unsere Datenschutzerklärung einzusehen und Ihre Einwilligung zu erteilen: +

+

+ + Datenschutzerklärung ansehen & zustimmen + +

+

+ Alternativ können Sie auch diesen Link in Ihren Browser kopieren:
+ ${consentUrl} +

+
+

+ Hacker-Net Telekommunikation – Stefan Hacker
+ Am Wunderburgpark 5b, 26135 Oldenburg
+ info@hacker-net.de +

+
+ `; + + const result = await sendEmail(credentials, systemEmail.emailAddress, { + to: customer.email, + subject: 'Datenschutzerklärung – Bitte um Ihre Zustimmung', + html: emailHtml, + }, { + context: 'consent-link', + customerId, + triggeredBy: req.user?.email, + }); + + if (!result.success) { + return res.status(400).json({ + success: false, + error: `E-Mail-Versand fehlgeschlagen: ${result.error}`, + }); + } + } + + // Audit-Log + await createAuditLog({ + userId: req.user?.userId, + userEmail: req.user?.email || 'unknown', + action: 'READ', + resourceType: 'CustomerConsent', + resourceId: customerId.toString(), + resourceLabel: `Consent-Link gesendet (${channel})`, + endpoint: req.path, + httpMethod: req.method, + ipAddress: req.socket.remoteAddress || 'unknown', + dataSubjectId: customerId, + legalBasis: 'DSGVO Art. 6 Abs. 1a', + }); + + res.json({ + success: true, + data: { + url: consentUrl, + channel, + hash, + }, + }); + } catch (error) { + console.error('Fehler beim Senden des Consent-Links:', error); + res.status(500).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Senden', + }); + } +} + +// ==================== VOLLMACHTEN ==================== + +/** + * Vollmacht-Anfrage an Kunden senden (per E-Mail, WhatsApp, Telegram, Signal) + */ +export async function sendAuthorizationRequest(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const representativeId = parseInt(req.params.representativeId); + const { channel } = req.body; + + // Kunde (Vollmachtgeber) laden + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + select: { id: true, firstName: true, lastName: true, email: true }, + }); + + // Vertreter (Bevollmächtigter) laden + const representative = await prisma.customer.findUnique({ + where: { id: representativeId }, + select: { id: true, firstName: true, lastName: true }, + }); + + if (!customer || !representative) { + return res.status(404).json({ success: false, error: 'Kunde oder Vertreter nicht gefunden' }); + } + + const baseUrl = process.env.PUBLIC_URL || req.headers.origin || 'http://localhost:5173'; + const portalUrl = `${baseUrl}/privacy`; + + // E-Mail senden + if (channel === 'email') { + if (!customer.email) { + return res.status(400).json({ success: false, error: 'Kunde hat keine E-Mail-Adresse hinterlegt' }); + } + + const systemEmail = await getSystemEmailCredentials(); + if (!systemEmail) { + return res.status(400).json({ + success: false, + error: 'Keine System-E-Mail konfiguriert. Bitte in den Email-Provider-Einstellungen eine System-E-Mail-Adresse und Passwort hinterlegen.', + }); + } + + const credentials: SmtpCredentials = { + host: systemEmail.smtpServer, + port: systemEmail.smtpPort, + user: systemEmail.emailAddress, + password: systemEmail.password, + encryption: systemEmail.smtpEncryption, + allowSelfSignedCerts: systemEmail.allowSelfSignedCerts, + }; + + const emailHtml = ` +
+

Vollmacht – Ihre Zustimmung erforderlich

+

Sehr geehrte(r) ${customer.firstName} ${customer.lastName},

+

+ ${representative.firstName} ${representative.lastName} möchte als Ihr Vertreter Zugriff auf Ihre Vertragsdaten erhalten. +

+

+ Damit dies möglich ist, benötigen wir Ihre Vollmacht. Sie können diese bequem über unser Kundenportal erteilen: +

+

+ + Vollmacht im Portal erteilen + +

+

+ Alternativ können Sie auch diesen Link in Ihren Browser kopieren:
+ ${portalUrl} +

+

+ Sie können die Vollmacht jederzeit im Portal unter "Datenschutz" widerrufen. +

+
+

+ Hacker-Net Telekommunikation – Stefan Hacker
+ Am Wunderburgpark 5b, 26135 Oldenburg
+ info@hacker-net.de +

+
+ `; + + const result = await sendEmail(credentials, systemEmail.emailAddress, { + to: customer.email, + subject: `Vollmacht für ${representative.firstName} ${representative.lastName} – Bitte um Ihre Zustimmung`, + html: emailHtml, + }, { + context: 'authorization-request', + customerId, + triggeredBy: req.user?.email, + }); + + if (!result.success) { + return res.status(400).json({ + success: false, + error: `E-Mail-Versand fehlgeschlagen: ${result.error}`, + }); + } + } + + // Messaging-Text für WhatsApp/Telegram/Signal + const messageText = `Hallo ${customer.firstName}, ${representative.firstName} ${representative.lastName} möchte als Ihr Vertreter Zugriff auf Ihre Vertragsdaten. Bitte erteilen Sie die Vollmacht im Portal: ${portalUrl}`; + + res.json({ + success: true, + data: { channel, portalUrl, messageText }, + }); + } catch (error) { + console.error('Fehler beim Senden der Vollmacht-Anfrage:', error); + res.status(500).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Senden', + }); + } +} + +/** + * Vollmachten für einen Kunden abrufen (Admin-Ansicht) + */ +export async function getAuthorizations(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + // Sicherstellen dass Einträge für alle aktiven Vertreter existieren + await authorizationService.ensureAuthorizationEntries(customerId); + const authorizations = await authorizationService.getAuthorizationsForCustomer(customerId); + res.json({ success: true, data: authorizations }); + } catch (error) { + console.error('Fehler beim Laden der Vollmachten:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden der Vollmachten' }); + } +} + +/** + * Vollmacht erteilen (Admin: z.B. Papier-Upload) + */ +export async function grantAuthorization(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const representativeId = parseInt(req.params.representativeId); + const { source, notes } = req.body; + + const auth = await authorizationService.grantAuthorization(customerId, representativeId, { + source: source || 'crm-backend', + notes, + }); + + res.json({ success: true, data: auth }); + } catch (error) { + console.error('Fehler beim Erteilen der Vollmacht:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Erteilen der Vollmacht', + }); + } +} + +/** + * Vollmacht widerrufen + */ +export async function withdrawAuthorization(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const representativeId = parseInt(req.params.representativeId); + + const auth = await authorizationService.withdrawAuthorization(customerId, representativeId); + res.json({ success: true, data: auth }); + } catch (error) { + console.error('Fehler beim Widerrufen der Vollmacht:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Widerrufen', + }); + } +} + +/** + * Vollmacht-Dokument hochladen (PDF) + */ +export async function uploadAuthorizationDocument(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const representativeId = parseInt(req.params.representativeId); + + if (!req.file) { + return res.status(400).json({ success: false, error: 'Keine Datei hochgeladen' }); + } + + const documentPath = `/uploads/authorizations/${req.file.filename}`; + const auth = await authorizationService.updateAuthorizationDocument( + customerId, + representativeId, + documentPath + ); + + res.json({ success: true, data: auth }); + } catch (error) { + console.error('Fehler beim Upload des Vollmacht-Dokuments:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Upload', + }); + } +} + +/** + * Vollmacht-Dokument löschen + */ +export async function deleteAuthorizationDocument(req: AuthRequest, res: Response) { + try { + const customerId = parseInt(req.params.customerId); + const representativeId = parseInt(req.params.representativeId); + + const auth = await authorizationService.deleteAuthorizationDocument(customerId, representativeId); + res.json({ success: true, data: auth }); + } catch (error) { + console.error('Fehler beim Löschen des Vollmacht-Dokuments:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Löschen', + }); + } +} + +/** + * Portal: Eigene Vollmachten abrufen (welche Vertreter dürfen meine Daten sehen?) + */ +export async function getMyAuthorizations(req: AuthRequest, res: Response) { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + return res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + } + + await authorizationService.ensureAuthorizationEntries(user.customerId); + const authorizations = await authorizationService.getAuthorizationsForCustomer(user.customerId); + res.json({ success: true, data: authorizations }); + } catch (error) { + console.error('Fehler beim Laden der eigenen Vollmachten:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden' }); + } +} + +/** + * Portal: Vollmacht erteilen/widerrufen + */ +export async function toggleMyAuthorization(req: AuthRequest, res: Response) { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + return res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + } + + const representativeId = parseInt(req.params.representativeId); + const { grant } = req.body; + + let auth; + if (grant) { + auth = await authorizationService.grantAuthorization(user.customerId, representativeId, { + source: 'portal', + }); + } else { + auth = await authorizationService.withdrawAuthorization(user.customerId, representativeId); + } + + res.json({ success: true, data: auth }); + } catch (error) { + console.error('Fehler beim Ändern der Vollmacht:', error); + res.status(400).json({ + success: false, + error: error instanceof Error ? error.message : 'Fehler beim Ändern', + }); + } +} + +/** + * Portal: Prüfe Vollmacht-Status für alle vertretenen Kunden + */ +export async function getMyAuthorizationStatus(req: AuthRequest, res: Response) { + try { + const user = req.user as any; + if (!user?.isCustomerPortal || !user?.customerId) { + return res.status(403).json({ success: false, error: 'Nur für Kundenportal-Benutzer' }); + } + + // IDs der Kunden die dieser Vertreter vertritt + const representedIds: number[] = user.representedCustomerIds || []; + + // Für jeden vertretenen Kunden prüfen ob Vollmacht erteilt + const statuses: { customerId: number; hasAuthorization: boolean }[] = []; + for (const custId of representedIds) { + const has = await authorizationService.hasAuthorization(custId, user.customerId); + statuses.push({ customerId: custId, hasAuthorization: has }); + } + + res.json({ success: true, data: statuses }); + } catch (error) { + console.error('Fehler beim Vollmacht-Status:', error); + res.status(500).json({ success: false, error: 'Fehler beim Laden' }); + } +} diff --git a/backend/src/index.ts b/backend/src/index.ts index 76a39fa3..644aa561 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -26,6 +26,12 @@ import emailProviderRoutes from './routes/emailProvider.routes.js'; import cachedEmailRoutes from './routes/cachedEmail.routes.js'; import invoiceRoutes from './routes/invoice.routes.js'; import contractHistoryRoutes from './routes/contractHistory.routes.js'; +import auditLogRoutes from './routes/auditLog.routes.js'; +import gdprRoutes from './routes/gdpr.routes.js'; +import consentPublicRoutes from './routes/consent-public.routes.js'; +import emailLogRoutes from './routes/emailLog.routes.js'; +import { auditContextMiddleware } from './middleware/auditContext.js'; +import { auditMiddleware } from './middleware/audit.js'; dotenv.config(); @@ -36,9 +42,16 @@ const PORT = process.env.PORT || 3001; app.use(cors()); app.use(express.json()); +// Audit-Logging Middleware (DSGVO-konform) +app.use(auditContextMiddleware); +app.use(auditMiddleware); + // Statische Dateien für Uploads app.use('/api/uploads', express.static(path.join(process.cwd(), 'uploads'))); +// Öffentliche Routes (OHNE Authentifizierung) +app.use('/api/public/consent', consentPublicRoutes); + // Routes app.use('/api/auth', authRoutes); app.use('/api/customers', customerRoutes); @@ -63,6 +76,9 @@ app.use('/api/email-providers', emailProviderRoutes); app.use('/api', cachedEmailRoutes); app.use('/api/energy-details', invoiceRoutes); app.use('/api', contractHistoryRoutes); +app.use('/api/audit-logs', auditLogRoutes); +app.use('/api/gdpr', gdprRoutes); +app.use('/api/email-logs', emailLogRoutes); // Health check app.get('/api/health', (req, res) => { diff --git a/backend/src/lib/prisma.ts b/backend/src/lib/prisma.ts new file mode 100644 index 00000000..f6f73875 --- /dev/null +++ b/backend/src/lib/prisma.ts @@ -0,0 +1,134 @@ +import { PrismaClient, Prisma } from '@prisma/client'; +import { setBeforeValues, setAfterValues } from '../middleware/auditContext.js'; + +// Modelle die für Before/After-Tracking relevant sind +const AUDITED_MODELS = [ + 'Customer', + 'Contract', + 'Address', + 'BankCard', + 'IdentityDocument', + 'User', + 'Meter', + 'MeterReading', + 'StressfreiEmail', + 'Provider', + 'Tariff', + 'ContractCategory', + 'AppSetting', + 'CustomerConsent', +]; + +// Sensible Felder die aus dem Audit-Log gefiltert werden +const SENSITIVE_FIELDS = [ + 'password', + 'passwordHash', + 'portalPasswordHash', + 'portalPasswordEncrypted', + 'emailPasswordEncrypted', + 'internetPasswordEncrypted', + 'sipPasswordEncrypted', + 'pin', + 'puk', + 'apiKey', +]; + +/** + * Filtert sensible Felder aus einem Objekt + */ +function filterSensitiveFields(obj: Record): Record { + const filtered: Record = {}; + for (const [key, value] of Object.entries(obj)) { + if (SENSITIVE_FIELDS.includes(key)) { + filtered[key] = '[REDACTED]'; + } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) { + filtered[key] = filterSensitiveFields(value as Record); + } else { + filtered[key] = value; + } + } + return filtered; +} + +/** + * Prüft ob ein Model für Audit-Tracking relevant ist + */ +function isAuditedModel(model: string | undefined): boolean { + return model !== undefined && AUDITED_MODELS.includes(model); +} + +/** + * Erstellt einen Prisma Client mit Audit-Middleware + */ +function createPrismaClient(): PrismaClient { + const prisma = new PrismaClient(); + + // Middleware für Before/After-Tracking + prisma.$use(async (params: Prisma.MiddlewareParams, next: (params: Prisma.MiddlewareParams) => Promise) => { + const { model, action, args } = params; + + // Nur relevante Modelle und Aktionen tracken + if (!isAuditedModel(model)) { + return next(params); + } + + // Update-Operationen: Vorherigen Stand abrufen + if (action === 'update' || action === 'updateMany') { + try { + const modelDelegate = (prisma as unknown as Record Promise }>)[ + model!.charAt(0).toLowerCase() + model!.slice(1) + ]; + + if (modelDelegate && args?.where) { + const before = await modelDelegate.findUnique({ where: args.where }); + if (before) { + setBeforeValues(filterSensitiveFields(before as Record)); + } + } + } catch { + // Fehler beim Abrufen des vorherigen Stands ignorieren + } + } + + // Delete-Operationen: Datensatz vor dem Löschen abrufen + if (action === 'delete' || action === 'deleteMany') { + try { + const modelDelegate = (prisma as unknown as Record Promise }>)[ + model!.charAt(0).toLowerCase() + model!.slice(1) + ]; + + if (modelDelegate && args?.where) { + const before = await modelDelegate.findUnique({ where: args.where }); + if (before) { + setBeforeValues(filterSensitiveFields(before as Record)); + } + } + } catch { + // Fehler beim Abrufen ignorieren + } + } + + // Operation ausführen + const result = await next(params); + + // Nach Update/Create: Neuen Stand speichern + if ((action === 'update' || action === 'create') && result) { + setAfterValues(filterSensitiveFields(result as Record)); + } + + return result; + }); + + return prisma; +} + +// Singleton-Instanz +const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined }; + +export const prisma = globalForPrisma.prisma ?? createPrismaClient(); + +if (process.env.NODE_ENV !== 'production') { + globalForPrisma.prisma = prisma; +} + +export default prisma; diff --git a/backend/src/middleware/audit.ts b/backend/src/middleware/audit.ts new file mode 100644 index 00000000..1da673c3 --- /dev/null +++ b/backend/src/middleware/audit.ts @@ -0,0 +1,213 @@ +import { Response, NextFunction } from 'express'; +import { AuditAction } from '@prisma/client'; +import { AuthRequest } from '../types/index.js'; +import { createAuditLog } from '../services/audit.service.js'; +import { getAuditContext, AuditContext } from './auditContext.js'; + +// Resource-Typ-Mapping basierend auf Route-Patterns +const RESOURCE_MAPPING: Record string | undefined }> = { + '/api/customers': { type: 'Customer', extractId: (req) => req.params.id || req.params.customerId }, + '/api/customers/*/bank-cards': { type: 'BankCard', extractId: (req) => req.params.bankCardId }, + '/api/customers/*/documents': { type: 'IdentityDocument', extractId: (req) => req.params.documentId }, + '/api/customers/*/addresses': { type: 'Address', extractId: (req) => req.params.addressId }, + '/api/customers/*/meters': { type: 'Meter', extractId: (req) => req.params.meterId }, + '/api/customers/*/consents': { type: 'CustomerConsent', extractId: (req) => req.params.type }, + '/api/contracts': { type: 'Contract', extractId: (req) => req.params.id }, + '/api/contracts/*/history': { type: 'ContractHistoryEntry', extractId: (req) => req.params.entryId }, + '/api/contracts/*/tasks': { type: 'ContractTask', extractId: (req) => req.params.taskId }, + '/api/users': { type: 'User', extractId: (req) => req.params.id }, + '/api/providers': { type: 'Provider', extractId: (req) => req.params.id }, + '/api/tariffs': { type: 'Tariff', extractId: (req) => req.params.id }, + '/api/platforms': { type: 'SalesPlatform', extractId: (req) => req.params.id }, + '/api/contract-categories': { type: 'ContractCategory', extractId: (req) => req.params.id }, + '/api/cancellation-periods': { type: 'CancellationPeriod', extractId: (req) => req.params.id }, + '/api/contract-durations': { type: 'ContractDuration', extractId: (req) => req.params.id }, + '/api/settings': { type: 'AppSetting', extractId: (req) => req.params.key }, + '/api/email-providers': { type: 'EmailProviderConfig', extractId: (req) => req.params.id }, + '/api/auth': { type: 'Authentication' }, + '/api/audit-logs': { type: 'AuditLog', extractId: (req) => req.params.id }, + '/api/gdpr': { type: 'GDPR' }, +}; + +// Routen die nicht geloggt werden sollen +const EXCLUDED_ROUTES = [ + '/api/health', + '/api/uploads', +]; + +/** + * Bestimmt die Aktion basierend auf HTTP-Methode und Erfolg + */ +function determineAction(method: string, path: string, success: boolean): AuditAction { + // Spezielle Auth-Aktionen + if (path.includes('/auth/login')) { + return success ? 'LOGIN' : 'LOGIN_FAILED'; + } + if (path.includes('/auth/logout')) { + return 'LOGOUT'; + } + + // Standard CRUD-Aktionen + switch (method.toUpperCase()) { + case 'GET': + return 'READ'; + case 'POST': + return 'CREATE'; + case 'PUT': + case 'PATCH': + return 'UPDATE'; + case 'DELETE': + return 'DELETE'; + default: + return 'READ'; + } +} + +/** + * Findet den passenden Resource-Typ für einen Pfad + */ +function findResourceMapping(path: string): { type: string; extractId?: (req: AuthRequest) => string | undefined } | null { + // Exakte Matches zuerst prüfen + for (const [pattern, mapping] of Object.entries(RESOURCE_MAPPING)) { + // Konvertiere Pattern zu Regex + const regexPattern = pattern + .replace(/\*/g, '[^/]+') + .replace(/\//g, '\\/'); + const regex = new RegExp(`^${regexPattern}(?:/|$)`); + + if (regex.test(path)) { + return mapping; + } + } + return null; +} + +/** + * Extrahiert die betroffene Kunden-ID für DSGVO-Tracking + */ +function extractDataSubjectId(req: AuthRequest): number | undefined { + // Aus Route-Parameter + const customerId = req.params.customerId || req.params.id; + if (customerId && req.path.includes('/customers')) { + return parseInt(customerId); + } + + // Aus Request-Body (bei Create) + if (req.body?.customerId) { + return parseInt(req.body.customerId); + } + + // Bei Kundenportal-Zugriff + if (req.user?.customerId) { + return req.user.customerId; + } + + return undefined; +} + +/** + * Extrahiert die IP-Adresse des Clients + */ +function getClientIp(req: AuthRequest): string { + const forwarded = req.headers['x-forwarded-for']; + if (typeof forwarded === 'string') { + return forwarded.split(',')[0].trim(); + } + return req.socket.remoteAddress || 'unknown'; +} + +/** + * Audit Middleware - loggt alle API-Aufrufe asynchron + */ +export function auditMiddleware(req: AuthRequest, res: Response, next: NextFunction): void { + const startTime = Date.now(); + + // Ausgeschlossene Routen überspringen + if (EXCLUDED_ROUTES.some((route) => req.path.startsWith(route))) { + next(); + return; + } + + // Resource-Mapping finden + const mapping = findResourceMapping(req.path); + if (!mapping) { + // Unbekannte Route - trotzdem loggen mit generischem Typ + next(); + return; + } + + // Original res.json überschreiben um Response zu capturen + const originalJson = res.json.bind(res); + let responseBody: unknown = null; + let responseSuccess = true; + + res.json = function (body: unknown) { + responseBody = body; + if (typeof body === 'object' && body !== null && 'success' in body) { + responseSuccess = (body as { success: boolean }).success; + } + return originalJson(body); + }; + + // Response-Ende abfangen für Logging + res.on('finish', () => { + // Async Logging - blockiert nicht die Response + setImmediate(async () => { + try { + const durationMs = Date.now() - startTime; + const action = determineAction(req.method, req.path, responseSuccess); + const resourceId = mapping.extractId?.(req); + const dataSubjectId = extractDataSubjectId(req); + + // Audit-Kontext abrufen (enthält Before/After-Werte von Prisma Middleware) + const auditContext = getAuditContext(); + + // Label für bessere Lesbarkeit generieren + let resourceLabel: string | undefined; + if (responseBody && typeof responseBody === 'object' && 'data' in responseBody) { + const data = (responseBody as { data: Record }).data; + if (data) { + // Versuche verschiedene Label-Felder + resourceLabel = + (data.contractNumber as string) || + (data.customerNumber as string) || + (data.name as string) || + (data.email as string) || + (data.firstName && data.lastName + ? `${data.firstName} ${data.lastName}` + : undefined); + } + } + + await createAuditLog({ + userId: req.user?.userId, + userEmail: req.user?.email || 'anonymous', + userRole: req.user?.permissions?.join(', '), + customerId: req.user?.customerId, + isCustomerPortal: req.user?.isCustomerPortal, + action, + resourceType: mapping.type, + resourceId, + resourceLabel, + endpoint: req.path, + httpMethod: req.method, + ipAddress: getClientIp(req), + userAgent: req.headers['user-agent'], + changesBefore: auditContext?.before, + changesAfter: auditContext?.after, + dataSubjectId, + success: responseSuccess, + errorMessage: !responseSuccess && responseBody && typeof responseBody === 'object' && 'error' in responseBody + ? (responseBody as { error: string }).error + : undefined, + durationMs, + }); + } catch (error) { + // Audit-Logging darf niemals die Anwendung beeinträchtigen + console.error('[AuditMiddleware] Fehler beim Logging:', error); + } + }); + }); + + next(); +} diff --git a/backend/src/middleware/auditContext.ts b/backend/src/middleware/auditContext.ts new file mode 100644 index 00000000..0542d088 --- /dev/null +++ b/backend/src/middleware/auditContext.ts @@ -0,0 +1,60 @@ +import { AsyncLocalStorage } from 'async_hooks'; + +/** + * Audit-Kontext für die Übertragung von Before/After-Werten + * zwischen Prisma-Middleware und Audit-Middleware + */ +export interface AuditContext { + before?: Record; + after?: Record; +} + +// AsyncLocalStorage für den Audit-Kontext +const auditStorage = new AsyncLocalStorage(); + +/** + * Startet einen neuen Audit-Kontext für einen Request + */ +export function runWithAuditContext(fn: () => T): T { + return auditStorage.run({}, fn); +} + +/** + * Setzt die "Before"-Werte im aktuellen Kontext + */ +export function setBeforeValues(values: Record): void { + const context = auditStorage.getStore(); + if (context) { + context.before = values; + } +} + +/** + * Setzt die "After"-Werte im aktuellen Kontext + */ +export function setAfterValues(values: Record): void { + const context = auditStorage.getStore(); + if (context) { + context.after = values; + } +} + +/** + * Holt den aktuellen Audit-Kontext + */ +export function getAuditContext(): AuditContext | undefined { + return auditStorage.getStore(); +} + +/** + * Express Middleware zum Initialisieren des Audit-Kontexts + */ +export function auditContextMiddleware( + req: unknown, + res: unknown, + next: () => void +): void { + runWithAuditContext(() => { + next(); + }); +} diff --git a/backend/src/middleware/auth.ts b/backend/src/middleware/auth.ts index b94749f2..f2ab5485 100644 --- a/backend/src/middleware/auth.ts +++ b/backend/src/middleware/auth.ts @@ -114,9 +114,14 @@ export function requireCustomerAccess( return; } - // Customers can only access their own data + // Customers can only access their own data + represented customers const customerId = parseInt(req.params.customerId || req.params.id); - if (req.user.customerId && req.user.customerId === customerId) { + const allowedIds = [ + req.user.customerId, + ...((req.user as any).representedCustomerIds || []), + ].filter(Boolean); + + if (allowedIds.includes(customerId)) { next(); return; } diff --git a/backend/src/routes/auditLog.routes.ts b/backend/src/routes/auditLog.routes.ts new file mode 100644 index 00000000..4c474dd1 --- /dev/null +++ b/backend/src/routes/auditLog.routes.ts @@ -0,0 +1,32 @@ +import { Router } from 'express'; +import { authenticate, requirePermission } from '../middleware/auth.js'; +import * as auditLogController from '../controllers/auditLog.controller.js'; + +const router = Router(); + +// Alle Routen erfordern Authentifizierung +router.use(authenticate); + +// Audit-Logs abrufen +router.get('/', requirePermission('audit:read'), auditLogController.getAuditLogs); + +// Einzelnes Audit-Log abrufen +router.get('/:id', requirePermission('audit:read'), auditLogController.getAuditLogById); + +// Audit-Logs für einen Kunden (DSGVO) +router.get('/customer/:customerId', requirePermission('audit:read'), auditLogController.getAuditLogsByCustomer); + +// Audit-Logs exportieren +router.get('/export', requirePermission('audit:export'), auditLogController.exportAuditLogs); + +// Hash-Ketten-Integrität prüfen +router.post('/verify', requirePermission('audit:admin'), auditLogController.verifyIntegrity); + +// Retention-Policies +router.get('/retention-policies', requirePermission('audit:admin'), auditLogController.getRetentionPolicies); +router.put('/retention-policies/:id', requirePermission('audit:admin'), auditLogController.updateRetentionPolicy); + +// Retention-Cleanup manuell ausführen +router.post('/cleanup', requirePermission('audit:admin'), auditLogController.runRetentionCleanup); + +export default router; diff --git a/backend/src/routes/consent-public.routes.ts b/backend/src/routes/consent-public.routes.ts new file mode 100644 index 00000000..db225615 --- /dev/null +++ b/backend/src/routes/consent-public.routes.ts @@ -0,0 +1,11 @@ +import { Router } from 'express'; +import * as controller from '../controllers/consent-public.controller.js'; + +const router = Router(); + +// Öffentliche Routes - KEINE Authentifizierung erforderlich +router.get('/:hash', controller.getConsentPage); +router.post('/:hash/grant', controller.grantAllConsents); +router.get('/:hash/pdf', controller.getConsentPdf); + +export default router; diff --git a/backend/src/routes/emailLog.routes.ts b/backend/src/routes/emailLog.routes.ts new file mode 100644 index 00000000..25078fb4 --- /dev/null +++ b/backend/src/routes/emailLog.routes.ts @@ -0,0 +1,13 @@ +import { Router } from 'express'; +import { authenticate, requirePermission } from '../middleware/auth.js'; +import * as emailLogController from '../controllers/emailLog.controller.js'; + +const router = Router(); + +router.use(authenticate); + +router.get('/', requirePermission('gdpr:admin'), emailLogController.getEmailLogs); +router.get('/stats', requirePermission('gdpr:admin'), emailLogController.getEmailLogStats); +router.get('/:id', requirePermission('gdpr:admin'), emailLogController.getEmailLogDetail); + +export default router; diff --git a/backend/src/routes/gdpr.routes.ts b/backend/src/routes/gdpr.routes.ts new file mode 100644 index 00000000..9dc1b5e4 --- /dev/null +++ b/backend/src/routes/gdpr.routes.ts @@ -0,0 +1,84 @@ +import { Router } from 'express'; +import multer from 'multer'; +import path from 'path'; +import fs from 'fs'; +import { authenticate, requirePermission } from '../middleware/auth.js'; +import * as gdprController from '../controllers/gdpr.controller.js'; + +const router = Router(); + +// Multer für Vollmacht-Uploads +const uploadsDir = path.join(process.cwd(), 'uploads', 'authorizations'); +if (!fs.existsSync(uploadsDir)) { + fs.mkdirSync(uploadsDir, { recursive: true }); +} +const authUpload = multer({ + storage: multer.diskStorage({ + destination: (_req, _file, cb) => cb(null, uploadsDir), + filename: (_req, file, cb) => { + const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9); + cb(null, `vollmacht-${uniqueSuffix}${path.extname(file.originalname)}`); + }, + }), + fileFilter: (_req, file, cb) => { + if (file.mimetype === 'application/pdf') { + cb(null, true); + } else { + cb(new Error('Nur PDF-Dateien sind erlaubt')); + } + }, + limits: { fileSize: 10 * 1024 * 1024 }, +}); + +// Alle Routen erfordern Authentifizierung +router.use(authenticate); + +// Dashboard-Statistiken +router.get('/dashboard', requirePermission('gdpr:admin'), gdprController.getDashboardStats); + +// Kundendaten exportieren (DSGVO Art. 15) +router.get('/customer/:customerId/export', requirePermission('gdpr:export'), gdprController.exportCustomerData); + +// Löschanfragen +router.get('/deletions', requirePermission('gdpr:admin'), gdprController.getDeletionRequests); +router.get('/deletions/:id', requirePermission('gdpr:admin'), gdprController.getDeletionRequest); +router.post('/deletions', requirePermission('gdpr:delete'), gdprController.createDeletionRequest); +router.put('/deletions/:id/process', requirePermission('gdpr:admin'), gdprController.processDeletionRequest); + +// Einwilligungen (Consents) +router.get('/customer/:customerId/consent-status', requirePermission('customers:read'), gdprController.checkConsentStatus); +router.get('/customer/:customerId/consents', requirePermission('customers:read'), gdprController.getCustomerConsents); +// Consent-Update: Nur authenticate (Check im Controller - nur Portal-User erlaubt) +router.put('/customer/:customerId/consents/:consentType', gdprController.updateCustomerConsent); +router.get('/consents/overview', requirePermission('gdpr:admin'), gdprController.getConsentOverview); + +// Datenschutzerklärung (Editor) +router.get('/privacy-policy', requirePermission('gdpr:admin'), gdprController.getPrivacyPolicy); +router.put('/privacy-policy', requirePermission('gdpr:admin'), gdprController.updatePrivacyPolicy); + +// Vollmacht-Vorlage (Editor) +router.get('/authorization-template', requirePermission('gdpr:admin'), gdprController.getAuthorizationTemplate); +router.put('/authorization-template', requirePermission('gdpr:admin'), gdprController.updateAuthorizationTemplate); + +// Consent-Link senden +router.post('/customer/:customerId/send-consent-link', requirePermission('customers:update'), gdprController.sendConsentLink); + +// Portal: Eigene Datenschutzseite (nur authenticate, Check im Controller) +router.get('/my-privacy', gdprController.getMyPrivacy); +router.get('/my-privacy/pdf', gdprController.getMyPrivacyPdf); +router.get('/my-consent-status', gdprController.getMyConsentStatus); + +// Vollmachten (Admin) +router.get('/customer/:customerId/authorizations', requirePermission('customers:read'), gdprController.getAuthorizations); +router.post('/customer/:customerId/authorizations/:representativeId/send', requirePermission('customers:update'), gdprController.sendAuthorizationRequest); +router.post('/customer/:customerId/authorizations/:representativeId/grant', requirePermission('customers:update'), gdprController.grantAuthorization); +router.post('/customer/:customerId/authorizations/:representativeId/withdraw', requirePermission('customers:update'), gdprController.withdrawAuthorization); +router.post('/customer/:customerId/authorizations/:representativeId/upload', requirePermission('customers:update'), authUpload.single('document'), gdprController.uploadAuthorizationDocument); +router.delete('/customer/:customerId/authorizations/:representativeId/document', requirePermission('customers:update'), gdprController.deleteAuthorizationDocument); + +// Portal: Vollmachten +router.get('/my-authorizations', gdprController.getMyAuthorizations); +router.put('/my-authorizations/:representativeId', gdprController.toggleMyAuthorization); +router.get('/my-authorization-status', gdprController.getMyAuthorizationStatus); + +export default router; diff --git a/backend/src/routes/meter.routes.ts b/backend/src/routes/meter.routes.ts index 7b10f81c..c3f60046 100644 --- a/backend/src/routes/meter.routes.ts +++ b/backend/src/routes/meter.routes.ts @@ -13,4 +13,13 @@ router.post('/:meterId/readings', authenticate, requirePermission('customers:upd router.put('/:meterId/readings/:readingId', authenticate, requirePermission('customers:update'), customerController.updateMeterReading); router.delete('/:meterId/readings/:readingId', authenticate, requirePermission('customers:delete'), customerController.deleteMeterReading); +// Status-Update (Zählerstand als übertragen markieren) +router.patch('/:meterId/readings/:readingId/transfer', authenticate, requirePermission('customers:update'), customerController.markReadingTransferred); + +// Portal: Zählerstand melden (Kunde) +router.post('/:meterId/readings/report', authenticate, customerController.reportMeterReading); + +// Portal: Eigene Zähler laden +router.get('/my-meters', authenticate, customerController.getMyMeters); + export default router; diff --git a/backend/src/services/appSetting.service.ts b/backend/src/services/appSetting.service.ts index a3aad90c..0d1034cd 100644 --- a/backend/src/services/appSetting.service.ts +++ b/backend/src/services/appSetting.service.ts @@ -9,6 +9,9 @@ const DEFAULT_SETTINGS: Record = { deadlineCriticalDays: '14', // Rot: Kritisch deadlineWarningDays: '42', // Gelb: Warnung (6 Wochen) deadlineOkDays: '90', // Grün: OK (3 Monate) + // Ausweis-Ablauf: Fristenschwellen (in Tagen) + documentExpiryCriticalDays: '30', // Rot: Kritisch (Standard 30 Tage) + documentExpiryWarningDays: '90', // Gelb: Warnung (Standard 90 Tage) }; export async function getSetting(key: string): Promise { diff --git a/backend/src/services/audit.service.ts b/backend/src/services/audit.service.ts new file mode 100644 index 00000000..2e48a203 --- /dev/null +++ b/backend/src/services/audit.service.ts @@ -0,0 +1,504 @@ +import { AuditAction, AuditSensitivity, Prisma } from '@prisma/client'; +import crypto from 'crypto'; +import { encrypt, decrypt } from '../utils/encryption.js'; +import prisma from '../lib/prisma.js'; + +export interface CreateAuditLogData { + userId?: number; + userEmail: string; + userRole?: string; + customerId?: number; + isCustomerPortal?: boolean; + action: AuditAction; + sensitivity?: AuditSensitivity; + resourceType: string; + resourceId?: string; + resourceLabel?: string; + endpoint: string; + httpMethod: string; + ipAddress: string; + userAgent?: string; + changesBefore?: Record; + changesAfter?: Record; + dataSubjectId?: number; + legalBasis?: string; + success?: boolean; + errorMessage?: string; + durationMs?: number; +} + +export interface AuditLogSearchParams { + userId?: number; + customerId?: number; + dataSubjectId?: number; + action?: AuditAction; + sensitivity?: AuditSensitivity; + resourceType?: string; + resourceId?: string; + startDate?: Date; + endDate?: Date; + success?: boolean; + search?: string; + page?: number; + limit?: number; +} + +/** + * Generiert einen SHA-256 Hash für einen Audit-Log-Eintrag + */ +function generateHash(data: { + userEmail: string; + action: AuditAction; + resourceType: string; + resourceId?: string | null; + endpoint: string; + createdAt: Date; + previousHash?: string | null; +}): string { + const content = JSON.stringify({ + userEmail: data.userEmail, + action: data.action, + resourceType: data.resourceType, + resourceId: data.resourceId, + endpoint: data.endpoint, + createdAt: data.createdAt.toISOString(), + previousHash: data.previousHash || '', + }); + return crypto.createHash('sha256').update(content).digest('hex'); +} + +/** + * Bestimmt die Sensitivität basierend auf dem Ressourcentyp + */ +function determineSensitivity(resourceType: string): AuditSensitivity { + const sensitivityMap: Record = { + // CRITICAL + Authentication: 'CRITICAL', + BankCard: 'CRITICAL', + IdentityDocument: 'CRITICAL', + // HIGH + Customer: 'HIGH', + User: 'HIGH', + CustomerConsent: 'HIGH', + DataDeletionRequest: 'HIGH', + // MEDIUM + Contract: 'MEDIUM', + Address: 'MEDIUM', + Meter: 'MEDIUM', + MeterReading: 'MEDIUM', + StressfreiEmail: 'MEDIUM', + CachedEmail: 'MEDIUM', + // LOW + Provider: 'LOW', + Tariff: 'LOW', + SalesPlatform: 'LOW', + AppSetting: 'LOW', + ContractCategory: 'LOW', + CancellationPeriod: 'LOW', + ContractDuration: 'LOW', + }; + return sensitivityMap[resourceType] || 'MEDIUM'; +} + +/** + * Prüft ob Änderungen verschlüsselt werden sollen + */ +function shouldEncryptChanges(resourceType: string): boolean { + const encryptedTypes = [ + 'BankCard', + 'IdentityDocument', + 'User', + 'Customer', // Enthält Portal-Passwörter + ]; + return encryptedTypes.includes(resourceType); +} + +/** + * Erstellt einen neuen Audit-Log-Eintrag mit Hash-Kette + */ +export async function createAuditLog(data: CreateAuditLogData): Promise { + try { + // Letzten Hash abrufen für die Kette + const lastLog = await prisma.auditLog.findFirst({ + orderBy: { id: 'desc' }, + select: { hash: true }, + }); + + const previousHash = lastLog?.hash || null; + const createdAt = new Date(); + + // Sensitivität bestimmen falls nicht angegeben + const sensitivity = data.sensitivity || determineSensitivity(data.resourceType); + + // Änderungen serialisieren und ggf. verschlüsseln + let changesBefore: string | null = null; + let changesAfter: string | null = null; + let changesEncrypted = false; + + if (data.changesBefore || data.changesAfter) { + changesEncrypted = shouldEncryptChanges(data.resourceType); + + if (data.changesBefore) { + const json = JSON.stringify(data.changesBefore); + changesBefore = changesEncrypted ? encrypt(json) : json; + } + + if (data.changesAfter) { + const json = JSON.stringify(data.changesAfter); + changesAfter = changesEncrypted ? encrypt(json) : json; + } + } + + // Hash generieren + const hash = generateHash({ + userEmail: data.userEmail, + action: data.action, + resourceType: data.resourceType, + resourceId: data.resourceId, + endpoint: data.endpoint, + createdAt, + previousHash, + }); + + // Eintrag erstellen + await prisma.auditLog.create({ + data: { + userId: data.userId, + userEmail: data.userEmail, + userRole: data.userRole, + customerId: data.customerId, + isCustomerPortal: data.isCustomerPortal || false, + action: data.action, + sensitivity, + resourceType: data.resourceType, + resourceId: data.resourceId, + resourceLabel: data.resourceLabel, + endpoint: data.endpoint, + httpMethod: data.httpMethod, + ipAddress: data.ipAddress, + userAgent: data.userAgent, + changesBefore, + changesAfter, + changesEncrypted, + dataSubjectId: data.dataSubjectId, + legalBasis: data.legalBasis, + success: data.success ?? true, + errorMessage: data.errorMessage, + durationMs: data.durationMs, + createdAt, + hash, + previousHash, + }, + }); + } catch (error) { + // Audit-Logging darf niemals die Hauptoperation blockieren + console.error('[AuditService] Fehler beim Erstellen des Audit-Logs:', error); + } +} + +/** + * Sucht Audit-Logs mit Filtern und Paginierung + */ +export async function searchAuditLogs(params: AuditLogSearchParams) { + const { + userId, + customerId, + dataSubjectId, + action, + sensitivity, + resourceType, + resourceId, + startDate, + endDate, + success, + search, + page = 1, + limit = 50, + } = params; + + const where: Prisma.AuditLogWhereInput = {}; + + if (userId !== undefined) where.userId = userId; + if (customerId !== undefined) where.customerId = customerId; + if (dataSubjectId !== undefined) where.dataSubjectId = dataSubjectId; + if (action) where.action = action; + if (sensitivity) where.sensitivity = sensitivity; + if (resourceType) where.resourceType = resourceType; + if (resourceId) where.resourceId = resourceId; + if (success !== undefined) where.success = success; + + if (startDate || endDate) { + where.createdAt = {}; + if (startDate) where.createdAt.gte = startDate; + if (endDate) where.createdAt.lte = endDate; + } + + if (search) { + where.OR = [ + { userEmail: { contains: search } }, + { resourceLabel: { contains: search } }, + { endpoint: { contains: search } }, + ]; + } + + const [logs, total] = await Promise.all([ + prisma.auditLog.findMany({ + where, + orderBy: { createdAt: 'desc' }, + skip: (page - 1) * limit, + take: limit, + }), + prisma.auditLog.count({ where }), + ]); + + // Entschlüsselung der Änderungen wenn nötig + const decryptedLogs = logs.map((log) => ({ + ...log, + changesBefore: log.changesBefore && log.changesEncrypted + ? JSON.parse(decrypt(log.changesBefore)) + : log.changesBefore ? JSON.parse(log.changesBefore) : null, + changesAfter: log.changesAfter && log.changesEncrypted + ? JSON.parse(decrypt(log.changesAfter)) + : log.changesAfter ? JSON.parse(log.changesAfter) : null, + })); + + return { + data: decryptedLogs, + pagination: { + page, + limit, + total, + totalPages: Math.ceil(total / limit), + }, + }; +} + +/** + * Holt einen einzelnen Audit-Log-Eintrag + */ +export async function getAuditLogById(id: number) { + const log = await prisma.auditLog.findUnique({ + where: { id }, + }); + + if (!log) return null; + + return { + ...log, + changesBefore: log.changesBefore && log.changesEncrypted + ? JSON.parse(decrypt(log.changesBefore)) + : log.changesBefore ? JSON.parse(log.changesBefore) : null, + changesAfter: log.changesAfter && log.changesEncrypted + ? JSON.parse(decrypt(log.changesAfter)) + : log.changesAfter ? JSON.parse(log.changesAfter) : null, + }; +} + +/** + * Holt alle Audit-Logs für eine betroffene Person (DSGVO) + */ +export async function getAuditLogsByDataSubject(customerId: number) { + const logs = await prisma.auditLog.findMany({ + where: { dataSubjectId: customerId }, + orderBy: { createdAt: 'desc' }, + }); + + return logs.map((log) => ({ + ...log, + changesBefore: log.changesBefore && log.changesEncrypted + ? JSON.parse(decrypt(log.changesBefore)) + : log.changesBefore ? JSON.parse(log.changesBefore) : null, + changesAfter: log.changesAfter && log.changesEncrypted + ? JSON.parse(decrypt(log.changesAfter)) + : log.changesAfter ? JSON.parse(log.changesAfter) : null, + })); +} + +/** + * Verifiziert die Integrität der Hash-Kette + */ +export async function verifyIntegrity(fromId?: number, toId?: number): Promise<{ + valid: boolean; + checkedCount: number; + invalidEntries: number[]; +}> { + const where: Prisma.AuditLogWhereInput = {}; + + if (fromId !== undefined) where.id = { gte: fromId }; + if (toId !== undefined) where.id = { ...(where.id as object || {}), lte: toId }; + + const logs = await prisma.auditLog.findMany({ + where, + orderBy: { id: 'asc' }, + select: { + id: true, + userEmail: true, + action: true, + resourceType: true, + resourceId: true, + endpoint: true, + createdAt: true, + hash: true, + previousHash: true, + }, + }); + + const invalidEntries: number[] = []; + + for (let i = 0; i < logs.length; i++) { + const log = logs[i]; + + // Hash neu berechnen + const expectedHash = generateHash({ + userEmail: log.userEmail, + action: log.action, + resourceType: log.resourceType, + resourceId: log.resourceId, + endpoint: log.endpoint, + createdAt: log.createdAt, + previousHash: log.previousHash, + }); + + // Prüfen ob Hash übereinstimmt + if (log.hash !== expectedHash) { + invalidEntries.push(log.id); + continue; + } + + // Prüfen ob previousHash mit dem Hash des vorherigen Eintrags übereinstimmt + if (i > 0) { + const previousLog = logs[i - 1]; + if (log.previousHash !== previousLog.hash) { + invalidEntries.push(log.id); + } + } + } + + return { + valid: invalidEntries.length === 0, + checkedCount: logs.length, + invalidEntries, + }; +} + +/** + * Exportiert Audit-Logs als JSON oder CSV + */ +export async function exportAuditLogs( + params: AuditLogSearchParams, + format: 'json' | 'csv' = 'json' +): Promise { + // Alle Logs ohne Paginierung + const result = await searchAuditLogs({ ...params, limit: 100000, page: 1 }); + const logs = result.data; + + if (format === 'json') { + return JSON.stringify(logs, null, 2); + } + + // CSV Export + const headers = [ + 'ID', + 'Zeitstempel', + 'Benutzer', + 'Aktion', + 'Ressource', + 'Ressource-ID', + 'Bezeichnung', + 'Endpoint', + 'IP-Adresse', + 'Erfolg', + 'Sensitivität', + ]; + + const rows = logs.map((log) => [ + log.id.toString(), + log.createdAt.toISOString(), + log.userEmail, + log.action, + log.resourceType, + log.resourceId || '', + log.resourceLabel || '', + log.endpoint, + log.ipAddress, + log.success ? 'Ja' : 'Nein', + log.sensitivity, + ]); + + const csvContent = [ + headers.join(';'), + ...rows.map((row) => row.map((cell) => `"${cell.replace(/"/g, '""')}"`).join(';')), + ].join('\n'); + + return csvContent; +} + +/** + * Löscht alte Audit-Logs basierend auf Retention-Policies + * Hinweis: Diese Funktion sollte nur von einem autorisierten Admin-Prozess aufgerufen werden + */ +export async function runRetentionCleanup(): Promise<{ + deletedCount: number; + policies: Array<{ resourceType: string; sensitivity: string | null; deletedCount: number }>; +}> { + const policies = await prisma.auditRetentionPolicy.findMany({ + where: { isActive: true }, + }); + + const results: Array<{ resourceType: string; sensitivity: string | null; deletedCount: number }> = []; + let totalDeleted = 0; + + for (const policy of policies) { + const cutoffDate = new Date(); + cutoffDate.setDate(cutoffDate.getDate() - policy.retentionDays); + + const where: Prisma.AuditLogWhereInput = { + createdAt: { lt: cutoffDate }, + }; + + if (policy.resourceType !== '*') { + where.resourceType = policy.resourceType; + } + + if (policy.sensitivity) { + where.sensitivity = policy.sensitivity; + } + + const deleted = await prisma.auditLog.deleteMany({ where }); + + results.push({ + resourceType: policy.resourceType, + sensitivity: policy.sensitivity, + deletedCount: deleted.count, + }); + + totalDeleted += deleted.count; + } + + return { + deletedCount: totalDeleted, + policies: results, + }; +} + +/** + * Holt die Retention-Policies + */ +export async function getRetentionPolicies() { + return prisma.auditRetentionPolicy.findMany({ + orderBy: [{ resourceType: 'asc' }, { sensitivity: 'asc' }], + }); +} + +/** + * Aktualisiert eine Retention-Policy + */ +export async function updateRetentionPolicy( + id: number, + data: { retentionDays?: number; description?: string; legalBasis?: string; isActive?: boolean } +) { + return prisma.auditRetentionPolicy.update({ + where: { id }, + data, + }); +} diff --git a/backend/src/services/auth.service.ts b/backend/src/services/auth.service.ts index da2a20d5..58e56555 100644 --- a/backend/src/services/auth.service.ts +++ b/backend/src/services/auth.service.ts @@ -283,6 +283,9 @@ export async function getUserById(id: number) { lastName: user.lastName, isActive: user.isActive, customerId: user.customerId, + whatsappNumber: user.whatsappNumber, + telegramUsername: user.telegramUsername, + signalNumber: user.signalNumber, roles: user.roles.map((ur) => ur.role.name), permissions: Array.from(permissions), isCustomerPortal: false, diff --git a/backend/src/services/authorization.service.ts b/backend/src/services/authorization.service.ts new file mode 100644 index 00000000..692da954 --- /dev/null +++ b/backend/src/services/authorization.service.ts @@ -0,0 +1,207 @@ +import prisma from '../lib/prisma.js'; +import fs from 'fs'; +import path from 'path'; + +/** + * Vollmachten für einen Kunden abrufen (wer darf diesen Kunden einsehen?) + */ +export async function getAuthorizationsForCustomer(customerId: number) { + return prisma.representativeAuthorization.findMany({ + where: { customerId }, + include: { + representative: { + select: { id: true, customerNumber: true, firstName: true, lastName: true }, + }, + }, + orderBy: { createdAt: 'desc' }, + }); +} + +/** + * Vollmachten die ein Vertreter erhalten hat (welche Kunden darf er einsehen?) + */ +export async function getAuthorizationsForRepresentative(representativeId: number) { + return prisma.representativeAuthorization.findMany({ + where: { representativeId }, + include: { + customer: { + select: { id: true, customerNumber: true, firstName: true, lastName: true }, + }, + }, + orderBy: { createdAt: 'desc' }, + }); +} + +/** + * Prüft ob ein Vertreter eine Vollmacht für einen Kunden hat + */ +export async function hasAuthorization(customerId: number, representativeId: number): Promise { + const auth = await prisma.representativeAuthorization.findUnique({ + where: { + customerId_representativeId: { customerId, representativeId }, + }, + }); + + return auth?.isGranted === true; +} + +/** + * Vollmacht erteilen oder aktualisieren + */ +export async function grantAuthorization( + customerId: number, + representativeId: number, + data: { source?: string; documentPath?: string; notes?: string } +) { + return prisma.representativeAuthorization.upsert({ + where: { + customerId_representativeId: { customerId, representativeId }, + }, + update: { + isGranted: true, + grantedAt: new Date(), + withdrawnAt: null, + source: data.source, + documentPath: data.documentPath ?? undefined, + notes: data.notes ?? undefined, + }, + create: { + customerId, + representativeId, + isGranted: true, + grantedAt: new Date(), + source: data.source || 'crm-backend', + documentPath: data.documentPath, + notes: data.notes, + }, + }); +} + +/** + * Vollmacht widerrufen + PDF löschen falls vorhanden + */ +export async function withdrawAuthorization(customerId: number, representativeId: number) { + // Erst prüfen ob eine PDF vorhanden ist + const existing = await prisma.representativeAuthorization.findUnique({ + where: { customerId_representativeId: { customerId, representativeId } }, + select: { documentPath: true }, + }); + + // PDF vom Filesystem löschen + if (existing?.documentPath) { + try { + const filePath = path.join(process.cwd(), existing.documentPath); + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + } + } catch (err) { + console.error('Fehler beim Löschen der Vollmacht-PDF:', err); + } + } + + return prisma.representativeAuthorization.update({ + where: { + customerId_representativeId: { customerId, representativeId }, + }, + data: { + isGranted: false, + withdrawnAt: new Date(), + documentPath: null, + }, + }); +} + +/** + * Vollmacht-Dokument (PDF) hochladen + */ +export async function updateAuthorizationDocument( + customerId: number, + representativeId: number, + documentPath: string +) { + // Wenn Dokument hochgeladen wird, gilt das als Vollmacht erteilen + return prisma.representativeAuthorization.upsert({ + where: { + customerId_representativeId: { customerId, representativeId }, + }, + update: { + documentPath, + isGranted: true, + grantedAt: new Date(), + withdrawnAt: null, + source: 'papier', + }, + create: { + customerId, + representativeId, + documentPath, + isGranted: true, + grantedAt: new Date(), + source: 'papier', + }, + }); +} + +/** + * Vollmacht-Dokument löschen + */ +export async function deleteAuthorizationDocument(customerId: number, representativeId: number) { + return prisma.representativeAuthorization.update({ + where: { + customerId_representativeId: { customerId, representativeId }, + }, + data: { + documentPath: null, + }, + }); +} + +/** + * Alle genehmigten Vertreter-IDs für einen Kunden + * (Welche Vertreter dürfen die Verträge dieses Kunden sehen?) + */ +export async function getAuthorizedRepresentativeIds(customerId: number): Promise { + const auths = await prisma.representativeAuthorization.findMany({ + where: { customerId, isGranted: true }, + select: { representativeId: true }, + }); + return auths.map((a) => a.representativeId); +} + +/** + * Alle Kunden-IDs für die ein Vertreter eine Vollmacht hat + */ +export async function getAuthorizedCustomerIds(representativeId: number): Promise { + const auths = await prisma.representativeAuthorization.findMany({ + where: { representativeId, isGranted: true }, + select: { customerId: true }, + }); + return auths.map((a) => a.customerId); +} + +/** + * Erstellt fehlende Vollmacht-Einträge für bestehende Vertreterbeziehungen + * (wird aufgerufen wenn man den Tab aufruft) + */ +export async function ensureAuthorizationEntries(customerId: number) { + // Alle aktiven Vertreter für diesen Kunden + const representatives = await prisma.customerRepresentative.findMany({ + where: { customerId, isActive: true }, + select: { representativeId: true }, + }); + + for (const rep of representatives) { + // Erstelle Eintrag falls nicht vorhanden + await prisma.representativeAuthorization.upsert({ + where: { + customerId_representativeId: { customerId, representativeId: rep.representativeId }, + }, + update: {}, // Nichts ändern wenn schon vorhanden + create: { + customerId, + representativeId: rep.representativeId, + isGranted: false, + }, + }); + } +} diff --git a/backend/src/services/consent-public.service.ts b/backend/src/services/consent-public.service.ts new file mode 100644 index 00000000..a462dfbe --- /dev/null +++ b/backend/src/services/consent-public.service.ts @@ -0,0 +1,187 @@ +import { ConsentType, ConsentStatus } from '@prisma/client'; +import crypto from 'crypto'; +import prisma from '../lib/prisma.js'; +import * as consentService from './consent.service.js'; +import * as appSettingService from './appSetting.service.js'; +import PDFDocument from 'pdfkit'; + +/** + * Kunden-Lookup per consentHash + */ +export async function getCustomerByConsentHash(hash: string) { + const customer = await prisma.customer.findUnique({ + where: { consentHash: hash }, + select: { + id: true, + firstName: true, + lastName: true, + customerNumber: true, + salutation: true, + email: true, + }, + }); + + if (!customer) return null; + + const consents = await consentService.getCustomerConsents(customer.id); + + return { customer, consents }; +} + +/** + * Alle 4 Einwilligungen über den öffentlichen Link erteilen + */ +export async function grantAllConsentsPublic(hash: string, ipAddress: string) { + const customer = await prisma.customer.findUnique({ + where: { consentHash: hash }, + select: { id: true, firstName: true, lastName: true }, + }); + + if (!customer) { + throw new Error('Ungültiger Link'); + } + + const results = []; + for (const type of Object.values(ConsentType)) { + const result = await consentService.updateConsent(customer.id, type, { + status: ConsentStatus.GRANTED, + source: 'public-link', + ipAddress, + createdBy: `${customer.firstName} ${customer.lastName} (Public-Link)`, + }); + results.push(result); + } + + return results; +} + +/** + * consentHash generieren falls nicht vorhanden + */ +export async function ensureConsentHash(customerId: number): Promise { + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + select: { consentHash: true }, + }); + + if (!customer) { + throw new Error('Kunde nicht gefunden'); + } + + if (customer.consentHash) { + return customer.consentHash; + } + + const hash = crypto.randomUUID(); + await prisma.customer.update({ + where: { id: customerId }, + data: { consentHash: hash }, + }); + + return hash; +} + +/** + * Platzhalter in Text ersetzen + */ +function replacePlaceholders(html: string, customer: { + firstName: string; + lastName: string; + customerNumber: string; + salutation?: string | null; + email?: string | null; +}): string { + return html + .replace(/\{\{vorname\}\}/gi, customer.firstName || '') + .replace(/\{\{nachname\}\}/gi, customer.lastName || '') + .replace(/\{\{kundennummer\}\}/gi, customer.customerNumber || '') + .replace(/\{\{anrede\}\}/gi, customer.salutation || '') + .replace(/\{\{email\}\}/gi, customer.email || '') + .replace(/\{\{datum\}\}/gi, new Date().toLocaleDateString('de-DE', { + day: '2-digit', + month: '2-digit', + year: 'numeric', + })); +} + +/** + * Datenschutzerklärung als HTML abrufen (mit Platzhaltern ersetzt) + */ +export async function getPrivacyPolicyHtml(customerId?: number): Promise { + const html = await appSettingService.getSetting('privacyPolicyHtml'); + + if (!html) { + return '

Keine Datenschutzerklärung hinterlegt.

'; + } + + if (!customerId) return html; + + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + select: { + firstName: true, + lastName: true, + customerNumber: true, + salutation: true, + email: true, + }, + }); + + if (!customer) return html; + + return replacePlaceholders(html, customer); +} + +/** + * HTML zu Plain-Text konvertieren (für PDF) + */ +function htmlToText(html: string): string { + return html + .replace(/]*>(.*?)<\/h[1-6]>/gi, '\n$1\n') + .replace(//gi, '\n') + .replace(/<\/p>/gi, '\n\n') + .replace(/]*>(.*?)<\/li>/gi, ' • $1\n') + .replace(/<[^>]+>/g, '') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/ /g, ' ') + .replace(/\n{3,}/g, '\n\n') + .trim(); +} + +/** + * Datenschutzerklärung als PDF generieren + */ +export async function generateConsentPdf(customerId: number): Promise { + const html = await getPrivacyPolicyHtml(customerId); + const text = htmlToText(html); + + return new Promise((resolve, reject) => { + const doc = new PDFDocument({ size: 'A4', margin: 50 }); + const chunks: Buffer[] = []; + + doc.on('data', (chunk: Buffer) => chunks.push(chunk)); + doc.on('end', () => resolve(Buffer.concat(chunks))); + doc.on('error', reject); + + // Titel + doc.fontSize(18).font('Helvetica-Bold').text('Datenschutzerklärung', { align: 'center' }); + doc.moveDown(1); + + // Datum + doc.fontSize(10).font('Helvetica') + .text(`Erstellt am: ${new Date().toLocaleDateString('de-DE')}`, { align: 'right' }); + doc.moveDown(1); + + // Inhalt + doc.fontSize(11).font('Helvetica').text(text, { + align: 'left', + lineGap: 4, + }); + + doc.end(); + }); +} diff --git a/backend/src/services/consent.service.ts b/backend/src/services/consent.service.ts new file mode 100644 index 00000000..739a0a54 --- /dev/null +++ b/backend/src/services/consent.service.ts @@ -0,0 +1,267 @@ +import { ConsentType, ConsentStatus } from '@prisma/client'; +import prisma from '../lib/prisma.js'; +import fs from 'fs'; +import path from 'path'; + +export interface UpdateConsentData { + status: ConsentStatus; + source?: string; + documentPath?: string; + version?: string; + ipAddress?: string; + createdBy: string; +} + +/** + * Holt alle Einwilligungen eines Kunden + */ +export async function getCustomerConsents(customerId: number) { + const consents = await prisma.customerConsent.findMany({ + where: { customerId }, + orderBy: { consentType: 'asc' }, + }); + + // Alle verfügbaren Consent-Typen mit Status + const allTypes = Object.values(ConsentType); + const consentMap = new Map(consents.map((c) => [c.consentType, c])); + + return allTypes.map((type) => { + const existing = consentMap.get(type); + return existing || { + id: null, + customerId, + consentType: type, + status: 'PENDING' as ConsentStatus, + grantedAt: null, + withdrawnAt: null, + source: null, + documentPath: null, + version: null, + ipAddress: null, + createdBy: null, + createdAt: null, + updatedAt: null, + }; + }); +} + +/** + * Aktualisiert oder erstellt eine Einwilligung + */ +export async function updateConsent( + customerId: number, + consentType: ConsentType, + data: UpdateConsentData +) { + // Prüfen ob Kunde existiert + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + }); + + if (!customer) { + throw new Error('Kunde nicht gefunden'); + } + + const now = new Date(); + const updateData = { + status: data.status, + source: data.source, + documentPath: data.documentPath, + version: data.version, + ipAddress: data.ipAddress, + grantedAt: data.status === 'GRANTED' ? now : undefined, + withdrawnAt: data.status === 'WITHDRAWN' ? now : undefined, + }; + + const result = await prisma.customerConsent.upsert({ + where: { + customerId_consentType: { customerId, consentType }, + }, + update: updateData, + create: { + customerId, + consentType, + ...updateData, + createdBy: data.createdBy, + }, + }); + + // Bei Widerruf: Datenschutz-PDF löschen wenn keine Einwilligung mehr besteht + if (data.status === 'WITHDRAWN') { + await deletePrivacyPdfOnWithdraw(customerId); + } + + return result; +} + +/** + * Holt die Historie einer Einwilligung (aus Audit-Logs) + */ +export async function getConsentHistory(customerId: number, consentType: ConsentType) { + // Aus Audit-Logs die Änderungen dieser Einwilligung abrufen + const logs = await prisma.auditLog.findMany({ + where: { + resourceType: 'CustomerConsent', + dataSubjectId: customerId, + changesAfter: { contains: consentType }, + }, + orderBy: { createdAt: 'desc' }, + take: 50, + }); + + return logs; +} + +/** + * Prüft ob eine bestimmte Einwilligung erteilt wurde + */ +export async function hasConsent(customerId: number, consentType: ConsentType): Promise { + const consent = await prisma.customerConsent.findUnique({ + where: { + customerId_consentType: { customerId, consentType }, + }, + }); + + return consent?.status === 'GRANTED'; +} + +/** + * Prüft ob ein Kunde die DSGVO-Einwilligung erfüllt hat. + * Erfüllt = entweder privacyPolicyPath vorhanden ODER alle Online-Consents GRANTED. + */ +export async function hasFullConsent(customerId: number): Promise<{ + hasConsent: boolean; + hasPaperConsent: boolean; + hasOnlineConsent: boolean; + consentDetails: { type: string; status: string }[]; + consentHash: string | null; +}> { + // Prüfe ob Papier-Datenschutzerklärung vorhanden + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + select: { privacyPolicyPath: true, consentHash: true }, + }); + + const hasPaperConsent = !!customer?.privacyPolicyPath; + + // Online-Consents prüfen + const allTypes = Object.values(ConsentType); + const consents = await prisma.customerConsent.findMany({ + where: { customerId }, + }); + + const consentMap = new Map(consents.map((c) => [c.consentType, c.status])); + const consentDetails = allTypes.map((type) => ({ + type, + status: (consentMap.get(type) || 'PENDING') as string, + })); + + const hasOnlineConsent = allTypes.every( + (type) => consentMap.get(type) === 'GRANTED' + ); + + return { + hasConsent: hasPaperConsent || hasOnlineConsent, + hasPaperConsent, + hasOnlineConsent, + consentDetails, + consentHash: customer?.consentHash || null, + }; +} + +/** + * Widerruft alle Einwilligungen eines Kunden + */ +export async function withdrawAllConsents(customerId: number, withdrawnBy: string) { + const result = await prisma.customerConsent.updateMany({ + where: { + customerId, + status: 'GRANTED', + }, + data: { + status: 'WITHDRAWN', + withdrawnAt: new Date(), + }, + }); + + // Datenschutz-PDF löschen + await deletePrivacyPdfOnWithdraw(customerId); + + return result; +} + +/** + * Löscht die Datenschutz-PDF bei Widerruf. + * Sobald auch nur eine Einwilligung widerrufen wird, ist die Gesamteinwilligung ungültig. + */ +async function deletePrivacyPdfOnWithdraw(customerId: number) { + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + select: { privacyPolicyPath: true }, + }); + + if (customer?.privacyPolicyPath) { + try { + const filePath = path.join(process.cwd(), customer.privacyPolicyPath); + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + } + } catch (err) { + console.error('Fehler beim Löschen der Datenschutz-PDF:', err); + } + + await prisma.customer.update({ + where: { id: customerId }, + data: { privacyPolicyPath: null }, + }); + + console.log(`Datenschutz-PDF für Kunde ${customerId} gelöscht (Einwilligung widerrufen)`); + } +} + +/** + * Consent-Übersicht für DSGVO-Dashboard + */ +export async function getConsentOverview() { + const allConsents = await prisma.customerConsent.groupBy({ + by: ['consentType', 'status'], + _count: { id: true }, + }); + + // Gruppieren nach Typ + const overview: Record = {}; + + for (const type of Object.values(ConsentType)) { + overview[type] = { granted: 0, withdrawn: 0, pending: 0 }; + } + + for (const row of allConsents) { + const type = row.consentType; + const status = row.status.toLowerCase() as 'granted' | 'withdrawn' | 'pending'; + overview[type][status] = row._count.id; + } + + return overview; +} + +/** + * Consent-Typ Labels für UI + */ +export const CONSENT_TYPE_LABELS: Record = { + DATA_PROCESSING: { + label: 'Datenverarbeitung', + description: 'Grundlegende Verarbeitung personenbezogener Daten zur Vertragserfüllung', + }, + MARKETING_EMAIL: { + label: 'E-Mail-Marketing', + description: 'Zusendung von Werbung und Angeboten per E-Mail', + }, + MARKETING_PHONE: { + label: 'Telefonmarketing', + description: 'Kontaktaufnahme zu Werbezwecken per Telefon', + }, + DATA_SHARING_PARTNER: { + label: 'Datenweitergabe', + description: 'Weitergabe von Daten an Partnerunternehmen', + }, +}; diff --git a/backend/src/services/contractCockpit.service.ts b/backend/src/services/contractCockpit.service.ts index b57e0cbd..7a4a4c8a 100644 --- a/backend/src/services/contractCockpit.service.ts +++ b/backend/src/services/contractCockpit.service.ts @@ -53,11 +53,54 @@ export interface CockpitSummary { openTasks: number; pendingContracts: number; reviewDue: number; // Erneute Prüfung fällig (Snooze abgelaufen) + missingConsents: number; // Fehlende oder widerrufene Einwilligungen + }; +} + +export interface DocumentAlert { + id: number; + type: string; // ID_CARD, PASSPORT, DRIVERS_LICENSE, OTHER + documentNumber: string; + expiryDate: string; + daysUntilExpiry: number; + urgency: UrgencyLevel; + customer: { + id: number; + customerNumber: string; + name: string; + }; +} + +export interface ReportedMeterReading { + id: number; + readingDate: string; + value: number; + unit: string; + notes?: string; + reportedBy?: string; + createdAt: string; + meter: { + id: number; + meterNumber: string; + type: string; + }; + customer: { + id: number; + customerNumber: string; + name: string; + }; + // Anbieter-Info für Quick-Login + providerPortal?: { + providerName: string; + portalUrl: string; + portalUsername?: string; }; } export interface CockpitResult { contracts: CockpitContract[]; + documentAlerts: DocumentAlert[]; + reportedReadings: ReportedMeterReading[]; summary: CockpitSummary; thresholds: { criticalDays: number; @@ -143,6 +186,8 @@ export async function getCockpitData(): Promise { const criticalDays = parseInt(settings.deadlineCriticalDays) || 14; const warningDays = parseInt(settings.deadlineWarningDays) || 42; const okDays = parseInt(settings.deadlineOkDays) || 90; + const docExpiryCriticalDays = parseInt(settings.documentExpiryCriticalDays) || 30; + const docExpiryWarningDays = parseInt(settings.documentExpiryWarningDays) || 90; // Lade alle relevanten Verträge (inkl. CANCELLED/DEACTIVATED für Schlussrechnung-Check) const contracts = await prisma.contract.findMany({ @@ -231,9 +276,41 @@ export async function getCockpitData(): Promise { openTasks: 0, pendingContracts: 0, reviewDue: 0, + missingConsents: 0, }, }; + // Consent-Daten batch-laden für alle Kunden + const allConsents = await prisma.customerConsent.findMany({ + where: { status: 'GRANTED' }, + select: { customerId: true, consentType: true }, + }); + + // Map: customerId → Set + const grantedConsentsMap = new Map>(); + for (const c of allConsents) { + if (!grantedConsentsMap.has(c.customerId)) { + grantedConsentsMap.set(c.customerId, new Set()); + } + grantedConsentsMap.get(c.customerId)!.add(c.consentType); + } + + // Widerrufene Consents laden + const withdrawnConsents = await prisma.customerConsent.findMany({ + where: { status: 'WITHDRAWN' }, + select: { customerId: true, consentType: true }, + }); + const withdrawnConsentsMap = new Map>(); + for (const c of withdrawnConsents) { + if (!withdrawnConsentsMap.has(c.customerId)) { + withdrawnConsentsMap.set(c.customerId, new Set()); + } + withdrawnConsentsMap.get(c.customerId)!.add(c.consentType); + } + + // Track welche Kunden bereits eine Consent-Warnung bekommen haben (nur einmal pro Kunde) + const customerConsentWarned = new Set(); + for (const contract of contracts) { const issues: CockpitIssue[] = []; @@ -407,17 +484,43 @@ export async function getCockpitData(): Promise { summary.byCategory.missingData++; } - // 7b. KEIN AUSWEIS (für DSL, FIBER, CABLE, MOBILE ist dies ein kritisches Problem) - if (!contract.identityDocumentId) { + // 7b. KEIN AUSWEIS (nur für Telekommunikationsprodukte relevant) + const requiresIdentityDocument = ['DSL', 'FIBER', 'CABLE', 'MOBILE'].includes(contract.type); + if (requiresIdentityDocument && !contract.identityDocumentId) { issues.push({ type: 'missing_identity_document', label: 'Ausweis fehlt', - urgency: requiresBankAndId ? 'critical' : 'warning', + urgency: 'critical', details: 'Kein Ausweisdokument verknüpft', }); summary.byCategory.missingData++; } + // 7c. AUSWEIS LÄUFT AB (nur aktive Ausweise prüfen) + if (contract.identityDocument && contract.identityDocument.isActive && contract.identityDocument.expiryDate) { + const expiryDate = new Date(contract.identityDocument.expiryDate); + const today = new Date(); + const daysUntilExpiry = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); + + if (daysUntilExpiry < 0) { + issues.push({ + type: 'identity_document_expired', + label: 'Ausweis abgelaufen', + urgency: 'critical', + details: `Ausweis seit ${Math.abs(daysUntilExpiry)} Tagen abgelaufen (${expiryDate.toLocaleDateString('de-DE')})`, + }); + summary.byCategory.missingData++; + } else if (daysUntilExpiry <= docExpiryWarningDays) { + issues.push({ + type: 'identity_document_expiring', + label: 'Ausweis läuft ab', + urgency: daysUntilExpiry <= docExpiryCriticalDays ? 'critical' : 'warning', + details: `Ausweis läuft in ${daysUntilExpiry} Tagen ab (${expiryDate.toLocaleDateString('de-DE')})`, + }); + summary.byCategory.cancellationDeadlines++; + } + } + // 8. ENERGIE-SPEZIFISCH: KEIN ZÄHLER if (['ELECTRICITY', 'GAS'].includes(contract.type) && contract.energyDetails) { if (!contract.energyDetails.meterId) { @@ -546,6 +649,36 @@ export async function getCockpitData(): Promise { } } + // #14 - Consent-Prüfung (nur für aktive Verträge, einmal pro Kunde) + if (['ACTIVE', 'PENDING', 'DRAFT'].includes(contract.status) && !customerConsentWarned.has(contract.customer.id)) { + const granted = grantedConsentsMap.get(contract.customer.id); + const withdrawn = withdrawnConsentsMap.get(contract.customer.id); + const requiredTypes = ['DATA_PROCESSING', 'MARKETING_EMAIL', 'MARKETING_PHONE', 'DATA_SHARING_PARTNER']; + + if (withdrawn && withdrawn.size > 0) { + // Mindestens eine Einwilligung widerrufen + issues.push({ + type: 'consent_withdrawn', + label: 'Einwilligung widerrufen', + urgency: 'critical', + details: `${withdrawn.size} Einwilligung(en) widerrufen`, + }); + summary.byCategory.missingConsents++; + customerConsentWarned.add(contract.customer.id); + } else if (!granted || granted.size < requiredTypes.length) { + // Nicht alle 4 Einwilligungen erteilt + const missing = requiredTypes.length - (granted?.size || 0); + issues.push({ + type: 'missing_consents', + label: 'Fehlende Einwilligungen', + urgency: 'critical', + details: `${missing} von ${requiredTypes.length} Einwilligungen fehlen`, + }); + summary.byCategory.missingConsents++; + customerConsentWarned.add(contract.customer.id); + } + } + // Nur Verträge mit Issues hinzufügen if (issues.length > 0) { const highestUrgency = getHighestUrgency(issues); @@ -596,8 +729,16 @@ export async function getCockpitData(): Promise { return urgencyOrder[a.highestUrgency] - urgencyOrder[b.highestUrgency]; }); + // Vertragsunabhängige Ausweis-Warnungen + const documentAlerts = await getDocumentExpiryAlerts(docExpiryCriticalDays, docExpiryWarningDays); + + // Gemeldete Zählerstände (REPORTED Status) + const reportedReadings = await getReportedMeterReadings(); + return { contracts: cockpitContracts, + documentAlerts, + reportedReadings, summary, thresholds: { criticalDays, @@ -606,3 +747,111 @@ export async function getCockpitData(): Promise { }, }; } + +/** + * Alle aktiven Ausweise die ablaufen oder abgelaufen sind (vertragsunabhängig) + */ +async function getDocumentExpiryAlerts(criticalDays: number, warningDays: number): Promise { + const now = new Date(); + const inWarningDays = new Date(now.getTime() + warningDays * 24 * 60 * 60 * 1000); + + const documents = await prisma.identityDocument.findMany({ + where: { + isActive: true, + expiryDate: { lte: inWarningDays }, + }, + include: { + customer: { + select: { id: true, customerNumber: true, firstName: true, lastName: true }, + }, + }, + orderBy: { expiryDate: 'asc' }, + }); + + return documents.map((doc) => { + const expiryDate = new Date(doc.expiryDate!); + const daysUntilExpiry = Math.ceil((expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)); + + let urgency: UrgencyLevel = 'warning'; + if (daysUntilExpiry < 0) urgency = 'critical'; + else if (daysUntilExpiry <= criticalDays) urgency = 'critical'; + + return { + id: doc.id, + type: doc.type, + documentNumber: doc.documentNumber, + expiryDate: expiryDate.toISOString(), + daysUntilExpiry, + urgency, + customer: { + id: doc.customer.id, + customerNumber: doc.customer.customerNumber, + name: `${doc.customer.firstName} ${doc.customer.lastName}`, + }, + }; + }); +} + +/** + * Vom Kunden gemeldete Zählerstände die noch nicht übertragen wurden + */ +async function getReportedMeterReadings(): Promise { + const readings = await prisma.meterReading.findMany({ + where: { status: 'REPORTED' }, + include: { + meter: { + include: { + customer: { + select: { id: true, customerNumber: true, firstName: true, lastName: true }, + }, + // Energie-Verträge für diesen Zähler (um Provider-Portal-Daten zu bekommen) + energyDetails: { + include: { + contract: { + select: { + id: true, + portalUsername: true, + provider: { + select: { id: true, name: true, portalUrl: true }, + }, + }, + }, + }, + take: 1, + }, + }, + }, + }, + orderBy: { createdAt: 'asc' }, + }); + + return readings.map((r) => { + const contract = r.meter.energyDetails?.[0]?.contract; + const provider = contract?.provider; + + return { + id: r.id, + readingDate: r.readingDate.toISOString(), + value: r.value, + unit: r.unit, + notes: r.notes ?? undefined, + reportedBy: r.reportedBy ?? undefined, + createdAt: r.createdAt.toISOString(), + meter: { + id: r.meter.id, + meterNumber: r.meter.meterNumber, + type: r.meter.type, + }, + customer: { + id: r.meter.customer.id, + customerNumber: r.meter.customer.customerNumber, + name: `${r.meter.customer.firstName} ${r.meter.customer.lastName}`, + }, + providerPortal: provider?.portalUrl ? { + providerName: provider.name, + portalUrl: provider.portalUrl, + portalUsername: contract?.portalUsername ?? undefined, + } : undefined, + }; + }); +} diff --git a/backend/src/services/emailLog.service.ts b/backend/src/services/emailLog.service.ts new file mode 100644 index 00000000..e9142786 --- /dev/null +++ b/backend/src/services/emailLog.service.ts @@ -0,0 +1,90 @@ +import prisma from '../lib/prisma.js'; + +export interface CreateEmailLogData { + fromAddress: string; + toAddress: string; + subject: string; + context: string; + customerId?: number; + triggeredBy?: string; + smtpServer: string; + smtpPort: number; + smtpEncryption: string; + smtpUser: string; + success: boolean; + messageId?: string; + errorMessage?: string; + smtpResponse?: string; +} + +export async function createEmailLog(data: CreateEmailLogData) { + return prisma.emailLog.create({ data }); +} + +export async function getEmailLogs(options?: { + page?: number; + limit?: number; + success?: boolean; + search?: string; + context?: string; +}) { + const page = options?.page || 1; + const limit = options?.limit || 50; + const skip = (page - 1) * limit; + + const where: Record = {}; + + if (options?.success !== undefined) { + where.success = options.success; + } + + if (options?.context) { + where.context = options.context; + } + + if (options?.search) { + where.OR = [ + { fromAddress: { contains: options.search } }, + { toAddress: { contains: options.search } }, + { subject: { contains: options.search } }, + { errorMessage: { contains: options.search } }, + ]; + } + + const [logs, total] = await Promise.all([ + prisma.emailLog.findMany({ + where, + orderBy: { sentAt: 'desc' }, + skip, + take: limit, + }), + prisma.emailLog.count({ where }), + ]); + + return { + data: logs, + pagination: { + page, + limit, + total, + totalPages: Math.ceil(total / limit), + }, + }; +} + +export async function getEmailLogById(id: number) { + return prisma.emailLog.findUnique({ where: { id } }); +} + +export async function getEmailLogStats() { + const [total, success, failed, last24h] = await Promise.all([ + prisma.emailLog.count(), + prisma.emailLog.count({ where: { success: true } }), + prisma.emailLog.count({ where: { success: false } }), + prisma.emailLog.count({ + where: { sentAt: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }, + }), + ]); + + return { total, success, failed, last24h }; +} diff --git a/backend/src/services/emailProvider/emailProviderService.ts b/backend/src/services/emailProvider/emailProviderService.ts index 0646c8cd..51949802 100644 --- a/backend/src/services/emailProvider/emailProviderService.ts +++ b/backend/src/services/emailProvider/emailProviderService.ts @@ -73,6 +73,9 @@ export interface CreateProviderConfigData { imapEncryption?: MailEncryption; smtpEncryption?: MailEncryption; allowSelfSignedCerts?: boolean; + // System-E-Mail + systemEmailAddress?: string; + systemEmailPassword?: string; isActive?: boolean; isDefault?: boolean; } @@ -86,9 +89,10 @@ export async function createProviderConfig(data: CreateProviderConfigData) { }); } - // Passwort verschlüsseln falls vorhanden + // Passwörter verschlüsseln falls vorhanden const { encrypt } = await import('../../utils/encryption.js'); const passwordEncrypted = data.password ? encrypt(data.password) : null; + const systemEmailPasswordEncrypted = data.systemEmailPassword ? encrypt(data.systemEmailPassword) : null; return prisma.emailProviderConfig.create({ data: { @@ -103,6 +107,8 @@ export async function createProviderConfig(data: CreateProviderConfigData) { imapEncryption: data.imapEncryption ?? 'SSL', smtpEncryption: data.smtpEncryption ?? 'SSL', allowSelfSignedCerts: data.allowSelfSignedCerts ?? false, + systemEmailAddress: data.systemEmailAddress || null, + systemEmailPasswordEncrypted, isActive: data.isActive ?? true, isDefault: data.isDefault ?? false, }, @@ -134,20 +140,30 @@ export async function updateProviderConfig( if (data.imapEncryption !== undefined) updateData.imapEncryption = data.imapEncryption; if (data.smtpEncryption !== undefined) updateData.smtpEncryption = data.smtpEncryption; if (data.allowSelfSignedCerts !== undefined) updateData.allowSelfSignedCerts = data.allowSelfSignedCerts; + if (data.systemEmailAddress !== undefined) updateData.systemEmailAddress = data.systemEmailAddress || null; if (data.isActive !== undefined) updateData.isActive = data.isActive; if (data.isDefault !== undefined) updateData.isDefault = data.isDefault; + const { encrypt } = await import('../../utils/encryption.js'); + // Passwort-Logik: // - Wenn neues Passwort übergeben → verschlüsseln und speichern // - Wenn Benutzername gelöscht wird → Passwort auch löschen (gehören zusammen) if (data.password) { - const { encrypt } = await import('../../utils/encryption.js'); updateData.passwordEncrypted = encrypt(data.password); } else if (data.username !== undefined && !data.username) { // Benutzername wird gelöscht → Passwort auch löschen updateData.passwordEncrypted = null; } + // System-E-Mail-Passwort + if (data.systemEmailPassword) { + updateData.systemEmailPasswordEncrypted = encrypt(data.systemEmailPassword); + } else if (data.systemEmailAddress !== undefined && !data.systemEmailAddress) { + // System-E-Mail wird gelöscht → Passwort auch löschen + updateData.systemEmailPasswordEncrypted = null; + } + return prisma.emailProviderConfig.update({ where: { id }, data: updateData, @@ -564,3 +580,45 @@ export async function testProviderConnection(options?: { }; } } + +// ==================== SYSTEM EMAIL ==================== + +export interface SystemEmailCredentials { + emailAddress: string; + password: string; + smtpServer: string; + smtpPort: number; + smtpEncryption: MailEncryption; + allowSelfSignedCerts: boolean; +} + +/** + * System-E-Mail-Credentials vom aktiven Provider holen. + * Wird für automatisierten Versand (DSGVO, Benachrichtigungen etc.) verwendet. + */ +export async function getSystemEmailCredentials(): Promise { + const config = await getActiveProviderConfig(); + if (!config?.systemEmailAddress || !config?.systemEmailPasswordEncrypted) { + return null; + } + + let password: string; + try { + password = decrypt(config.systemEmailPasswordEncrypted); + } catch { + console.error('System-E-Mail-Passwort konnte nicht entschlüsselt werden'); + return null; + } + + const settings = await getImapSmtpSettings(); + if (!settings) return null; + + return { + emailAddress: config.systemEmailAddress, + password, + smtpServer: settings.smtpServer, + smtpPort: settings.smtpPort, + smtpEncryption: settings.smtpEncryption, + allowSelfSignedCerts: settings.allowSelfSignedCerts, + }; +} diff --git a/backend/src/services/gdpr.service.ts b/backend/src/services/gdpr.service.ts new file mode 100644 index 00000000..79a5796d --- /dev/null +++ b/backend/src/services/gdpr.service.ts @@ -0,0 +1,565 @@ +import { DeletionRequestStatus } from '@prisma/client'; +import prisma from '../lib/prisma.js'; +import { getAuditLogsByDataSubject } from './audit.service.js'; +import { getCustomerConsents, withdrawAllConsents } from './consent.service.js'; +import PDFDocument from 'pdfkit'; +import fs from 'fs'; +import path from 'path'; + +export interface CreateDeletionRequestData { + customerId: number; + requestSource: string; + requestedBy: string; +} + +export interface ProcessDeletionRequestData { + processedBy: string; + action: 'complete' | 'partial' | 'reject'; + retentionReason?: string; +} + +/** + * Exportiert alle Daten eines Kunden (DSGVO Art. 15) + */ +export async function exportCustomerData(customerId: number) { + const customer = await prisma.customer.findUnique({ + where: { id: customerId }, + include: { + addresses: true, + bankCards: { + select: { + id: true, + accountHolder: true, + iban: true, + bic: true, + bankName: true, + isActive: true, + createdAt: true, + }, + }, + identityDocuments: { + select: { + id: true, + type: true, + documentNumber: true, + issuingAuthority: true, + issueDate: true, + expiryDate: true, + isActive: true, + createdAt: true, + }, + }, + meters: { + include: { + readings: true, + }, + }, + contracts: { + include: { + address: true, + billingAddress: true, + provider: true, + tariff: true, + energyDetails: { + include: { invoices: true }, + }, + internetDetails: { + include: { phoneNumbers: true }, + }, + mobileDetails: { + include: { simCards: true }, + }, + tvDetails: true, + carInsuranceDetails: true, + historyEntries: true, + tasks: { + include: { subtasks: true }, + }, + }, + }, + stressfreiEmails: { + select: { + id: true, + email: true, + platform: true, + isActive: true, + createdAt: true, + }, + }, + consents: true, + }, + }); + + if (!customer) { + throw new Error('Kunde nicht gefunden'); + } + + // Audit-Logs für diesen Kunden + const accessLogs = await getAuditLogsByDataSubject(customerId); + + // Sensible Felder entfernen + const exportData = { + exportDate: new Date().toISOString(), + dataSubject: { + id: customer.id, + customerNumber: customer.customerNumber, + name: `${customer.firstName} ${customer.lastName}`, + }, + personalData: { + salutation: customer.salutation, + firstName: customer.firstName, + lastName: customer.lastName, + companyName: customer.companyName, + type: customer.type, + birthDate: customer.birthDate, + birthPlace: customer.birthPlace, + email: customer.email, + phone: customer.phone, + mobile: customer.mobile, + taxNumber: customer.taxNumber, + portalEnabled: customer.portalEnabled, + portalEmail: customer.portalEmail, + portalLastLogin: customer.portalLastLogin, + createdAt: customer.createdAt, + updatedAt: customer.updatedAt, + }, + addresses: customer.addresses, + bankCards: customer.bankCards, + identityDocuments: customer.identityDocuments, + meters: customer.meters, + contracts: customer.contracts.map((c) => ({ + ...c, + // Sensible Daten entfernen + portalPasswordEncrypted: undefined, + })), + emails: customer.stressfreiEmails, + consents: customer.consents, + accessHistory: accessLogs.map((log) => ({ + timestamp: log.createdAt, + action: log.action, + user: log.userEmail, + resource: log.resourceType, + ipAddress: log.ipAddress, + })), + }; + + return exportData; +} + +/** + * Erstellt eine Löschanfrage + */ +export async function createDeletionRequest(data: CreateDeletionRequestData) { + // Prüfen ob Kunde existiert + const customer = await prisma.customer.findUnique({ + where: { id: data.customerId }, + }); + + if (!customer) { + throw new Error('Kunde nicht gefunden'); + } + + // Prüfen ob bereits eine offene Anfrage existiert + const existingRequest = await prisma.dataDeletionRequest.findFirst({ + where: { + customerId: data.customerId, + status: { in: ['PENDING', 'IN_PROGRESS'] }, + }, + }); + + if (existingRequest) { + throw new Error('Es existiert bereits eine offene Löschanfrage für diesen Kunden'); + } + + return prisma.dataDeletionRequest.create({ + data: { + customerId: data.customerId, + requestSource: data.requestSource, + requestedBy: data.requestedBy, + status: 'PENDING', + }, + }); +} + +/** + * Holt alle Löschanfragen mit Paginierung + */ +export async function getDeletionRequests(params: { + status?: DeletionRequestStatus; + page?: number; + limit?: number; +}) { + const { status, page = 1, limit = 20 } = params; + + const where = status ? { status } : {}; + + const [requests, total] = await Promise.all([ + prisma.dataDeletionRequest.findMany({ + where, + orderBy: { requestedAt: 'desc' }, + skip: (page - 1) * limit, + take: limit, + }), + prisma.dataDeletionRequest.count({ where }), + ]); + + // Kundendaten hinzufügen + const customerIds = requests.map((r) => r.customerId); + const customers = await prisma.customer.findMany({ + where: { id: { in: customerIds } }, + select: { + id: true, + customerNumber: true, + firstName: true, + lastName: true, + }, + }); + + const customerMap = new Map(customers.map((c) => [c.id, c])); + + const requestsWithCustomer = requests.map((r) => ({ + ...r, + customer: customerMap.get(r.customerId) || null, + })); + + return { + data: requestsWithCustomer, + pagination: { + page, + limit, + total, + totalPages: Math.ceil(total / limit), + }, + }; +} + +/** + * Holt eine einzelne Löschanfrage + */ +export async function getDeletionRequest(id: number) { + const request = await prisma.dataDeletionRequest.findUnique({ + where: { id }, + }); + + if (!request) return null; + + const customer = await prisma.customer.findUnique({ + where: { id: request.customerId }, + select: { + id: true, + customerNumber: true, + firstName: true, + lastName: true, + email: true, + }, + }); + + return { ...request, customer }; +} + +/** + * Bearbeitet eine Löschanfrage + */ +export async function processDeletionRequest( + requestId: number, + data: ProcessDeletionRequestData +) { + const request = await prisma.dataDeletionRequest.findUnique({ + where: { id: requestId }, + }); + + if (!request) { + throw new Error('Löschanfrage nicht gefunden'); + } + + if (request.status !== 'PENDING' && request.status !== 'IN_PROGRESS') { + throw new Error('Diese Anfrage wurde bereits bearbeitet'); + } + + // Status auf IN_PROGRESS setzen + await prisma.dataDeletionRequest.update({ + where: { id: requestId }, + data: { status: 'IN_PROGRESS' }, + }); + + const customerId = request.customerId; + const deletedData: Record = {}; + const retainedData: Record = {}; + + try { + if (data.action === 'reject') { + // Anfrage ablehnen + return prisma.dataDeletionRequest.update({ + where: { id: requestId }, + data: { + status: 'REJECTED', + processedAt: new Date(), + processedBy: data.processedBy, + retentionReason: data.retentionReason, + }, + }); + } + + // Einwilligungen widerrufen + await withdrawAllConsents(customerId, data.processedBy); + deletedData['consents'] = 1; + + // Verträge prüfen - aktive Verträge müssen behalten werden + const contracts = await prisma.contract.findMany({ + where: { customerId }, + }); + + const activeContracts = contracts.filter( + (c) => c.status === 'ACTIVE' || c.status === 'PENDING' + ); + + if (activeContracts.length > 0) { + retainedData['contracts'] = { + count: activeContracts.length, + reason: 'Aktive Verträge müssen für die Vertragserfüllung aufbewahrt werden', + }; + } + + // Löschbare Daten anonymisieren (statt hart löschen) + if (data.action === 'complete' && activeContracts.length === 0) { + // Kunde vollständig anonymisieren + await anonymizeCustomer(customerId); + deletedData['customer'] = 1; + deletedData['addresses'] = 1; + deletedData['bankCards'] = 1; + deletedData['identityDocuments'] = 1; + } else { + // Teilweise Löschung - nur optionale Daten + const deletedAddresses = await prisma.address.deleteMany({ + where: { customerId, isDefault: false }, + }); + deletedData['addresses'] = deletedAddresses.count; + + // Inaktive Bankkarten löschen + const deletedBankCards = await prisma.bankCard.deleteMany({ + where: { customerId, isActive: false }, + }); + deletedData['bankCards'] = deletedBankCards.count; + + // Inaktive Dokumente löschen + const deletedDocs = await prisma.identityDocument.deleteMany({ + where: { customerId, isActive: false }, + }); + deletedData['identityDocuments'] = deletedDocs.count; + } + + // Löschnachweis generieren + const proofPath = await generateDeletionProof(requestId, customerId, deletedData, retainedData); + + // Anfrage abschließen + const status = Object.keys(retainedData).length > 0 ? 'PARTIALLY_COMPLETED' : 'COMPLETED'; + + return prisma.dataDeletionRequest.update({ + where: { id: requestId }, + data: { + status, + processedAt: new Date(), + processedBy: data.processedBy, + deletedData: JSON.stringify(deletedData), + retainedData: JSON.stringify(retainedData), + retentionReason: data.retentionReason, + proofDocument: proofPath, + }, + }); + } catch (error) { + // Bei Fehler Status zurücksetzen + await prisma.dataDeletionRequest.update({ + where: { id: requestId }, + data: { status: 'PENDING' }, + }); + throw error; + } +} + +/** + * Anonymisiert Kundendaten (DSGVO-konform) + */ +async function anonymizeCustomer(customerId: number) { + const anonymized = `[GELÖSCHT-${Date.now()}]`; + + await prisma.customer.update({ + where: { id: customerId }, + data: { + firstName: anonymized, + lastName: anonymized, + salutation: null, + companyName: null, + birthDate: null, + birthPlace: null, + email: null, + phone: null, + mobile: null, + taxNumber: null, + notes: null, + portalEnabled: false, + portalEmail: null, + portalPasswordHash: null, + portalPasswordEncrypted: null, + }, + }); + + // Adressen anonymisieren + await prisma.address.updateMany({ + where: { customerId }, + data: { + street: anonymized, + houseNumber: '', + postalCode: '00000', + city: anonymized, + }, + }); + + // Bankkarten anonymisieren + await prisma.bankCard.updateMany({ + where: { customerId }, + data: { + accountHolder: anonymized, + iban: 'XX00000000000000000000', + bic: null, + bankName: null, + isActive: false, + }, + }); + + // Ausweisdokumente anonymisieren + await prisma.identityDocument.updateMany({ + where: { customerId }, + data: { + documentNumber: anonymized, + issuingAuthority: null, + isActive: false, + }, + }); +} + +/** + * Generiert ein Löschnachweis-PDF + */ +async function generateDeletionProof( + requestId: number, + customerId: number, + deletedData: Record, + retainedData: Record +): Promise { + const uploadsDir = path.join(process.cwd(), 'uploads', 'gdpr'); + + // Verzeichnis erstellen falls nicht vorhanden + if (!fs.existsSync(uploadsDir)) { + fs.mkdirSync(uploadsDir, { recursive: true }); + } + + const filename = `loeschnachweis_${requestId}_${Date.now()}.pdf`; + const filepath = path.join(uploadsDir, filename); + + const doc = new PDFDocument({ size: 'A4', margin: 50 }); + const writeStream = fs.createWriteStream(filepath); + doc.pipe(writeStream); + + // Titel + doc.fontSize(18).text('Datenlöschungsnachweis', { align: 'center' }); + doc.moveDown(); + + // Metadaten + doc.fontSize(12); + doc.text(`Anfrage-ID: ${requestId}`); + doc.text(`Kunden-ID: ${customerId}`); + doc.text(`Datum: ${new Date().toLocaleDateString('de-DE')}`); + doc.text(`Uhrzeit: ${new Date().toLocaleTimeString('de-DE')}`); + doc.moveDown(); + + // Gelöschte Daten + doc.fontSize(14).text('Gelöschte Daten:', { underline: true }); + doc.fontSize(12); + for (const [category, count] of Object.entries(deletedData)) { + doc.text(`• ${category}: ${count} Einträge`); + } + doc.moveDown(); + + // Aufbewahrte Daten + if (Object.keys(retainedData).length > 0) { + doc.fontSize(14).text('Aufbewahrte Daten:', { underline: true }); + doc.fontSize(12); + for (const [category, info] of Object.entries(retainedData)) { + doc.text(`• ${category}: ${info.count} Einträge`); + doc.fontSize(10).text(` Grund: ${info.reason}`, { indent: 20 }); + doc.fontSize(12); + } + doc.moveDown(); + } + + // Rechtlicher Hinweis + doc.moveDown(); + doc.fontSize(10).text( + 'Dieses Dokument bestätigt die Durchführung der Datenlöschung gemäß Art. 17 DSGVO. ' + + 'Daten, die aus gesetzlichen Gründen aufbewahrt werden müssen, wurden nicht gelöscht.', + { align: 'justify' } + ); + + doc.end(); + + // Warten bis Datei geschrieben wurde + await new Promise((resolve) => writeStream.on('finish', resolve)); + + return `gdpr/${filename}`; +} + +/** + * Dashboard-Statistiken für DSGVO + */ +export async function getGDPRDashboardStats() { + const [ + pendingDeletions, + completedDeletions, + recentExports, + consentStats, + ] = await Promise.all([ + // Offene Löschanfragen + prisma.dataDeletionRequest.count({ + where: { status: { in: ['PENDING', 'IN_PROGRESS'] } }, + }), + // Abgeschlossene Löschungen (letzte 30 Tage) + prisma.dataDeletionRequest.count({ + where: { + status: { in: ['COMPLETED', 'PARTIALLY_COMPLETED'] }, + processedAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) }, + }, + }), + // Letzte Datenexporte (aus Audit-Log) + prisma.auditLog.count({ + where: { + action: 'EXPORT', + resourceType: 'GDPR', + createdAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) }, + }, + }), + // Consent-Statistik + prisma.customerConsent.groupBy({ + by: ['status'], + _count: { id: true }, + }), + ]); + + const consentByStatus = consentStats.reduce( + (acc, s) => { + acc[s.status.toLowerCase()] = s._count.id; + return acc; + }, + { granted: 0, withdrawn: 0, pending: 0 } as Record + ); + + return { + deletionRequests: { + pending: pendingDeletions, + completedLast30Days: completedDeletions, + }, + dataExports: { + last30Days: recentExports, + }, + consents: consentByStatus, + }; +} diff --git a/backend/src/services/smtpService.ts b/backend/src/services/smtpService.ts index 355ad17a..9d4a8274 100644 --- a/backend/src/services/smtpService.ts +++ b/backend/src/services/smtpService.ts @@ -42,11 +42,19 @@ export interface SendEmailResult { error?: string; } +// Optionaler Logging-Kontext +export interface EmailLogContext { + context: string; // z.B. "consent-link", "authorization-request", "customer-email" + customerId?: number; + triggeredBy?: string; // User-Email +} + // E-Mail senden export async function sendEmail( credentials: SmtpCredentials, fromAddress: string, - params: SendEmailParams + params: SendEmailParams, + logContext?: EmailLogContext ): Promise { // Verschlüsselungs-Einstellungen basierend auf Modus const encryption = credentials.encryption ?? 'SSL'; @@ -155,6 +163,27 @@ export async function sendEmail( // Nicht kritisch - E-Mail wurde trotzdem gesendet } + // E-Mail-Log erstellen (async, nicht blockierend) + if (logContext) { + import('./emailLog.service.js').then(({ createEmailLog }) => { + createEmailLog({ + fromAddress, + toAddress: Array.isArray(params.to) ? params.to.join(', ') : params.to, + subject: params.subject, + context: logContext.context, + customerId: logContext.customerId, + triggeredBy: logContext.triggeredBy, + smtpServer: credentials.host, + smtpPort: credentials.port, + smtpEncryption: credentials.encryption ?? 'SSL', + smtpUser: credentials.user, + success: true, + messageId: result.messageId, + smtpResponse: result.response, + }).catch((err) => console.error('EmailLog write error:', err)); + }); + } + return { success: true, messageId: result.messageId, @@ -203,6 +232,26 @@ export async function sendEmail( } } + // E-Mail-Log erstellen (Fehler) + if (logContext) { + import('./emailLog.service.js').then(({ createEmailLog }) => { + createEmailLog({ + fromAddress, + toAddress: Array.isArray(params.to) ? params.to.join(', ') : params.to, + subject: params.subject, + context: logContext.context, + customerId: logContext.customerId, + triggeredBy: logContext.triggeredBy, + smtpServer: credentials.host, + smtpPort: credentials.port, + smtpEncryption: credentials.encryption ?? 'SSL', + smtpUser: credentials.user, + success: false, + errorMessage, + }).catch((err) => console.error('EmailLog write error:', err)); + }); + } + return { success: false, error: errorMessage, diff --git a/backend/src/services/user.service.ts b/backend/src/services/user.service.ts index 5582e50b..cb5c8f3a 100644 --- a/backend/src/services/user.service.ts +++ b/backend/src/services/user.service.ts @@ -47,6 +47,9 @@ export async function getAllUsers(filters: UserFilters) { lastName: true, isActive: true, customerId: true, + whatsappNumber: true, + telegramUsername: true, + signalNumber: true, createdAt: true, roles: { include: { @@ -62,21 +65,25 @@ export async function getAllUsers(filters: UserFilters) { prisma.user.count({ where }), ]); - // Get Developer role ID - const developerRole = await prisma.role.findFirst({ - where: { name: 'Developer' }, - }); + // Get hidden role IDs + const [developerRole, gdprRole] = await Promise.all([ + prisma.role.findFirst({ where: { name: 'Developer' } }), + prisma.role.findFirst({ where: { name: 'DSGVO' } }), + ]); return { users: users.map((u) => { - // Check if user has developer role assigned const hasDeveloperAccess = developerRole ? u.roles.some((ur) => ur.roleId === developerRole.id) : false; + const hasGdprAccess = gdprRole + ? u.roles.some((ur) => ur.roleId === gdprRole.id) + : false; return { ...u, roles: u.roles.map((r) => r.role), hasDeveloperAccess, + hasGdprAccess, }; }), pagination: buildPaginationResponse(page, limit, total), @@ -93,6 +100,9 @@ export async function getUserById(id: number) { lastName: true, isActive: true, customerId: true, + whatsappNumber: true, + telegramUsername: true, + signalNumber: true, createdAt: true, updatedAt: true, roles: { @@ -135,6 +145,10 @@ export async function createUser(data: { roleIds: number[]; customerId?: number; hasDeveloperAccess?: boolean; + hasGdprAccess?: boolean; + whatsappNumber?: string; + telegramUsername?: string; + signalNumber?: string; }) { const hashedPassword = await bcrypt.hash(data.password, 10); @@ -145,6 +159,9 @@ export async function createUser(data: { firstName: data.firstName, lastName: data.lastName, customerId: data.customerId, + whatsappNumber: data.whatsappNumber || null, + telegramUsername: data.telegramUsername || null, + signalNumber: data.signalNumber || null, roles: { create: data.roleIds.map((roleId) => ({ roleId })), }, @@ -167,6 +184,11 @@ export async function createUser(data: { await setUserDeveloperAccess(user.id, true); } + // DSGVO-Zugriff setzen falls aktiviert + if (data.hasGdprAccess) { + await setUserGdprAccess(user.id, true); + } + return user; } @@ -181,9 +203,13 @@ export async function updateUser( roleIds?: number[]; customerId?: number; hasDeveloperAccess?: boolean; + hasGdprAccess?: boolean; + whatsappNumber?: string; + telegramUsername?: string; + signalNumber?: string; } ) { - const { roleIds, password, hasDeveloperAccess, ...userData } = data; + const { roleIds, password, hasDeveloperAccess, hasGdprAccess, ...userData } = data; // Check if this would remove the last admin const isBeingDeactivated = userData.isActive === false; @@ -311,18 +337,20 @@ export async function updateUser( } // Handle developer access - console.log('updateUser - hasDeveloperAccess:', hasDeveloperAccess); if (hasDeveloperAccess !== undefined) { await setUserDeveloperAccess(id, hasDeveloperAccess); } + // Handle GDPR access + if (hasGdprAccess !== undefined) { + await setUserGdprAccess(id, hasGdprAccess); + } + return getUserById(id); } // Helper to set developer access for a user async function setUserDeveloperAccess(userId: number, enabled: boolean) { - console.log('setUserDeveloperAccess called - userId:', userId, 'enabled:', enabled); - // Get or create developer:access permission let developerPerm = await prisma.permission.findFirst({ where: { resource: 'developer', action: 'access' }, @@ -356,11 +384,7 @@ async function setUserDeveloperAccess(userId: number, enabled: boolean) { where: { userId, roleId: developerRole.id }, }); - console.log('setUserDeveloperAccess - developerRole.id:', developerRole.id, 'hasRole:', hasRole); - if (enabled && !hasRole) { - // Add Developer role - console.log('Adding Developer role'); await prisma.userRole.create({ data: { userId, roleId: developerRole.id }, }); @@ -370,8 +394,6 @@ async function setUserDeveloperAccess(userId: number, enabled: boolean) { data: { tokenInvalidatedAt: new Date() }, }); } else if (!enabled && hasRole) { - // Remove Developer role - console.log('Removing Developer role'); await prisma.userRole.delete({ where: { userId_roleId: { userId, roleId: developerRole.id } }, }); @@ -380,8 +402,56 @@ async function setUserDeveloperAccess(userId: number, enabled: boolean) { where: { id: userId }, data: { tokenInvalidatedAt: new Date() }, }); - } else { - console.log('No action needed - enabled:', enabled, 'hasRole:', !!hasRole); + } +} + +// Helper to set GDPR access for a user +async function setUserGdprAccess(userId: number, enabled: boolean) { + // Get or create DSGVO role + let gdprRole = await prisma.role.findFirst({ + where: { name: 'DSGVO' }, + }); + + if (!gdprRole) { + // Create DSGVO role with all audit:* and gdpr:* permissions + const gdprPermissions = await prisma.permission.findMany({ + where: { + OR: [{ resource: 'audit' }, { resource: 'gdpr' }], + }, + }); + + gdprRole = await prisma.role.create({ + data: { + name: 'DSGVO', + description: 'DSGVO-Zugriff: Audit-Logs und Datenschutz-Verwaltung', + permissions: { + create: gdprPermissions.map((p) => ({ permissionId: p.id })), + }, + }, + }); + } + + // Check if user already has DSGVO role + const hasRole = await prisma.userRole.findFirst({ + where: { userId, roleId: gdprRole.id }, + }); + + if (enabled && !hasRole) { + await prisma.userRole.create({ + data: { userId, roleId: gdprRole.id }, + }); + await prisma.user.update({ + where: { id: userId }, + data: { tokenInvalidatedAt: new Date() }, + }); + } else if (!enabled && hasRole) { + await prisma.userRole.delete({ + where: { userId_roleId: { userId, roleId: gdprRole.id } }, + }); + await prisma.user.update({ + where: { id: userId }, + data: { tokenInvalidatedAt: new Date() }, + }); } } diff --git a/datenschutzerklärung_vorlage.docx b/datenschutzerklärung_vorlage.docx new file mode 100644 index 00000000..3a3ccb10 Binary files /dev/null and b/datenschutzerklärung_vorlage.docx differ diff --git a/frontend/dist/assets/index-AsLwOxex.js b/frontend/dist/assets/index-AsLwOxex.js deleted file mode 100644 index e3d0e444..00000000 --- a/frontend/dist/assets/index-AsLwOxex.js +++ /dev/null @@ -1,730 +0,0 @@ -var yf=e=>{throw TypeError(e)};var zc=(e,t,n)=>t.has(e)||yf("Cannot "+n);var M=(e,t,n)=>(zc(e,t,"read from private field"),n?n.call(e):t.get(e)),me=(e,t,n)=>t.has(e)?yf("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),te=(e,t,n,r)=>(zc(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),be=(e,t,n)=>(zc(e,t,"access private method"),n);var Ll=(e,t,n,r)=>({set _(a){te(e,t,a,n)},get _(){return M(e,t,r)}});function Qv(e,t){for(var n=0;nr[a]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();function Hv(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tg={exports:{}},rc={},sg={exports:{}},Ee={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var bl=Symbol.for("react.element"),Wv=Symbol.for("react.portal"),Gv=Symbol.for("react.fragment"),Zv=Symbol.for("react.strict_mode"),Jv=Symbol.for("react.profiler"),Xv=Symbol.for("react.provider"),Yv=Symbol.for("react.context"),ej=Symbol.for("react.forward_ref"),tj=Symbol.for("react.suspense"),sj=Symbol.for("react.memo"),nj=Symbol.for("react.lazy"),vf=Symbol.iterator;function rj(e){return e===null||typeof e!="object"?null:(e=vf&&e[vf]||e["@@iterator"],typeof e=="function"?e:null)}var ng={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},rg=Object.assign,ag={};function Ya(e,t,n){this.props=e,this.context=t,this.refs=ag,this.updater=n||ng}Ya.prototype.isReactComponent={};Ya.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Ya.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ig(){}ig.prototype=Ya.prototype;function Yu(e,t,n){this.props=e,this.context=t,this.refs=ag,this.updater=n||ng}var em=Yu.prototype=new ig;em.constructor=Yu;rg(em,Ya.prototype);em.isPureReactComponent=!0;var jf=Array.isArray,lg=Object.prototype.hasOwnProperty,tm={current:null},og={key:!0,ref:!0,__self:!0,__source:!0};function cg(e,t,n){var r,a={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)lg.call(t,r)&&!og.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,de=B[le];if(0>>1;lea(st,Q))Ca(nt,st)?(B[le]=nt,B[C]=Q,le=C):(B[le]=st,B[Ve]=Q,le=Ve);else if(Ca(nt,Q))B[le]=nt,B[C]=Q,le=C;else break e}}return _}function a(B,_){var Q=B.sortIndex-_.sortIndex;return Q!==0?Q:B.id-_.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();e.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,x=3,m=!1,f=!1,p=!1,b=typeof setTimeout=="function"?setTimeout:null,g=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(B){for(var _=n(d);_!==null;){if(_.callback===null)r(d);else if(_.startTime<=B)r(d),_.sortIndex=_.expirationTime,t(c,_);else break;_=n(d)}}function N(B){if(p=!1,v(B),!f)if(n(c)!==null)f=!0,k(E);else{var _=n(d);_!==null&&K(N,_.startTime-B)}}function E(B,_){f=!1,p&&(p=!1,g(w),w=-1),m=!0;var Q=x;try{for(v(_),h=n(c);h!==null&&(!(h.expirationTime>_)||B&&!O());){var le=h.callback;if(typeof le=="function"){h.callback=null,x=h.priorityLevel;var de=le(h.expirationTime<=_);_=e.unstable_now(),typeof de=="function"?h.callback=de:h===n(c)&&r(c),v(_)}else r(c);h=n(c)}if(h!==null)var Ke=!0;else{var Ve=n(d);Ve!==null&&K(N,Ve.startTime-_),Ke=!1}return Ke}finally{h=null,x=Q,m=!1}}var P=!1,I=null,w=-1,S=5,A=-1;function O(){return!(e.unstable_now()-AB||125le?(B.sortIndex=Q,t(d,B),n(c)===null&&B===n(d)&&(p?(g(w),w=-1):p=!0,K(N,Q-le))):(B.sortIndex=de,t(c,B),f||m||(f=!0,k(E))),B},e.unstable_shouldYield=O,e.unstable_wrapCallback=function(B){var _=x;return function(){var Q=x;x=_;try{return B.apply(this,arguments)}finally{x=Q}}}})(fg);hg.exports=fg;var xj=hg.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var gj=j,js=xj;function Y(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),wd=Object.prototype.hasOwnProperty,yj=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Nf={},wf={};function vj(e){return wd.call(wf,e)?!0:wd.call(Nf,e)?!1:yj.test(e)?wf[e]=!0:(Nf[e]=!0,!1)}function jj(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function bj(e,t,n,r){if(t===null||typeof t>"u"||jj(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Xt(e,t,n,r,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var Lt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Lt[e]=new Xt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Lt[t]=new Xt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Lt[e]=new Xt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Lt[e]=new Xt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Lt[e]=new Xt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Lt[e]=new Xt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Lt[e]=new Xt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Lt[e]=new Xt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Lt[e]=new Xt(e,5,!1,e.toLowerCase(),null,!1,!1)});var nm=/[\-:]([a-z])/g;function rm(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(nm,rm);Lt[t]=new Xt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(nm,rm);Lt[t]=new Xt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(nm,rm);Lt[t]=new Xt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Lt[e]=new Xt(e,1,!1,e.toLowerCase(),null,!1,!1)});Lt.xlinkHref=new Xt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Lt[e]=new Xt(e,1,!1,e.toLowerCase(),null,!0,!0)});function am(e,t,n,r){var a=Lt.hasOwnProperty(t)?Lt[t]:null;(a!==null?a.type!==0:r||!(2o||a[l]!==i[o]){var c=` -`+a[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=o);break}}}finally{Kc=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?bi(e):""}function Nj(e){switch(e.tag){case 5:return bi(e.type);case 16:return bi("Lazy");case 13:return bi("Suspense");case 19:return bi("SuspenseList");case 0:case 2:case 15:return e=Bc(e.type,!1),e;case 11:return e=Bc(e.type.render,!1),e;case 1:return e=Bc(e.type,!0),e;default:return""}}function Ed(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case oa:return"Fragment";case la:return"Portal";case Sd:return"Profiler";case im:return"StrictMode";case kd:return"Suspense";case Cd:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case gg:return(e.displayName||"Context")+".Consumer";case xg:return(e._context.displayName||"Context")+".Provider";case lm:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case om:return t=e.displayName||null,t!==null?t:Ed(e.type)||"Memo";case $n:t=e._payload,e=e._init;try{return Ed(e(t))}catch{}}return null}function wj(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ed(t);case 8:return t===im?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function fr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function vg(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Sj(e){var t=vg(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function $l(e){e._valueTracker||(e._valueTracker=Sj(e))}function jg(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=vg(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function wo(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Dd(e,t){var n=t.checked;return ot({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function kf(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=fr(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function bg(e,t){t=t.checked,t!=null&&am(e,"checked",t,!1)}function Ad(e,t){bg(e,t);var n=fr(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Pd(e,t.type,n):t.hasOwnProperty("defaultValue")&&Pd(e,t.type,fr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Cf(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Pd(e,t,n){(t!=="number"||wo(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Ni=Array.isArray;function ja(e,t,n,r){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=_l.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function _i(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Ei={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},kj=["Webkit","ms","Moz","O"];Object.keys(Ei).forEach(function(e){kj.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Ei[t]=Ei[e]})});function kg(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Ei.hasOwnProperty(e)&&Ei[e]?(""+t).trim():t+"px"}function Cg(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=kg(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,a):e[n]=a}}var Cj=ot({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Fd(e,t){if(t){if(Cj[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Y(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Y(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Y(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Y(62))}}function Id(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Rd=null;function cm(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ld=null,ba=null,Na=null;function Af(e){if(e=Sl(e)){if(typeof Ld!="function")throw Error(Y(280));var t=e.stateNode;t&&(t=cc(t),Ld(e.stateNode,e.type,t))}}function Eg(e){ba?Na?Na.push(e):Na=[e]:ba=e}function Dg(){if(ba){var e=ba,t=Na;if(Na=ba=null,Af(e),t)for(e=0;e>>=0,e===0?32:31-(Oj(e)/zj|0)|0}var Kl=64,Bl=4194304;function wi(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Eo(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,a=e.suspendedLanes,i=e.pingedLanes,l=n&268435455;if(l!==0){var o=l&~a;o!==0?r=wi(o):(i&=l,i!==0&&(r=wi(i)))}else l=n&~a,l!==0?r=wi(l):i!==0&&(r=wi(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&a)&&(a=r&-r,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Nl(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Bs(t),e[t]=n}function Bj(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Ai),zf=" ",$f=!1;function Wg(e,t){switch(e){case"keyup":return xb.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Gg(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ca=!1;function yb(e,t){switch(e){case"compositionend":return Gg(t);case"keypress":return t.which!==32?null:($f=!0,zf);case"textInput":return e=t.data,e===zf&&$f?null:e;default:return null}}function vb(e,t){if(ca)return e==="compositionend"||!gm&&Wg(e,t)?(e=Qg(),lo=fm=tr=null,ca=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Uf(n)}}function Yg(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Yg(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ey(){for(var e=window,t=wo();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=wo(e.document)}return t}function ym(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Db(e){var t=ey(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Yg(n.ownerDocument.documentElement,n)){if(r!==null&&ym(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=n.textContent.length,i=Math.min(r.start,a);r=r.end===void 0?i:Math.min(r.end,a),!e.extend&&i>r&&(a=r,r=i,i=a),a=qf(n,i);var l=qf(n,r);a&&l&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,da=null,Bd=null,Mi=null,Ud=!1;function Vf(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ud||da==null||da!==wo(r)||(r=da,"selectionStart"in r&&ym(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Mi&&Qi(Mi,r)||(Mi=r,r=Po(Bd,"onSelect"),0ha||(e.current=Gd[ha],Gd[ha]=null,ha--)}function Qe(e,t){ha++,Gd[ha]=e.current,e.current=t}var pr={},Ut=yr(pr),os=yr(!1),qr=pr;function qa(e,t){var n=e.type.contextTypes;if(!n)return pr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in n)a[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function cs(e){return e=e.childContextTypes,e!=null}function To(){Je(os),Je(Ut)}function Xf(e,t,n){if(Ut.current!==pr)throw Error(Y(168));Qe(Ut,t),Qe(os,n)}function cy(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var a in r)if(!(a in t))throw Error(Y(108,wj(e)||"Unknown",a));return ot({},n,r)}function Fo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||pr,qr=Ut.current,Qe(Ut,e),Qe(os,os.current),!0}function Yf(e,t,n){var r=e.stateNode;if(!r)throw Error(Y(169));n?(e=cy(e,t,qr),r.__reactInternalMemoizedMergedChildContext=e,Je(os),Je(Ut),Qe(Ut,e)):Je(os),Qe(os,n)}var gn=null,dc=!1,sd=!1;function dy(e){gn===null?gn=[e]:gn.push(e)}function _b(e){dc=!0,dy(e)}function vr(){if(!sd&&gn!==null){sd=!0;var e=0,t=Ue;try{var n=gn;for(Ue=1;e>=l,a-=l,wn=1<<32-Bs(t)+a|n<w?(S=I,I=null):S=I.sibling;var A=x(g,I,v[w],N);if(A===null){I===null&&(I=S);break}e&&I&&A.alternate===null&&t(g,I),y=i(A,y,w),P===null?E=A:P.sibling=A,P=A,I=S}if(w===v.length)return n(g,I),tt&&Nr(g,w),E;if(I===null){for(;ww?(S=I,I=null):S=I.sibling;var O=x(g,I,A.value,N);if(O===null){I===null&&(I=S);break}e&&I&&O.alternate===null&&t(g,I),y=i(O,y,w),P===null?E=O:P.sibling=O,P=O,I=S}if(A.done)return n(g,I),tt&&Nr(g,w),E;if(I===null){for(;!A.done;w++,A=v.next())A=h(g,A.value,N),A!==null&&(y=i(A,y,w),P===null?E=A:P.sibling=A,P=A);return tt&&Nr(g,w),E}for(I=r(g,I);!A.done;w++,A=v.next())A=m(I,g,w,A.value,N),A!==null&&(e&&A.alternate!==null&&I.delete(A.key===null?w:A.key),y=i(A,y,w),P===null?E=A:P.sibling=A,P=A);return e&&I.forEach(function(R){return t(g,R)}),tt&&Nr(g,w),E}function b(g,y,v,N){if(typeof v=="object"&&v!==null&&v.type===oa&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case zl:e:{for(var E=v.key,P=y;P!==null;){if(P.key===E){if(E=v.type,E===oa){if(P.tag===7){n(g,P.sibling),y=a(P,v.props.children),y.return=g,g=y;break e}}else if(P.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===$n&&sp(E)===P.type){n(g,P.sibling),y=a(P,v.props),y.ref=xi(g,P,v),y.return=g,g=y;break e}n(g,P);break}else t(g,P);P=P.sibling}v.type===oa?(y=Kr(v.props.children,g.mode,N,v.key),y.return=g,g=y):(N=xo(v.type,v.key,v.props,null,g.mode,N),N.ref=xi(g,y,v),N.return=g,g=N)}return l(g);case la:e:{for(P=v.key;y!==null;){if(y.key===P)if(y.tag===4&&y.stateNode.containerInfo===v.containerInfo&&y.stateNode.implementation===v.implementation){n(g,y.sibling),y=a(y,v.children||[]),y.return=g,g=y;break e}else{n(g,y);break}else t(g,y);y=y.sibling}y=dd(v,g.mode,N),y.return=g,g=y}return l(g);case $n:return P=v._init,b(g,y,P(v._payload),N)}if(Ni(v))return f(g,y,v,N);if(ui(v))return p(g,y,v,N);Gl(g,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,y!==null&&y.tag===6?(n(g,y.sibling),y=a(y,v),y.return=g,g=y):(n(g,y),y=cd(v,g.mode,N),y.return=g,g=y),l(g)):n(g,y)}return b}var Qa=fy(!0),py=fy(!1),Lo=yr(null),Oo=null,xa=null,Nm=null;function wm(){Nm=xa=Oo=null}function Sm(e){var t=Lo.current;Je(Lo),e._currentValue=t}function Xd(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Sa(e,t){Oo=e,Nm=xa=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ls=!0),e.firstContext=null)}function Ts(e){var t=e._currentValue;if(Nm!==e)if(e={context:e,memoizedValue:t,next:null},xa===null){if(Oo===null)throw Error(Y(308));xa=e,Oo.dependencies={lanes:0,firstContext:e}}else xa=xa.next=e;return t}var Cr=null;function km(e){Cr===null?Cr=[e]:Cr.push(e)}function xy(e,t,n,r){var a=t.interleaved;return a===null?(n.next=n,km(t)):(n.next=a.next,a.next=n),t.interleaved=n,Pn(e,r)}function Pn(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var _n=!1;function Cm(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function gy(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Cn(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function or(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Te&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,Pn(e,n)}return a=r.interleaved,a===null?(t.next=t,km(r)):(t.next=a.next,a.next=t),r.interleaved=t,Pn(e,n)}function co(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,um(e,n)}}function np(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var a=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?a=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?a=i=t:i=i.next=t}else a=i=t;n={baseState:r.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function zo(e,t,n,r){var a=e.updateQueue;_n=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=e.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var x=o.lane,m=o.eventTime;if((r&x)===x){u!==null&&(u=u.next={eventTime:m,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var f=e,p=o;switch(x=t,m=n,p.tag){case 1:if(f=p.payload,typeof f=="function"){h=f.call(m,h,x);break e}h=f;break e;case 3:f.flags=f.flags&-65537|128;case 0:if(f=p.payload,x=typeof f=="function"?f.call(m,h,x):f,x==null)break e;h=ot({},h,x);break e;case 2:_n=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,x=a.effects,x===null?a.effects=[o]:x.push(o))}else m={eventTime:m,lane:x,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=m,c=h):u=u.next=m,l|=x;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;x=o,o=x.next,x.next=null,a.lastBaseUpdate=x,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);Hr|=l,e.lanes=l,e.memoizedState=h}}function rp(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=rd.transition;rd.transition={};try{e(!1),t()}finally{Ue=n,rd.transition=r}}function Iy(){return Fs().memoizedState}function qb(e,t,n){var r=dr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ry(e))Ly(t,n);else if(n=xy(e,t,n,r),n!==null){var a=Zt();Us(n,e,r,a),Oy(n,t,r)}}function Vb(e,t,n){var r=dr(e),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ry(e))Ly(t,a);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,o=i(l,n);if(a.hasEagerState=!0,a.eagerState=o,qs(o,l)){var c=t.interleaved;c===null?(a.next=a,km(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=xy(e,t,a,r),n!==null&&(a=Zt(),Us(n,e,r,a),Oy(n,t,r))}}function Ry(e){var t=e.alternate;return e===it||t!==null&&t===it}function Ly(e,t){Ti=_o=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Oy(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,um(e,n)}}var Ko={readContext:Ts,useCallback:zt,useContext:zt,useEffect:zt,useImperativeHandle:zt,useInsertionEffect:zt,useLayoutEffect:zt,useMemo:zt,useReducer:zt,useRef:zt,useState:zt,useDebugValue:zt,useDeferredValue:zt,useTransition:zt,useMutableSource:zt,useSyncExternalStore:zt,useId:zt,unstable_isNewReconciler:!1},Qb={readContext:Ts,useCallback:function(e,t){return Zs().memoizedState=[e,t===void 0?null:t],e},useContext:Ts,useEffect:ip,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,mo(4194308,4,Ay.bind(null,t,e),n)},useLayoutEffect:function(e,t){return mo(4194308,4,e,t)},useInsertionEffect:function(e,t){return mo(4,2,e,t)},useMemo:function(e,t){var n=Zs();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Zs();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=qb.bind(null,it,e),[r.memoizedState,e]},useRef:function(e){var t=Zs();return e={current:e},t.memoizedState=e},useState:ap,useDebugValue:Im,useDeferredValue:function(e){return Zs().memoizedState=e},useTransition:function(){var e=ap(!1),t=e[0];return e=Ub.bind(null,e[1]),Zs().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=it,a=Zs();if(tt){if(n===void 0)throw Error(Y(407));n=n()}else{if(n=t(),Pt===null)throw Error(Y(349));Qr&30||by(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,ip(wy.bind(null,r,i,e),[e]),r.flags|=2048,el(9,Ny.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Zs(),t=Pt.identifierPrefix;if(tt){var n=Sn,r=wn;n=(r&~(1<<32-Bs(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Xi++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=l.createElement(n,{is:r.is}):(e=l.createElement(n),n==="select"&&(l=e,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):e=l.createElementNS(e,n),e[tn]=t,e[Gi]=r,Hy(e,t,!1,!1),t.stateNode=e;e:{switch(l=Id(n,r),n){case"dialog":Ze("cancel",e),Ze("close",e),a=r;break;case"iframe":case"object":case"embed":Ze("load",e),a=r;break;case"video":case"audio":for(a=0;aGa&&(t.flags|=128,r=!0,gi(i,!1),t.lanes=4194304)}else{if(!r)if(e=$o(l),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),gi(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!tt)return $t(t),null}else 2*ft()-i.renderingStartTime>Ga&&n!==1073741824&&(t.flags|=128,r=!0,gi(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=ft(),t.sibling=null,n=at.current,Qe(at,r?n&1|2:n&1),t):($t(t),null);case 22:case 23:return _m(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?ps&1073741824&&($t(t),t.subtreeFlags&6&&(t.flags|=8192)):$t(t),null;case 24:return null;case 25:return null}throw Error(Y(156,t.tag))}function eN(e,t){switch(jm(t),t.tag){case 1:return cs(t.type)&&To(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ha(),Je(os),Je(Ut),Am(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Dm(t),null;case 13:if(Je(at),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Y(340));Va()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Je(at),null;case 4:return Ha(),null;case 10:return Sm(t.type._context),null;case 22:case 23:return _m(),null;case 24:return null;default:return null}}var Jl=!1,Kt=!1,tN=typeof WeakSet=="function"?WeakSet:Set,he=null;function ga(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){mt(e,t,r)}else n.current=null}function lu(e,t,n){try{n()}catch(r){mt(e,t,r)}}var gp=!1;function sN(e,t){if(qd=Do,e=ey(),ym(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=e,x=null;t:for(;;){for(var m;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(m=h.firstChild)!==null;)x=h,h=m;for(;;){if(h===e)break t;if(x===n&&++d===a&&(o=l),x===i&&++u===r&&(c=l),(m=h.nextSibling)!==null)break;h=x,x=h.parentNode}h=m}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Vd={focusedElem:e,selectionRange:n},Do=!1,he=t;he!==null;)if(t=he,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,he=e;else for(;he!==null;){t=he;try{var f=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(f!==null){var p=f.memoizedProps,b=f.memoizedState,g=t.stateNode,y=g.getSnapshotBeforeUpdate(t.elementType===t.type?p:Rs(t.type,p),b);g.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Y(163))}}catch(N){mt(t,t.return,N)}if(e=t.sibling,e!==null){e.return=t.return,he=e;break}he=t.return}return f=gp,gp=!1,f}function Fi(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var a=r=r.next;do{if((a.tag&e)===e){var i=a.destroy;a.destroy=void 0,i!==void 0&&lu(t,n,i)}a=a.next}while(a!==r)}}function hc(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function ou(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Zy(e){var t=e.alternate;t!==null&&(e.alternate=null,Zy(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[tn],delete t[Gi],delete t[Wd],delete t[zb],delete t[$b])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Jy(e){return e.tag===5||e.tag===3||e.tag===4}function yp(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Jy(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function cu(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Mo));else if(r!==4&&(e=e.child,e!==null))for(cu(e,t,n),e=e.sibling;e!==null;)cu(e,t,n),e=e.sibling}function du(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(du(e,t,n),e=e.sibling;e!==null;)du(e,t,n),e=e.sibling}var Mt=null,zs=!1;function On(e,t,n){for(n=n.child;n!==null;)Xy(e,t,n),n=n.sibling}function Xy(e,t,n){if(rn&&typeof rn.onCommitFiberUnmount=="function")try{rn.onCommitFiberUnmount(ac,n)}catch{}switch(n.tag){case 5:Kt||ga(n,t);case 6:var r=Mt,a=zs;Mt=null,On(e,t,n),Mt=r,zs=a,Mt!==null&&(zs?(e=Mt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Mt.removeChild(n.stateNode));break;case 18:Mt!==null&&(zs?(e=Mt,n=n.stateNode,e.nodeType===8?td(e.parentNode,n):e.nodeType===1&&td(e,n),qi(e)):td(Mt,n.stateNode));break;case 4:r=Mt,a=zs,Mt=n.stateNode.containerInfo,zs=!0,On(e,t,n),Mt=r,zs=a;break;case 0:case 11:case 14:case 15:if(!Kt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){a=r=r.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&lu(n,t,l),a=a.next}while(a!==r)}On(e,t,n);break;case 1:if(!Kt&&(ga(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){mt(n,t,o)}On(e,t,n);break;case 21:On(e,t,n);break;case 22:n.mode&1?(Kt=(r=Kt)||n.memoizedState!==null,On(e,t,n),Kt=r):On(e,t,n);break;default:On(e,t,n)}}function vp(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new tN),t.forEach(function(r){var a=uN.bind(null,e,r);n.has(r)||(n.add(r),r.then(a,a))})}}function Is(e,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=ft()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*rN(r/1960))-r,10e?16:e,sr===null)var r=!1;else{if(e=sr,sr=null,qo=0,Te&6)throw Error(Y(331));var a=Te;for(Te|=4,he=e.current;he!==null;){var i=he,l=i.child;if(he.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cft()-zm?_r(e,0):Om|=n),ds(e,t)}function i0(e,t){t===0&&(e.mode&1?(t=Bl,Bl<<=1,!(Bl&130023424)&&(Bl=4194304)):t=1);var n=Zt();e=Pn(e,t),e!==null&&(Nl(e,t,n),ds(e,n))}function dN(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),i0(e,n)}function uN(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(Y(314))}r!==null&&r.delete(t),i0(e,n)}var l0;l0=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||os.current)ls=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ls=!1,Xb(e,t,n);ls=!!(e.flags&131072)}else ls=!1,tt&&t.flags&1048576&&uy(t,Ro,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;ho(e,t),e=t.pendingProps;var a=qa(t,Ut.current);Sa(t,n),a=Mm(null,t,r,e,a,n);var i=Tm();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,cs(r)?(i=!0,Fo(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Cm(t),a.updater=mc,t.stateNode=a,a._reactInternals=t,eu(t,r,e,n),t=nu(null,t,r,!0,i,n)):(t.tag=0,tt&&i&&vm(t),Gt(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(ho(e,t),e=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=hN(r),e=Rs(r,e),a){case 0:t=su(null,t,r,e,n);break e;case 1:t=fp(null,t,r,e,n);break e;case 11:t=mp(null,t,r,e,n);break e;case 14:t=hp(null,t,r,Rs(r.type,e),n);break e}throw Error(Y(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),su(e,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),fp(e,t,r,a,n);case 3:e:{if(qy(t),e===null)throw Error(Y(387));r=t.pendingProps,i=t.memoizedState,a=i.element,gy(e,t),zo(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=Wa(Error(Y(423)),t),t=pp(e,t,r,n,a);break e}else if(r!==a){a=Wa(Error(Y(424)),t),t=pp(e,t,r,n,a);break e}else for(ys=lr(t.stateNode.containerInfo.firstChild),vs=t,tt=!0,$s=null,n=py(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Va(),r===a){t=Mn(e,t,n);break e}Gt(e,t,r,n)}t=t.child}return t;case 5:return yy(t),e===null&&Jd(t),r=t.type,a=t.pendingProps,i=e!==null?e.memoizedProps:null,l=a.children,Qd(r,a)?l=null:i!==null&&Qd(r,i)&&(t.flags|=32),Uy(e,t),Gt(e,t,l,n),t.child;case 6:return e===null&&Jd(t),null;case 13:return Vy(e,t,n);case 4:return Em(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Qa(t,null,r,n):Gt(e,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),mp(e,t,r,a,n);case 7:return Gt(e,t,t.pendingProps,n),t.child;case 8:return Gt(e,t,t.pendingProps.children,n),t.child;case 12:return Gt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,Qe(Lo,r._currentValue),r._currentValue=l,i!==null)if(qs(i.value,l)){if(i.children===a.children&&!os.current){t=Mn(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){l=i.child;for(var c=o.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=Cn(-1,n&-n),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var u=d.pending;u===null?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),Xd(i.return,n,t),o.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(Y(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),Xd(l,n,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}Gt(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,Sa(t,n),a=Ts(a),r=r(a),t.flags|=1,Gt(e,t,r,n),t.child;case 14:return r=t.type,a=Rs(r,t.pendingProps),a=Rs(r.type,a),hp(e,t,r,a,n);case 15:return Ky(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:Rs(r,a),ho(e,t),t.tag=1,cs(r)?(e=!0,Fo(t)):e=!1,Sa(t,n),zy(t,r,a),eu(t,r,a,n),nu(null,t,r,!0,e,n);case 19:return Qy(e,t,n);case 22:return By(e,t,n)}throw Error(Y(156,t.tag))};function o0(e,t){return Rg(e,t)}function mN(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ds(e,t,n,r){return new mN(e,t,n,r)}function Bm(e){return e=e.prototype,!(!e||!e.isReactComponent)}function hN(e){if(typeof e=="function")return Bm(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lm)return 11;if(e===om)return 14}return 2}function ur(e,t){var n=e.alternate;return n===null?(n=Ds(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function xo(e,t,n,r,a,i){var l=2;if(r=e,typeof e=="function")Bm(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case oa:return Kr(n.children,a,i,t);case im:l=8,a|=8;break;case Sd:return e=Ds(12,n,t,a|2),e.elementType=Sd,e.lanes=i,e;case kd:return e=Ds(13,n,t,a),e.elementType=kd,e.lanes=i,e;case Cd:return e=Ds(19,n,t,a),e.elementType=Cd,e.lanes=i,e;case yg:return pc(n,a,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case xg:l=10;break e;case gg:l=9;break e;case lm:l=11;break e;case om:l=14;break e;case $n:l=16,r=null;break e}throw Error(Y(130,e==null?e:typeof e,""))}return t=Ds(l,n,t,a),t.elementType=e,t.type=r,t.lanes=i,t}function Kr(e,t,n,r){return e=Ds(7,e,r,t),e.lanes=n,e}function pc(e,t,n,r){return e=Ds(22,e,r,t),e.elementType=yg,e.lanes=n,e.stateNode={isHidden:!1},e}function cd(e,t,n){return e=Ds(6,e,null,t),e.lanes=n,e}function dd(e,t,n){return t=Ds(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function fN(e,t,n,r,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=qc(0),this.expirationTimes=qc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=qc(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function Um(e,t,n,r,a,i,l,o,c){return e=new fN(e,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ds(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Cm(i),e}function pN(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(m0)}catch(e){console.error(e)}}m0(),mg.exports=bs;var jN=mg.exports,Ep=jN;Nd.createRoot=Ep.createRoot,Nd.hydrateRoot=Ep.hydrateRoot;/** - * @remix-run/router v1.23.2 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function sl(){return sl=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Hm(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function NN(){return Math.random().toString(36).substr(2,8)}function Ap(e,t){return{usr:e.state,key:e.key,idx:t}}function pu(e,t,n,r){return n===void 0&&(n=null),sl({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?si(t):t,{state:n,key:t&&t.key||r||NN()})}function Ho(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function si(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function wN(e,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=nr.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(sl({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=nr.Pop;let b=u(),g=b==null?null:b-d;d=b,c&&c({action:o,location:p.location,delta:g})}function x(b,g){o=nr.Push;let y=pu(p.location,b,g);d=u()+1;let v=Ap(y,d),N=p.createHref(y);try{l.pushState(v,"",N)}catch(E){if(E instanceof DOMException&&E.name==="DataCloneError")throw E;a.location.assign(N)}i&&c&&c({action:o,location:p.location,delta:1})}function m(b,g){o=nr.Replace;let y=pu(p.location,b,g);d=u();let v=Ap(y,d),N=p.createHref(y);l.replaceState(v,"",N),i&&c&&c({action:o,location:p.location,delta:0})}function f(b){let g=a.location.origin!=="null"?a.location.origin:a.location.href,y=typeof b=="string"?b:Ho(b);return y=y.replace(/ $/,"%20"),lt(g,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,g)}let p={get action(){return o},get location(){return e(a,l)},listen(b){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(Dp,h),c=b,()=>{a.removeEventListener(Dp,h),c=null}},createHref(b){return t(a,b)},createURL:f,encodeLocation(b){let g=f(b);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:x,replace:m,go(b){return l.go(b)}};return p}var Pp;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Pp||(Pp={}));function SN(e,t,n){return n===void 0&&(n="/"),kN(e,t,n)}function kN(e,t,n,r){let a=typeof t=="string"?si(t):t,i=Za(a.pathname||"/",n);if(i==null)return null;let l=h0(e);CN(l);let o=null;for(let c=0;o==null&&c{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(lt(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let d=mr([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(lt(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),h0(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:FN(d,i.index),routesMeta:u})};return e.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of f0(i.path))a(i,l,c)}),t}function f0(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return a?[i,""]:[i];let l=f0(r.join("/")),o=[];return o.push(...l.map(c=>c===""?i:[i,c].join("/"))),a&&o.push(...l),o.map(c=>e.startsWith("/")&&c===""?"/":c)}function CN(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:IN(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const EN=/^:[\w-]+$/,DN=3,AN=2,PN=1,MN=10,TN=-2,Mp=e=>e==="*";function FN(e,t){let n=e.split("/"),r=n.length;return n.some(Mp)&&(r+=TN),t&&(r+=AN),n.filter(a=>!Mp(a)).reduce((a,i)=>a+(EN.test(i)?DN:i===""?PN:MN),r)}function IN(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function RN(e,t,n){let{routesMeta:r}=e,a={},i="/",l=[];for(let o=0;o{let{paramName:x,isOptional:m}=u;if(x==="*"){let p=o[h]||"";l=i.slice(0,i.length-p.length).replace(/(.)\/+$/,"$1")}const f=o[h];return m&&!f?d[x]=void 0:d[x]=(f||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:e}}function LN(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Hm(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(r.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function ON(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Hm(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function Za(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}const zN=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,$N=e=>zN.test(e);function _N(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?si(e):e,i;if(n)if($N(n))i=n;else{if(n.includes("//")){let l=n;n=n.replace(/\/\/+/g,"/"),Hm(!1,"Pathnames cannot have embedded double slashes - normalizing "+(l+" -> "+n))}n.startsWith("/")?i=Tp(n.substring(1),"/"):i=Tp(n,t)}else i=t;return{pathname:i,search:UN(r),hash:qN(a)}}function Tp(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function ud(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function KN(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Wm(e,t){let n=KN(e);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Gm(e,t,n,r){r===void 0&&(r=!1);let a;typeof e=="string"?a=si(e):(a=sl({},e),lt(!a.pathname||!a.pathname.includes("?"),ud("?","pathname","search",a)),lt(!a.pathname||!a.pathname.includes("#"),ud("#","pathname","hash",a)),lt(!a.search||!a.search.includes("#"),ud("#","search","hash",a)));let i=e===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=n;else{let h=t.length-1;if(!r&&l.startsWith("..")){let x=l.split("/");for(;x[0]==="..";)x.shift(),h-=1;a.pathname=x.join("/")}o=h>=0?t[h]:"/"}let c=_N(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const mr=e=>e.join("/").replace(/\/\/+/g,"/"),BN=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),UN=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,qN=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function VN(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const p0=["post","put","patch","delete"];new Set(p0);const QN=["get",...p0];new Set(QN);/** - * React Router v6.30.3 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function nl(){return nl=Object.assign?Object.assign.bind():function(e){for(var t=1;t{o.current=!0}),j.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=Gm(d,JSON.parse(l),i,u.relative==="path");e==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:mr([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,e])}const GN=j.createContext(null);function ZN(e){let t=j.useContext(cn).outlet;return t&&j.createElement(GN.Provider,{value:e},t)}function Nc(){let{matches:e}=j.useContext(cn),t=e[e.length-1];return t?t.params:{}}function wc(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(In),{matches:a}=j.useContext(cn),{pathname:i}=Rn(),l=JSON.stringify(Wm(a,r.v7_relativeSplatPath));return j.useMemo(()=>Gm(e,JSON.parse(l),i,n==="path"),[e,l,i,n])}function JN(e,t){return XN(e,t)}function XN(e,t,n,r){ni()||lt(!1);let{navigator:a}=j.useContext(In),{matches:i}=j.useContext(cn),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Rn(),u;if(t){var h;let b=typeof t=="string"?si(t):t;c==="/"||(h=b.pathname)!=null&&h.startsWith(c)||lt(!1),u=b}else u=d;let x=u.pathname||"/",m=x;if(c!=="/"){let b=c.replace(/^\//,"").split("/");m="/"+x.replace(/^\//,"").split("/").slice(b.length).join("/")}let f=SN(e,{pathname:m}),p=nw(f&&f.map(b=>Object.assign({},b,{params:Object.assign({},o,b.params),pathname:mr([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:mr([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,n,r);return t&&p?j.createElement(bc.Provider,{value:{location:nl({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:nr.Pop}},p):p}function YN(){let e=lw(),t=VN(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return j.createElement(j.Fragment,null,j.createElement("h2",null,"Unexpected Application Error!"),j.createElement("h3",{style:{fontStyle:"italic"}},t),n?j.createElement("pre",{style:a},n):null,null)}const ew=j.createElement(YN,null);class tw extends j.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?j.createElement(cn.Provider,{value:this.props.routeContext},j.createElement(g0.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function sw(e){let{routeContext:t,match:n,children:r}=e,a=j.useContext(jc);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(cn.Provider,{value:t},r)}function nw(e,t,n,r){var a;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let l=e,o=(a=n)==null?void 0:a.errors;if(o!=null){let u=l.findIndex(h=>h.route.id&&(o==null?void 0:o[h.route.id])!==void 0);u>=0||lt(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,x)=>{let m,f=!1,p=null,b=null;n&&(m=o&&h.route.id?o[h.route.id]:void 0,p=h.route.errorElement||ew,c&&(d<0&&x===0?(cw("route-fallback"),f=!0,b=null):d===x&&(f=!0,b=h.route.hydrateFallbackElement||null)));let g=t.concat(l.slice(0,x+1)),y=()=>{let v;return m?v=p:f?v=b:h.route.Component?v=j.createElement(h.route.Component,null):h.route.element?v=h.route.element:v=u,j.createElement(sw,{match:h,routeContext:{outlet:u,matches:g,isDataRoute:n!=null},children:v})};return n&&(h.route.ErrorBoundary||h.route.errorElement||x===0)?j.createElement(tw,{location:n.location,revalidation:n.revalidation,component:p,error:m,children:y(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):y()},null)}var v0=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(v0||{}),j0=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(j0||{});function rw(e){let t=j.useContext(jc);return t||lt(!1),t}function aw(e){let t=j.useContext(x0);return t||lt(!1),t}function iw(e){let t=j.useContext(cn);return t||lt(!1),t}function b0(e){let t=iw(),n=t.matches[t.matches.length-1];return n.route.id||lt(!1),n.route.id}function lw(){var e;let t=j.useContext(g0),n=aw(),r=b0();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function ow(){let{router:e}=rw(v0.UseNavigateStable),t=b0(j0.UseNavigateStable),n=j.useRef(!1);return y0(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?e.navigate(a):e.navigate(a,nl({fromRouteId:t},i)))},[e,t])}const Fp={};function cw(e,t,n){Fp[e]||(Fp[e]=!0)}function dw(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function va(e){let{to:t,replace:n,state:r,relative:a}=e;ni()||lt(!1);let{future:i,static:l}=j.useContext(In),{matches:o}=j.useContext(cn),{pathname:c}=Rn(),d=Yt(),u=Gm(t,Wm(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return j.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function uw(e){return ZN(e.context)}function ze(e){lt(!1)}function mw(e){let{basename:t="/",children:n=null,location:r,navigationType:a=nr.Pop,navigator:i,static:l=!1,future:o}=e;ni()&<(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:nl({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=si(r));let{pathname:u="/",search:h="",hash:x="",state:m=null,key:f="default"}=r,p=j.useMemo(()=>{let b=Za(u,c);return b==null?null:{location:{pathname:b,search:h,hash:x,state:m,key:f},navigationType:a}},[c,u,h,x,m,f,a]);return p==null?null:j.createElement(In.Provider,{value:d},j.createElement(bc.Provider,{children:n,value:p}))}function hw(e){let{children:t,location:n}=e;return JN(gu(t),n)}new Promise(()=>{});function gu(e,t){t===void 0&&(t=[]);let n=[];return j.Children.forEach(e,(r,a)=>{if(!j.isValidElement(r))return;let i=[...t,a];if(r.type===j.Fragment){n.push.apply(n,gu(r.props.children,i));return}r.type!==ze&<(!1),!r.props.index||!r.props.children||lt(!1);let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=gu(r.props.children,i)),n.push(l)}),n}/** - * React Router DOM v6.30.3 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Wo(){return Wo=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[a]=e[a]);return n}function fw(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function pw(e,t){return e.button===0&&(!t||t==="_self")&&!fw(e)}function yu(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function xw(e,t){let n=yu(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const gw=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],yw=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],vw="6";try{window.__reactRouterVersion=vw}catch{}const jw=j.createContext({isTransitioning:!1}),bw="startTransition",Ip=cj[bw];function Nw(e){let{basename:t,children:n,future:r,window:a}=e,i=j.useRef();i.current==null&&(i.current=bN({window:a,v5Compat:!0}));let l=i.current,[o,c]=j.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=j.useCallback(h=>{d&&Ip?Ip(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>dw(r),[r]),j.createElement(mw,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const ww=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Sw=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,ke=j.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,x=N0(t,gw),{basename:m}=j.useContext(In),f,p=!1;if(typeof d=="string"&&Sw.test(d)&&(f=d,ww))try{let v=new URL(window.location.href),N=d.startsWith("//")?new URL(v.protocol+d):new URL(d),E=Za(N.pathname,m);N.origin===v.origin&&E!=null?d=E+N.search+N.hash:p=!0}catch{}let b=HN(d,{relative:a}),g=Cw(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function y(v){r&&r(v),v.defaultPrevented||g(v)}return j.createElement("a",Wo({},x,{href:f||b,onClick:p||i?r:y,ref:n,target:c}))}),md=j.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=N0(t,yw),x=wc(c,{relative:h.relative}),m=Rn(),f=j.useContext(x0),{navigator:p,basename:b}=j.useContext(In),g=f!=null&&Ew(x)&&d===!0,y=p.encodeLocation?p.encodeLocation(x).pathname:x.pathname,v=m.pathname,N=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;a||(v=v.toLowerCase(),N=N?N.toLowerCase():null,y=y.toLowerCase()),N&&b&&(N=Za(N,b)||N);const E=y!=="/"&&y.endsWith("/")?y.length-1:y.length;let P=v===y||!l&&v.startsWith(y)&&v.charAt(E)==="/",I=N!=null&&(N===y||!l&&N.startsWith(y)&&N.charAt(y.length)==="/"),w={isActive:P,isPending:I,isTransitioning:g},S=P?r:void 0,A;typeof i=="function"?A=i(w):A=[i,P?"active":null,I?"pending":null,g?"transitioning":null].filter(Boolean).join(" ");let O=typeof o=="function"?o(w):o;return j.createElement(ke,Wo({},h,{"aria-current":S,className:A,ref:n,style:O,to:c,viewTransition:d}),typeof u=="function"?u(w):u)});var vu;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(vu||(vu={}));var Rp;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Rp||(Rp={}));function kw(e){let t=j.useContext(jc);return t||lt(!1),t}function Cw(e,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Yt(),d=Rn(),u=wc(e,{relative:l});return j.useCallback(h=>{if(pw(h,n)){h.preventDefault();let x=r!==void 0?r:Ho(d)===Ho(u);c(e,{replace:x,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,e,i,l,o])}function Sc(e){let t=j.useRef(yu(e)),n=j.useRef(!1),r=Rn(),a=j.useMemo(()=>xw(r.search,n.current?null:t.current),[r.search]),i=Yt(),l=j.useCallback((o,c)=>{const d=yu(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function Ew(e,t){t===void 0&&(t={});let n=j.useContext(jw);n==null&<(!1);let{basename:r}=kw(vu.useViewTransitionState),a=wc(e,{relative:t.relative});if(!n.isTransitioning)return!1;let i=Za(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=Za(n.nextLocation.pathname,r)||n.nextLocation.pathname;return xu(a.pathname,l)!=null||xu(a.pathname,i)!=null}var ta=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Dw={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Vn,Xu,Ux,Aw=(Ux=class{constructor(){me(this,Vn,Dw);me(this,Xu,!1)}setTimeoutProvider(e){te(this,Vn,e)}setTimeout(e,t){return M(this,Vn).setTimeout(e,t)}clearTimeout(e){M(this,Vn).clearTimeout(e)}setInterval(e,t){return M(this,Vn).setInterval(e,t)}clearInterval(e){M(this,Vn).clearInterval(e)}},Vn=new WeakMap,Xu=new WeakMap,Ux),Dr=new Aw;function Pw(e){setTimeout(e,0)}var Gr=typeof window>"u"||"Deno"in globalThis;function _t(){}function Mw(e,t){return typeof e=="function"?e(t):e}function ju(e){return typeof e=="number"&&e>=0&&e!==1/0}function w0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function hr(e,t){return typeof e=="function"?e(t):e}function ks(e,t){return typeof e=="function"?e(t):e}function Lp(e,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=e;if(l){if(r){if(t.queryHash!==Zm(l,t.options))return!1}else if(!rl(t.queryKey,l))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function Op(e,t){const{exact:n,status:r,predicate:a,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Zr(t.options.mutationKey)!==Zr(i))return!1}else if(!rl(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function Zm(e,t){return((t==null?void 0:t.queryKeyHashFn)||Zr)(e)}function Zr(e){return JSON.stringify(e,(t,n)=>bu(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function rl(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>rl(e[n],t[n])):!1}var Tw=Object.prototype.hasOwnProperty;function Jm(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=zp(e)&&zp(t);if(!r&&!(bu(e)&&bu(t)))return t;const i=(r?e:Object.keys(e)).length,l=r?t:Object.keys(t),o=l.length,c=r?new Array(o):{};let d=0;for(let u=0;u{Dr.setTimeout(t,e)})}function Nu(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Jm(e,t):t}function Iw(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Rw(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Xm=Symbol();function S0(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Xm?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Ym(e,t){return typeof e=="function"?e(...t):!!e}function Lw(e,t,n){let r=!1,a;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(a??(a=t()),r||(r=!0,a.aborted?n():a.addEventListener("abort",n,{once:!0})),a)}),e}var Mr,Qn,Da,qx,Ow=(qx=class extends ta{constructor(){super();me(this,Mr);me(this,Qn);me(this,Da);te(this,Da,t=>{if(!Gr&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){M(this,Qn)||this.setEventListener(M(this,Da))}onUnsubscribe(){var t;this.hasListeners()||((t=M(this,Qn))==null||t.call(this),te(this,Qn,void 0))}setEventListener(t){var n;te(this,Da,t),(n=M(this,Qn))==null||n.call(this),te(this,Qn,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){M(this,Mr)!==t&&(te(this,Mr,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof M(this,Mr)=="boolean"?M(this,Mr):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Mr=new WeakMap,Qn=new WeakMap,Da=new WeakMap,qx),eh=new Ow;function wu(){let e,t;const n=new Promise((a,i)=>{e=a,t=i});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),e(a)},n.reject=a=>{r({status:"rejected",reason:a}),t(a)},n}var zw=Pw;function $w(){let e=[],t=0,n=o=>{o()},r=o=>{o()},a=zw;const i=o=>{t?e.push(o):a(()=>{n(o)})},l=()=>{const o=e;e=[],o.length&&a(()=>{r(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||l()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{a=o}}}var ht=$w(),Aa,Hn,Pa,Vx,_w=(Vx=class extends ta{constructor(){super();me(this,Aa,!0);me(this,Hn);me(this,Pa);te(this,Pa,t=>{if(!Gr&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){M(this,Hn)||this.setEventListener(M(this,Pa))}onUnsubscribe(){var t;this.hasListeners()||((t=M(this,Hn))==null||t.call(this),te(this,Hn,void 0))}setEventListener(t){var n;te(this,Pa,t),(n=M(this,Hn))==null||n.call(this),te(this,Hn,t(this.setOnline.bind(this)))}setOnline(t){M(this,Aa)!==t&&(te(this,Aa,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return M(this,Aa)}},Aa=new WeakMap,Hn=new WeakMap,Pa=new WeakMap,Vx),Go=new _w;function Kw(e){return Math.min(1e3*2**e,3e4)}function k0(e){return(e??"online")==="online"?Go.isOnline():!0}var Su=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function C0(e){let t=!1,n=0,r;const a=wu(),i=()=>a.status!=="pending",l=p=>{var b;if(!i()){const g=new Su(p);x(g),(b=e.onCancel)==null||b.call(e,g)}},o=()=>{t=!0},c=()=>{t=!1},d=()=>eh.isFocused()&&(e.networkMode==="always"||Go.isOnline())&&e.canRun(),u=()=>k0(e.networkMode)&&e.canRun(),h=p=>{i()||(r==null||r(),a.resolve(p))},x=p=>{i()||(r==null||r(),a.reject(p))},m=()=>new Promise(p=>{var b;r=g=>{(i()||d())&&p(g)},(b=e.onPause)==null||b.call(e)}).then(()=>{var p;r=void 0,i()||(p=e.onContinue)==null||p.call(e)}),f=()=>{if(i())return;let p;const b=n===0?e.initialPromise:void 0;try{p=b??e.fn()}catch(g){p=Promise.reject(g)}Promise.resolve(p).then(h).catch(g=>{var P;if(i())return;const y=e.retry??(Gr?0:3),v=e.retryDelay??Kw,N=typeof v=="function"?v(n,g):v,E=y===!0||typeof y=="number"&&nd()?void 0:m()).then(()=>{t?x(g):f()})})};return{promise:a,status:()=>a.status,cancel:l,continue:()=>(r==null||r(),a),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?f():m().then(f),a)}}var Tr,Qx,E0=(Qx=class{constructor(){me(this,Tr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ju(this.gcTime)&&te(this,Tr,Dr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Gr?1/0:5*60*1e3))}clearGcTimeout(){M(this,Tr)&&(Dr.clearTimeout(M(this,Tr)),te(this,Tr,void 0))}},Tr=new WeakMap,Qx),Fr,Ma,ws,Ir,Ct,ml,Rr,Ls,pn,Hx,Bw=(Hx=class extends E0{constructor(t){super();me(this,Ls);me(this,Fr);me(this,Ma);me(this,ws);me(this,Ir);me(this,Ct);me(this,ml);me(this,Rr);te(this,Rr,!1),te(this,ml,t.defaultOptions),this.setOptions(t.options),this.observers=[],te(this,Ir,t.client),te(this,ws,M(this,Ir).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,te(this,Fr,Kp(this.options)),this.state=t.state??M(this,Fr),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=M(this,Ct))==null?void 0:t.promise}setOptions(t){if(this.options={...M(this,ml),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=Kp(this.options);n.data!==void 0&&(this.setState(_p(n.data,n.dataUpdatedAt)),te(this,Fr,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&M(this,ws).remove(this)}setData(t,n){const r=Nu(this.state.data,t,this.options);return be(this,Ls,pn).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){be(this,Ls,pn).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=M(this,Ct))==null?void 0:r.promise;return(a=M(this,Ct))==null||a.cancel(t),n?n.then(_t).catch(_t):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(M(this,Fr))}isActive(){return this.observers.some(t=>ks(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Xm||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>hr(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!w0(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=M(this,Ct))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=M(this,Ct))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),M(this,ws).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(M(this,Ct)&&(M(this,Rr)?M(this,Ct).cancel({revert:!0}):M(this,Ct).cancelRetry()),this.scheduleGc()),M(this,ws).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||be(this,Ls,pn).call(this,{type:"invalidate"})}async fetch(t,n){var c,d,u,h,x,m,f,p,b,g,y,v;if(this.state.fetchStatus!=="idle"&&((c=M(this,Ct))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(M(this,Ct))return M(this,Ct).continueRetry(),M(this,Ct).promise}if(t&&this.setOptions(t),!this.options.queryFn){const N=this.observers.find(E=>E.options.queryFn);N&&this.setOptions(N.options)}const r=new AbortController,a=N=>{Object.defineProperty(N,"signal",{enumerable:!0,get:()=>(te(this,Rr,!0),r.signal)})},i=()=>{const N=S0(this.options,n),P=(()=>{const I={client:M(this,Ir),queryKey:this.queryKey,meta:this.meta};return a(I),I})();return te(this,Rr,!1),this.options.persister?this.options.persister(N,P,this):N(P)},o=(()=>{const N={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:M(this,Ir),state:this.state,fetchFn:i};return a(N),N})();(d=this.options.behavior)==null||d.onFetch(o,this),te(this,Ma,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&be(this,Ls,pn).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),te(this,Ct,C0({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:N=>{N instanceof Su&&N.revert&&this.setState({...M(this,Ma),fetchStatus:"idle"}),r.abort()},onFail:(N,E)=>{be(this,Ls,pn).call(this,{type:"failed",failureCount:N,error:E})},onPause:()=>{be(this,Ls,pn).call(this,{type:"pause"})},onContinue:()=>{be(this,Ls,pn).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const N=await M(this,Ct).start();if(N===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(N),(m=(x=M(this,ws).config).onSuccess)==null||m.call(x,N,this),(p=(f=M(this,ws).config).onSettled)==null||p.call(f,N,this.state.error,this),N}catch(N){if(N instanceof Su){if(N.silent)return M(this,Ct).promise;if(N.revert){if(this.state.data===void 0)throw N;return this.state.data}}throw be(this,Ls,pn).call(this,{type:"error",error:N}),(g=(b=M(this,ws).config).onError)==null||g.call(b,N,this),(v=(y=M(this,ws).config).onSettled)==null||v.call(y,this.state.data,N,this),N}finally{this.scheduleGc()}}},Fr=new WeakMap,Ma=new WeakMap,ws=new WeakMap,Ir=new WeakMap,Ct=new WeakMap,ml=new WeakMap,Rr=new WeakMap,Ls=new WeakSet,pn=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...D0(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,..._p(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return te(this,Ma,t.manual?a:void 0),a;case"error":const i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),ht.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),M(this,ws).notify({query:this,type:"updated",action:t})})},Hx);function D0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:k0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function _p(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Kp(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var ns,De,hl,Qt,Lr,Ta,vn,Wn,fl,Fa,Ia,Or,zr,Gn,Ra,$e,ki,ku,Cu,Eu,Du,Au,Pu,Mu,A0,Wx,th=(Wx=class extends ta{constructor(t,n){super();me(this,$e);me(this,ns);me(this,De);me(this,hl);me(this,Qt);me(this,Lr);me(this,Ta);me(this,vn);me(this,Wn);me(this,fl);me(this,Fa);me(this,Ia);me(this,Or);me(this,zr);me(this,Gn);me(this,Ra,new Set);this.options=n,te(this,ns,t),te(this,Wn,null),te(this,vn,wu()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(M(this,De).addObserver(this),Bp(M(this,De),this.options)?be(this,$e,ki).call(this):this.updateResult(),be(this,$e,Du).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Tu(M(this,De),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Tu(M(this,De),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,be(this,$e,Au).call(this),be(this,$e,Pu).call(this),M(this,De).removeObserver(this)}setOptions(t){const n=this.options,r=M(this,De);if(this.options=M(this,ns).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ks(this.options.enabled,M(this,De))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");be(this,$e,Mu).call(this),M(this,De).setOptions(this.options),n._defaulted&&!al(this.options,n)&&M(this,ns).getQueryCache().notify({type:"observerOptionsUpdated",query:M(this,De),observer:this});const a=this.hasListeners();a&&Up(M(this,De),r,this.options,n)&&be(this,$e,ki).call(this),this.updateResult(),a&&(M(this,De)!==r||ks(this.options.enabled,M(this,De))!==ks(n.enabled,M(this,De))||hr(this.options.staleTime,M(this,De))!==hr(n.staleTime,M(this,De)))&&be(this,$e,ku).call(this);const i=be(this,$e,Cu).call(this);a&&(M(this,De)!==r||ks(this.options.enabled,M(this,De))!==ks(n.enabled,M(this,De))||i!==M(this,Gn))&&be(this,$e,Eu).call(this,i)}getOptimisticResult(t){const n=M(this,ns).getQueryCache().build(M(this,ns),t),r=this.createResult(n,t);return qw(this,r)&&(te(this,Qt,r),te(this,Ta,this.options),te(this,Lr,M(this,De).state)),r}getCurrentResult(){return M(this,Qt)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),a==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&M(this,vn).status==="pending"&&M(this,vn).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,a))})}trackProp(t){M(this,Ra).add(t)}getCurrentQuery(){return M(this,De)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=M(this,ns).defaultQueryOptions(t),r=M(this,ns).getQueryCache().build(M(this,ns),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return be(this,$e,ki).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),M(this,Qt)))}createResult(t,n){var S;const r=M(this,De),a=this.options,i=M(this,Qt),l=M(this,Lr),o=M(this,Ta),d=t!==r?t.state:M(this,hl),{state:u}=t;let h={...u},x=!1,m;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&Bp(t,n),R=A&&Up(t,r,n,a);(O||R)&&(h={...h,...D0(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:p,status:b}=h;m=h.data;let g=!1;if(n.placeholderData!==void 0&&m===void 0&&b==="pending"){let A;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(A=i.data,g=!0):A=typeof n.placeholderData=="function"?n.placeholderData((S=M(this,Ia))==null?void 0:S.state.data,M(this,Ia)):n.placeholderData,A!==void 0&&(b="success",m=Nu(i==null?void 0:i.data,A,n),x=!0)}if(n.select&&m!==void 0&&!g)if(i&&m===(l==null?void 0:l.data)&&n.select===M(this,fl))m=M(this,Fa);else try{te(this,fl,n.select),m=n.select(m),m=Nu(i==null?void 0:i.data,m,n),te(this,Fa,m),te(this,Wn,null)}catch(A){te(this,Wn,A)}M(this,Wn)&&(f=M(this,Wn),m=M(this,Fa),p=Date.now(),b="error");const y=h.fetchStatus==="fetching",v=b==="pending",N=b==="error",E=v&&y,P=m!==void 0,w={status:b,fetchStatus:h.fetchStatus,isPending:v,isSuccess:b==="success",isError:N,isInitialLoading:E,isLoading:E,data:m,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:y,isRefetching:y&&!v,isLoadingError:N&&!P,isPaused:h.fetchStatus==="paused",isPlaceholderData:x,isRefetchError:N&&P,isStale:sh(t,n),refetch:this.refetch,promise:M(this,vn),isEnabled:ks(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const A=w.data!==void 0,O=w.status==="error"&&!A,R=z=>{O?z.reject(w.error):A&&z.resolve(w.data)},q=()=>{const z=te(this,vn,w.promise=wu());R(z)},D=M(this,vn);switch(D.status){case"pending":t.queryHash===r.queryHash&&R(D);break;case"fulfilled":(O||w.data!==D.value)&&q();break;case"rejected":(!O||w.error!==D.reason)&&q();break}}return w}updateResult(){const t=M(this,Qt),n=this.createResult(M(this,De),this.options);if(te(this,Lr,M(this,De).state),te(this,Ta,this.options),M(this,Lr).data!==void 0&&te(this,Ia,M(this,De)),al(n,t))return;te(this,Qt,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!M(this,Ra).size)return!0;const l=new Set(i??M(this,Ra));return this.options.throwOnError&&l.add("error"),Object.keys(M(this,Qt)).some(o=>{const c=o;return M(this,Qt)[c]!==t[c]&&l.has(c)})};be(this,$e,A0).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&be(this,$e,Du).call(this)}},ns=new WeakMap,De=new WeakMap,hl=new WeakMap,Qt=new WeakMap,Lr=new WeakMap,Ta=new WeakMap,vn=new WeakMap,Wn=new WeakMap,fl=new WeakMap,Fa=new WeakMap,Ia=new WeakMap,Or=new WeakMap,zr=new WeakMap,Gn=new WeakMap,Ra=new WeakMap,$e=new WeakSet,ki=function(t){be(this,$e,Mu).call(this);let n=M(this,De).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(_t)),n},ku=function(){be(this,$e,Au).call(this);const t=hr(this.options.staleTime,M(this,De));if(Gr||M(this,Qt).isStale||!ju(t))return;const r=w0(M(this,Qt).dataUpdatedAt,t)+1;te(this,Or,Dr.setTimeout(()=>{M(this,Qt).isStale||this.updateResult()},r))},Cu=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(M(this,De)):this.options.refetchInterval)??!1},Eu=function(t){be(this,$e,Pu).call(this),te(this,Gn,t),!(Gr||ks(this.options.enabled,M(this,De))===!1||!ju(M(this,Gn))||M(this,Gn)===0)&&te(this,zr,Dr.setInterval(()=>{(this.options.refetchIntervalInBackground||eh.isFocused())&&be(this,$e,ki).call(this)},M(this,Gn)))},Du=function(){be(this,$e,ku).call(this),be(this,$e,Eu).call(this,be(this,$e,Cu).call(this))},Au=function(){M(this,Or)&&(Dr.clearTimeout(M(this,Or)),te(this,Or,void 0))},Pu=function(){M(this,zr)&&(Dr.clearInterval(M(this,zr)),te(this,zr,void 0))},Mu=function(){const t=M(this,ns).getQueryCache().build(M(this,ns),this.options);if(t===M(this,De))return;const n=M(this,De);te(this,De,t),te(this,hl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},A0=function(t){ht.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(M(this,Qt))}),M(this,ns).getQueryCache().notify({query:M(this,De),type:"observerResultsUpdated"})})},Wx);function Uw(e,t){return ks(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Bp(e,t){return Uw(e,t)||e.state.data!==void 0&&Tu(e,t,t.refetchOnMount)}function Tu(e,t,n){if(ks(t.enabled,e)!==!1&&hr(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&sh(e,t)}return!1}function Up(e,t,n,r){return(e!==t||ks(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&sh(e,n)}function sh(e,t){return ks(t.enabled,e)!==!1&&e.isStaleByTime(hr(t.staleTime,e))}function qw(e,t){return!al(e.getCurrentResult(),t)}function qp(e){return{onFetch:(t,n)=>{var u,h,x,m,f;const r=t.options,a=(x=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:x.direction,i=((m=t.state.data)==null?void 0:m.pages)||[],l=((f=t.state.data)==null?void 0:f.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let p=!1;const b=v=>{Lw(v,()=>t.signal,()=>p=!0)},g=S0(t.options,t.fetchOptions),y=async(v,N,E)=>{if(p)return Promise.reject();if(N==null&&v.pages.length)return Promise.resolve(v);const I=(()=>{const O={client:t.client,queryKey:t.queryKey,pageParam:N,direction:E?"backward":"forward",meta:t.options.meta};return b(O),O})(),w=await g(I),{maxPages:S}=t.options,A=E?Rw:Iw;return{pages:A(v.pages,w,S),pageParams:A(v.pageParams,N,S)}};if(a&&i.length){const v=a==="backward",N=v?Vw:Vp,E={pages:i,pageParams:l},P=N(r,E);o=await y(E,P,v)}else{const v=e??i.length;do{const N=c===0?l[0]??r.initialPageParam:Vp(r,o);if(c>0&&N==null)break;o=await y(o,N),c++}while(c{var p,b;return(b=(p=t.options).persister)==null?void 0:b.call(p,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function Vp(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Vw(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var pl,Xs,Ht,$r,Ys,zn,Gx,Qw=(Gx=class extends E0{constructor(t){super();me(this,Ys);me(this,pl);me(this,Xs);me(this,Ht);me(this,$r);te(this,pl,t.client),this.mutationId=t.mutationId,te(this,Ht,t.mutationCache),te(this,Xs,[]),this.state=t.state||P0(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){M(this,Xs).includes(t)||(M(this,Xs).push(t),this.clearGcTimeout(),M(this,Ht).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){te(this,Xs,M(this,Xs).filter(n=>n!==t)),this.scheduleGc(),M(this,Ht).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){M(this,Xs).length||(this.state.status==="pending"?this.scheduleGc():M(this,Ht).remove(this))}continue(){var t;return((t=M(this,$r))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var l,o,c,d,u,h,x,m,f,p,b,g,y,v,N,E,P,I,w,S;const n=()=>{be(this,Ys,zn).call(this,{type:"continue"})},r={client:M(this,pl),meta:this.options.meta,mutationKey:this.options.mutationKey};te(this,$r,C0({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(A,O)=>{be(this,Ys,zn).call(this,{type:"failed",failureCount:A,error:O})},onPause:()=>{be(this,Ys,zn).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>M(this,Ht).canRun(this)}));const a=this.state.status==="pending",i=!M(this,$r).canStart();try{if(a)n();else{be(this,Ys,zn).call(this,{type:"pending",variables:t,isPaused:i}),await((o=(l=M(this,Ht).config).onMutate)==null?void 0:o.call(l,t,this,r));const O=await((d=(c=this.options).onMutate)==null?void 0:d.call(c,t,r));O!==this.state.context&&be(this,Ys,zn).call(this,{type:"pending",context:O,variables:t,isPaused:i})}const A=await M(this,$r).start();return await((h=(u=M(this,Ht).config).onSuccess)==null?void 0:h.call(u,A,t,this.state.context,this,r)),await((m=(x=this.options).onSuccess)==null?void 0:m.call(x,A,t,this.state.context,r)),await((p=(f=M(this,Ht).config).onSettled)==null?void 0:p.call(f,A,null,this.state.variables,this.state.context,this,r)),await((g=(b=this.options).onSettled)==null?void 0:g.call(b,A,null,t,this.state.context,r)),be(this,Ys,zn).call(this,{type:"success",data:A}),A}catch(A){try{await((v=(y=M(this,Ht).config).onError)==null?void 0:v.call(y,A,t,this.state.context,this,r))}catch(O){Promise.reject(O)}try{await((E=(N=this.options).onError)==null?void 0:E.call(N,A,t,this.state.context,r))}catch(O){Promise.reject(O)}try{await((I=(P=M(this,Ht).config).onSettled)==null?void 0:I.call(P,void 0,A,this.state.variables,this.state.context,this,r))}catch(O){Promise.reject(O)}try{await((S=(w=this.options).onSettled)==null?void 0:S.call(w,void 0,A,t,this.state.context,r))}catch(O){Promise.reject(O)}throw be(this,Ys,zn).call(this,{type:"error",error:A}),A}finally{M(this,Ht).runNext(this)}}},pl=new WeakMap,Xs=new WeakMap,Ht=new WeakMap,$r=new WeakMap,Ys=new WeakSet,zn=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),ht.batch(()=>{M(this,Xs).forEach(r=>{r.onMutationUpdate(t)}),M(this,Ht).notify({mutation:this,type:"updated",action:t})})},Gx);function P0(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var jn,Os,xl,Zx,Hw=(Zx=class extends ta{constructor(t={}){super();me(this,jn);me(this,Os);me(this,xl);this.config=t,te(this,jn,new Set),te(this,Os,new Map),te(this,xl,0)}build(t,n,r){const a=new Qw({client:t,mutationCache:this,mutationId:++Ll(this,xl)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){M(this,jn).add(t);const n=eo(t);if(typeof n=="string"){const r=M(this,Os).get(n);r?r.push(t):M(this,Os).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(M(this,jn).delete(t)){const n=eo(t);if(typeof n=="string"){const r=M(this,Os).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&M(this,Os).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=eo(t);if(typeof n=="string"){const r=M(this,Os).get(n),a=r==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r;const n=eo(t);if(typeof n=="string"){const a=(r=M(this,Os).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){ht.batch(()=>{M(this,jn).forEach(t=>{this.notify({type:"removed",mutation:t})}),M(this,jn).clear(),M(this,Os).clear()})}getAll(){return Array.from(M(this,jn))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Op(n,r))}findAll(t={}){return this.getAll().filter(n=>Op(t,n))}notify(t){ht.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return ht.batch(()=>Promise.all(t.map(n=>n.continue().catch(_t))))}},jn=new WeakMap,Os=new WeakMap,xl=new WeakMap,Zx);function eo(e){var t;return(t=e.options.scope)==null?void 0:t.id}var bn,Zn,rs,Nn,En,go,Fu,Jx,Ww=(Jx=class extends ta{constructor(n,r){super();me(this,En);me(this,bn);me(this,Zn);me(this,rs);me(this,Nn);te(this,bn,n),this.setOptions(r),this.bindMethods(),be(this,En,go).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var a;const r=this.options;this.options=M(this,bn).defaultMutationOptions(n),al(this.options,r)||M(this,bn).getMutationCache().notify({type:"observerOptionsUpdated",mutation:M(this,rs),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&Zr(r.mutationKey)!==Zr(this.options.mutationKey)?this.reset():((a=M(this,rs))==null?void 0:a.state.status)==="pending"&&M(this,rs).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=M(this,rs))==null||n.removeObserver(this)}onMutationUpdate(n){be(this,En,go).call(this),be(this,En,Fu).call(this,n)}getCurrentResult(){return M(this,Zn)}reset(){var n;(n=M(this,rs))==null||n.removeObserver(this),te(this,rs,void 0),be(this,En,go).call(this),be(this,En,Fu).call(this)}mutate(n,r){var a;return te(this,Nn,r),(a=M(this,rs))==null||a.removeObserver(this),te(this,rs,M(this,bn).getMutationCache().build(M(this,bn),this.options)),M(this,rs).addObserver(this),M(this,rs).execute(n)}},bn=new WeakMap,Zn=new WeakMap,rs=new WeakMap,Nn=new WeakMap,En=new WeakSet,go=function(){var r;const n=((r=M(this,rs))==null?void 0:r.state)??P0();te(this,Zn,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Fu=function(n){ht.batch(()=>{var r,a,i,l,o,c,d,u;if(M(this,Nn)&&this.hasListeners()){const h=M(this,Zn).variables,x=M(this,Zn).context,m={client:M(this,bn),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(a=(r=M(this,Nn)).onSuccess)==null||a.call(r,n.data,h,x,m)}catch(f){Promise.reject(f)}try{(l=(i=M(this,Nn)).onSettled)==null||l.call(i,n.data,null,h,x,m)}catch(f){Promise.reject(f)}}else if((n==null?void 0:n.type)==="error"){try{(c=(o=M(this,Nn)).onError)==null||c.call(o,n.error,h,x,m)}catch(f){Promise.reject(f)}try{(u=(d=M(this,Nn)).onSettled)==null||u.call(d,void 0,n.error,h,x,m)}catch(f){Promise.reject(f)}}}this.listeners.forEach(h=>{h(M(this,Zn))})})},Jx);function Qp(e,t){const n=new Set(t);return e.filter(r=>!n.has(r))}function Gw(e,t,n){const r=e.slice(0);return r[t]=n,r}var La,fs,Oa,za,Ss,Jn,gl,yl,vl,jl,Ot,Iu,Ru,Lu,Ou,zu,Xx,Zw=(Xx=class extends ta{constructor(t,n,r){super();me(this,Ot);me(this,La);me(this,fs);me(this,Oa);me(this,za);me(this,Ss);me(this,Jn);me(this,gl);me(this,yl);me(this,vl);me(this,jl,[]);te(this,La,t),te(this,za,r),te(this,Oa,[]),te(this,Ss,[]),te(this,fs,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&M(this,Ss).forEach(t=>{t.subscribe(n=>{be(this,Ot,Ou).call(this,t,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,M(this,Ss).forEach(t=>{t.destroy()})}setQueries(t,n){te(this,Oa,t),te(this,za,n),ht.batch(()=>{const r=M(this,Ss),a=be(this,Ot,Lu).call(this,M(this,Oa));a.forEach(h=>h.observer.setOptions(h.defaultedQueryOptions));const i=a.map(h=>h.observer),l=i.map(h=>h.getCurrentResult()),o=r.length!==i.length,c=i.some((h,x)=>h!==r[x]),d=o||c,u=d?!0:l.some((h,x)=>{const m=M(this,fs)[x];return!m||!al(h,m)});!d&&!u||(d&&(te(this,jl,a),te(this,Ss,i)),te(this,fs,l),this.hasListeners()&&(d&&(Qp(r,i).forEach(h=>{h.destroy()}),Qp(i,r).forEach(h=>{h.subscribe(x=>{be(this,Ot,Ou).call(this,h,x)})})),be(this,Ot,zu).call(this)))})}getCurrentResult(){return M(this,fs)}getQueries(){return M(this,Ss).map(t=>t.getCurrentQuery())}getObservers(){return M(this,Ss)}getOptimisticResult(t,n){const r=be(this,Ot,Lu).call(this,t),a=r.map(l=>l.observer.getOptimisticResult(l.defaultedQueryOptions)),i=r.map(l=>l.defaultedQueryOptions.queryHash);return[a,l=>be(this,Ot,Ru).call(this,l??a,n,i),()=>be(this,Ot,Iu).call(this,a,r)]}},La=new WeakMap,fs=new WeakMap,Oa=new WeakMap,za=new WeakMap,Ss=new WeakMap,Jn=new WeakMap,gl=new WeakMap,yl=new WeakMap,vl=new WeakMap,jl=new WeakMap,Ot=new WeakSet,Iu=function(t,n){return n.map((r,a)=>{const i=t[a];return r.defaultedQueryOptions.notifyOnChangeProps?i:r.observer.trackResult(i,l=>{n.forEach(o=>{o.observer.trackProp(l)})})})},Ru=function(t,n,r){if(n){const a=M(this,vl),i=r!==void 0&&a!==void 0&&(a.length!==r.length||r.some((l,o)=>l!==a[o]));return(!M(this,Jn)||M(this,fs)!==M(this,yl)||i||n!==M(this,gl))&&(te(this,gl,n),te(this,yl,M(this,fs)),r!==void 0&&te(this,vl,r),te(this,Jn,Jm(M(this,Jn),n(t)))),M(this,Jn)}return t},Lu=function(t){const n=new Map;M(this,Ss).forEach(a=>{const i=a.options.queryHash;if(!i)return;const l=n.get(i);l?l.push(a):n.set(i,[a])});const r=[];return t.forEach(a=>{var c;const i=M(this,La).defaultQueryOptions(a),o=((c=n.get(i.queryHash))==null?void 0:c.shift())??new th(M(this,La),i);r.push({defaultedQueryOptions:i,observer:o})}),r},Ou=function(t,n){const r=M(this,Ss).indexOf(t);r!==-1&&(te(this,fs,Gw(M(this,fs),r,n)),be(this,Ot,zu).call(this))},zu=function(){var t;if(this.hasListeners()){const n=M(this,Jn),r=be(this,Ot,Iu).call(this,M(this,fs),M(this,jl)),a=be(this,Ot,Ru).call(this,r,(t=M(this,za))==null?void 0:t.combine);n!==a&&ht.batch(()=>{this.listeners.forEach(i=>{i(M(this,fs))})})}},Xx),en,Yx,Jw=(Yx=class extends ta{constructor(t={}){super();me(this,en);this.config=t,te(this,en,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??Zm(a,n);let l=this.get(i);return l||(l=new Bw({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){M(this,en).has(t.queryHash)||(M(this,en).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=M(this,en).get(t.queryHash);n&&(t.destroy(),n===t&&M(this,en).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){ht.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return M(this,en).get(t)}getAll(){return[...M(this,en).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Lp(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Lp(t,r)):n}notify(t){ht.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){ht.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){ht.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},en=new WeakMap,Yx),dt,Xn,Yn,$a,_a,er,Ka,Ba,eg,Xw=(eg=class{constructor(e={}){me(this,dt);me(this,Xn);me(this,Yn);me(this,$a);me(this,_a);me(this,er);me(this,Ka);me(this,Ba);te(this,dt,e.queryCache||new Jw),te(this,Xn,e.mutationCache||new Hw),te(this,Yn,e.defaultOptions||{}),te(this,$a,new Map),te(this,_a,new Map),te(this,er,0)}mount(){Ll(this,er)._++,M(this,er)===1&&(te(this,Ka,eh.subscribe(async e=>{e&&(await this.resumePausedMutations(),M(this,dt).onFocus())})),te(this,Ba,Go.subscribe(async e=>{e&&(await this.resumePausedMutations(),M(this,dt).onOnline())})))}unmount(){var e,t;Ll(this,er)._--,M(this,er)===0&&((e=M(this,Ka))==null||e.call(this),te(this,Ka,void 0),(t=M(this,Ba))==null||t.call(this),te(this,Ba,void 0))}isFetching(e){return M(this,dt).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return M(this,Xn).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=M(this,dt).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=M(this,dt).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(hr(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return M(this,dt).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),a=M(this,dt).get(r.queryHash),i=a==null?void 0:a.state.data,l=Mw(t,i);if(l!==void 0)return M(this,dt).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(e,t,n){return ht.batch(()=>M(this,dt).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=M(this,dt).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=M(this,dt);ht.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=M(this,dt);return ht.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=ht.batch(()=>M(this,dt).findAll(e).map(a=>a.cancel(n)));return Promise.all(r).then(_t).catch(_t)}invalidateQueries(e,t={}){return ht.batch(()=>(M(this,dt).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=ht.batch(()=>M(this,dt).findAll(e).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(_t)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(_t)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=M(this,dt).build(this,t);return n.isStaleByTime(hr(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(_t).catch(_t)}fetchInfiniteQuery(e){return e.behavior=qp(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(_t).catch(_t)}ensureInfiniteQueryData(e){return e.behavior=qp(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Go.isOnline()?M(this,Xn).resumePausedMutations():Promise.resolve()}getQueryCache(){return M(this,dt)}getMutationCache(){return M(this,Xn)}getDefaultOptions(){return M(this,Yn)}setDefaultOptions(e){te(this,Yn,e)}setQueryDefaults(e,t){M(this,$a).set(Zr(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...M(this,$a).values()],n={};return t.forEach(r=>{rl(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){M(this,_a).set(Zr(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...M(this,_a).values()],n={};return t.forEach(r=>{rl(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...M(this,Yn).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zm(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Xm&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...M(this,Yn).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){M(this,dt).clear(),M(this,Xn).clear()}},dt=new WeakMap,Xn=new WeakMap,Yn=new WeakMap,$a=new WeakMap,_a=new WeakMap,er=new WeakMap,Ka=new WeakMap,Ba=new WeakMap,eg),M0=j.createContext(void 0),ge=e=>{const t=j.useContext(M0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Yw=({client:e,children:t})=>(j.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s.jsx(M0.Provider,{value:e,children:t})),T0=j.createContext(!1),F0=()=>j.useContext(T0);T0.Provider;function e1(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var t1=j.createContext(e1()),I0=()=>j.useContext(t1),R0=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?Ym(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},L0=e=>{j.useEffect(()=>{e.clearReset()},[e])},O0=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(a&&e.data===void 0||Ym(n,[e.error,r])),z0=e=>{if(e.suspense){const n=a=>a==="static"?a:Math.max(a??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...a)=>n(r(...a)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},$0=(e,t)=>e.isLoading&&e.isFetching&&!t,$u=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,Zo=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function s1({queries:e,...t},n){const r=ge(),a=F0(),i=I0(),l=j.useMemo(()=>e.map(p=>{const b=r.defaultQueryOptions(p);return b._optimisticResults=a?"isRestoring":"optimistic",b}),[e,r,a]);l.forEach(p=>{z0(p);const b=r.getQueryCache().get(p.queryHash);R0(p,i,b)}),L0(i);const[o]=j.useState(()=>new Zw(r,l,t)),[c,d,u]=o.getOptimisticResult(l,t.combine),h=!a&&t.subscribed!==!1;j.useSyncExternalStore(j.useCallback(p=>h?o.subscribe(ht.batchCalls(p)):_t,[o,h]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),j.useEffect(()=>{o.setQueries(l,t)},[l,t,o]);const m=c.some((p,b)=>$u(l[b],p))?c.flatMap((p,b)=>{const g=l[b];if(g){const y=new th(r,g);if($u(g,p))return Zo(g,y,i);$0(p,a)&&Zo(g,y,i)}return[]}):[];if(m.length>0)throw Promise.all(m);const f=c.find((p,b)=>{const g=l[b];return g&&O0({result:p,errorResetBoundary:i,throwOnError:g.throwOnError,query:r.getQueryCache().get(g.queryHash),suspense:g.suspense})});if(f!=null&&f.error)throw f.error;return d(u())}function n1(e,t,n){var x,m,f,p;const r=F0(),a=I0(),i=ge(),l=i.defaultQueryOptions(e);(m=(x=i.getDefaultOptions().queries)==null?void 0:x._experimental_beforeQuery)==null||m.call(x,l);const o=i.getQueryCache().get(l.queryHash);l._optimisticResults=r?"isRestoring":"optimistic",z0(l),R0(l,a,o),L0(a);const c=!i.getQueryCache().get(l.queryHash),[d]=j.useState(()=>new t(i,l)),u=d.getOptimisticResult(l),h=!r&&e.subscribed!==!1;if(j.useSyncExternalStore(j.useCallback(b=>{const g=h?d.subscribe(ht.batchCalls(b)):_t;return d.updateResult(),g},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),j.useEffect(()=>{d.setOptions(l)},[l,d]),$u(l,u))throw Zo(l,d,a);if(O0({result:u,errorResetBoundary:a,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw u.error;if((p=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||p.call(f,l,u),l.experimental_prefetchInRender&&!Gr&&$0(u,r)){const b=c?Zo(l,d,a):o==null?void 0:o.promise;b==null||b.catch(_t).finally(()=>{d.updateResult()})}return l.notifyOnChangeProps?u:d.trackResult(u)}function fe(e,t){return n1(e,th)}function G(e,t){const n=ge(),[r]=j.useState(()=>new Ww(n,e));j.useEffect(()=>{r.setOptions(e)},[r,e]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(ht.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((l,o)=>{r.mutate(l,o).catch(_t)},[r]);if(a.error&&Ym(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}let r1={data:""},a1=e=>{if(typeof window=="object"){let t=(e?e.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return t.nonce=window.__nonce__,t.parentNode||(e||document.head).appendChild(t),t.firstChild}return e||r1},i1=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,l1=/\/\*[^]*?\*\/| +/g,Hp=/\n+/g,Un=(e,t)=>{let n="",r="",a="";for(let i in e){let l=e[i];i[0]=="@"?i[1]=="i"?n=i+" "+l+";":r+=i[1]=="f"?Un(l,i):i+"{"+Un(l,i[1]=="k"?"":t)+"}":typeof l=="object"?r+=Un(l,t?t.replace(/([^,])+/g,o=>i.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,c=>/&/.test(c)?c.replace(/&/g,o):o?o+" "+c:c)):i):l!=null&&(i=/^--/.test(i)?i:i.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=Un.p?Un.p(i,l):i+":"+l+";")}return n+(t&&a?t+"{"+a+"}":a)+r},hn={},_0=e=>{if(typeof e=="object"){let t="";for(let n in e)t+=n+_0(e[n]);return t}return e},o1=(e,t,n,r,a)=>{let i=_0(e),l=hn[i]||(hn[i]=(c=>{let d=0,u=11;for(;d>>0;return"go"+u})(i));if(!hn[l]){let c=i!==e?e:(d=>{let u,h,x=[{}];for(;u=i1.exec(d.replace(l1,""));)u[4]?x.shift():u[3]?(h=u[3].replace(Hp," ").trim(),x.unshift(x[0][h]=x[0][h]||{})):x[0][u[1]]=u[2].replace(Hp," ").trim();return x[0]})(e);hn[l]=Un(a?{["@keyframes "+l]:c}:c,n?"":"."+l)}let o=n&&hn.g?hn.g:null;return n&&(hn.g=hn[l]),((c,d,u,h)=>{h?d.data=d.data.replace(h,c):d.data.indexOf(c)===-1&&(d.data=u?c+d.data:d.data+c)})(hn[l],t,r,o),l},c1=(e,t,n)=>e.reduce((r,a,i)=>{let l=t[i];if(l&&l.call){let o=l(n),c=o&&o.props&&o.props.className||/^go/.test(o)&&o;l=c?"."+c:o&&typeof o=="object"?o.props?"":Un(o,""):o===!1?"":o}return r+a+(l??"")},"");function kc(e){let t=this||{},n=e.call?e(t.p):e;return o1(n.unshift?n.raw?c1(n,[].slice.call(arguments,1),t.p):n.reduce((r,a)=>Object.assign(r,a&&a.call?a(t.p):a),{}):n,a1(t.target),t.g,t.o,t.k)}let K0,_u,Ku;kc.bind({g:1});let Tn=kc.bind({k:1});function d1(e,t,n,r){Un.p=t,K0=e,_u=n,Ku=r}function jr(e,t){let n=this||{};return function(){let r=arguments;function a(i,l){let o=Object.assign({},i),c=o.className||a.className;n.p=Object.assign({theme:_u&&_u()},o),n.o=/ *go\d+/.test(c),o.className=kc.apply(n,r)+(c?" "+c:"");let d=e;return e[0]&&(d=o.as||e,delete o.as),Ku&&d[0]&&Ku(o),K0(d,o)}return a}}var u1=e=>typeof e=="function",Jo=(e,t)=>u1(e)?e(t):e,m1=(()=>{let e=0;return()=>(++e).toString()})(),B0=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})(),h1=20,nh="default",U0=(e,t)=>{let{toastLimit:n}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,n)};case 1:return{...e,toasts:e.toasts.map(l=>l.id===t.toast.id?{...l,...t.toast}:l)};case 2:let{toast:r}=t;return U0(e,{type:e.toasts.find(l=>l.id===r.id)?1:0,toast:r});case 3:let{toastId:a}=t;return{...e,toasts:e.toasts.map(l=>l.id===a||a===void 0?{...l,dismissed:!0,visible:!1}:l)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(l=>l.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let i=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(l=>({...l,pauseDuration:l.pauseDuration+i}))}}},yo=[],q0={toasts:[],pausedAt:void 0,settings:{toastLimit:h1}},sn={},V0=(e,t=nh)=>{sn[t]=U0(sn[t]||q0,e),yo.forEach(([n,r])=>{n===t&&r(sn[t])})},Q0=e=>Object.keys(sn).forEach(t=>V0(e,t)),f1=e=>Object.keys(sn).find(t=>sn[t].toasts.some(n=>n.id===e)),Cc=(e=nh)=>t=>{V0(t,e)},p1={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},x1=(e={},t=nh)=>{let[n,r]=j.useState(sn[t]||q0),a=j.useRef(sn[t]);j.useEffect(()=>(a.current!==sn[t]&&r(sn[t]),yo.push([t,r]),()=>{let l=yo.findIndex(([o])=>o===t);l>-1&&yo.splice(l,1)}),[t]);let i=n.toasts.map(l=>{var o,c,d;return{...e,...e[l.type],...l,removeDelay:l.removeDelay||((o=e[l.type])==null?void 0:o.removeDelay)||(e==null?void 0:e.removeDelay),duration:l.duration||((c=e[l.type])==null?void 0:c.duration)||(e==null?void 0:e.duration)||p1[l.type],style:{...e.style,...(d=e[l.type])==null?void 0:d.style,...l.style}}});return{...n,toasts:i}},g1=(e,t="blank",n)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...n,id:(n==null?void 0:n.id)||m1()}),Cl=e=>(t,n)=>{let r=g1(t,e,n);return Cc(r.toasterId||f1(r.id))({type:2,toast:r}),r.id},wt=(e,t)=>Cl("blank")(e,t);wt.error=Cl("error");wt.success=Cl("success");wt.loading=Cl("loading");wt.custom=Cl("custom");wt.dismiss=(e,t)=>{let n={type:3,toastId:e};t?Cc(t)(n):Q0(n)};wt.dismissAll=e=>wt.dismiss(void 0,e);wt.remove=(e,t)=>{let n={type:4,toastId:e};t?Cc(t)(n):Q0(n)};wt.removeAll=e=>wt.remove(void 0,e);wt.promise=(e,t,n)=>{let r=wt.loading(t.loading,{...n,...n==null?void 0:n.loading});return typeof e=="function"&&(e=e()),e.then(a=>{let i=t.success?Jo(t.success,a):void 0;return i?wt.success(i,{id:r,...n,...n==null?void 0:n.success}):wt.dismiss(r),a}).catch(a=>{let i=t.error?Jo(t.error,a):void 0;i?wt.error(i,{id:r,...n,...n==null?void 0:n.error}):wt.dismiss(r)}),e};var y1=1e3,v1=(e,t="default")=>{let{toasts:n,pausedAt:r}=x1(e,t),a=j.useRef(new Map).current,i=j.useCallback((h,x=y1)=>{if(a.has(h))return;let m=setTimeout(()=>{a.delete(h),l({type:4,toastId:h})},x);a.set(h,m)},[]);j.useEffect(()=>{if(r)return;let h=Date.now(),x=n.map(m=>{if(m.duration===1/0)return;let f=(m.duration||0)+m.pauseDuration-(h-m.createdAt);if(f<0){m.visible&&wt.dismiss(m.id);return}return setTimeout(()=>wt.dismiss(m.id,t),f)});return()=>{x.forEach(m=>m&&clearTimeout(m))}},[n,r,t]);let l=j.useCallback(Cc(t),[t]),o=j.useCallback(()=>{l({type:5,time:Date.now()})},[l]),c=j.useCallback((h,x)=>{l({type:1,toast:{id:h,height:x}})},[l]),d=j.useCallback(()=>{r&&l({type:6,time:Date.now()})},[r,l]),u=j.useCallback((h,x)=>{let{reverseOrder:m=!1,gutter:f=8,defaultPosition:p}=x||{},b=n.filter(v=>(v.position||p)===(h.position||p)&&v.height),g=b.findIndex(v=>v.id===h.id),y=b.filter((v,N)=>Nv.visible).slice(...m?[y+1]:[0,y]).reduce((v,N)=>v+(N.height||0)+f,0)},[n]);return j.useEffect(()=>{n.forEach(h=>{if(h.dismissed)i(h.id,h.removeDelay);else{let x=a.get(h.id);x&&(clearTimeout(x),a.delete(h.id))}})},[n,i]),{toasts:n,handlers:{updateHeight:c,startPause:o,endPause:d,calculateOffset:u}}},j1=Tn` -from { - transform: scale(0) rotate(45deg); - opacity: 0; -} -to { - transform: scale(1) rotate(45deg); - opacity: 1; -}`,b1=Tn` -from { - transform: scale(0); - opacity: 0; -} -to { - transform: scale(1); - opacity: 1; -}`,N1=Tn` -from { - transform: scale(0) rotate(90deg); - opacity: 0; -} -to { - transform: scale(1) rotate(90deg); - opacity: 1; -}`,w1=jr("div")` - width: 20px; - opacity: 0; - height: 20px; - border-radius: 10px; - background: ${e=>e.primary||"#ff4b4b"}; - position: relative; - transform: rotate(45deg); - - animation: ${j1} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; - animation-delay: 100ms; - - &:after, - &:before { - content: ''; - animation: ${b1} 0.15s ease-out forwards; - animation-delay: 150ms; - position: absolute; - border-radius: 3px; - opacity: 0; - background: ${e=>e.secondary||"#fff"}; - bottom: 9px; - left: 4px; - height: 2px; - width: 12px; - } - - &:before { - animation: ${N1} 0.15s ease-out forwards; - animation-delay: 180ms; - transform: rotate(90deg); - } -`,S1=Tn` - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -`,k1=jr("div")` - width: 12px; - height: 12px; - box-sizing: border-box; - border: 2px solid; - border-radius: 100%; - border-color: ${e=>e.secondary||"#e0e0e0"}; - border-right-color: ${e=>e.primary||"#616161"}; - animation: ${S1} 1s linear infinite; -`,C1=Tn` -from { - transform: scale(0) rotate(45deg); - opacity: 0; -} -to { - transform: scale(1) rotate(45deg); - opacity: 1; -}`,E1=Tn` -0% { - height: 0; - width: 0; - opacity: 0; -} -40% { - height: 0; - width: 6px; - opacity: 1; -} -100% { - opacity: 1; - height: 10px; -}`,D1=jr("div")` - width: 20px; - opacity: 0; - height: 20px; - border-radius: 10px; - background: ${e=>e.primary||"#61d345"}; - position: relative; - transform: rotate(45deg); - - animation: ${C1} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; - animation-delay: 100ms; - &:after { - content: ''; - box-sizing: border-box; - animation: ${E1} 0.2s ease-out forwards; - opacity: 0; - animation-delay: 200ms; - position: absolute; - border-right: 2px solid; - border-bottom: 2px solid; - border-color: ${e=>e.secondary||"#fff"}; - bottom: 6px; - left: 6px; - height: 10px; - width: 6px; - } -`,A1=jr("div")` - position: absolute; -`,P1=jr("div")` - position: relative; - display: flex; - justify-content: center; - align-items: center; - min-width: 20px; - min-height: 20px; -`,M1=Tn` -from { - transform: scale(0.6); - opacity: 0.4; -} -to { - transform: scale(1); - opacity: 1; -}`,T1=jr("div")` - position: relative; - transform: scale(0.6); - opacity: 0.4; - min-width: 20px; - animation: ${M1} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; -`,F1=({toast:e})=>{let{icon:t,type:n,iconTheme:r}=e;return t!==void 0?typeof t=="string"?j.createElement(T1,null,t):t:n==="blank"?null:j.createElement(P1,null,j.createElement(k1,{...r}),n!=="loading"&&j.createElement(A1,null,n==="error"?j.createElement(w1,{...r}):j.createElement(D1,{...r})))},I1=e=>` -0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;} -100% {transform: translate3d(0,0,0) scale(1); opacity:1;} -`,R1=e=>` -0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} -100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;} -`,L1="0%{opacity:0;} 100%{opacity:1;}",O1="0%{opacity:1;} 100%{opacity:0;}",z1=jr("div")` - display: flex; - align-items: center; - background: #fff; - color: #363636; - line-height: 1.3; - will-change: transform; - box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05); - max-width: 350px; - pointer-events: auto; - padding: 8px 10px; - border-radius: 8px; -`,$1=jr("div")` - display: flex; - justify-content: center; - margin: 4px 10px; - color: inherit; - flex: 1 1 auto; - white-space: pre-line; -`,_1=(e,t)=>{let n=e.includes("top")?1:-1,[r,a]=B0()?[L1,O1]:[I1(n),R1(n)];return{animation:t?`${Tn(r)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${Tn(a)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},K1=j.memo(({toast:e,position:t,style:n,children:r})=>{let a=e.height?_1(e.position||t||"top-center",e.visible):{opacity:0},i=j.createElement(F1,{toast:e}),l=j.createElement($1,{...e.ariaProps},Jo(e.message,e));return j.createElement(z1,{className:e.className,style:{...a,...n,...e.style}},typeof r=="function"?r({icon:i,message:l}):j.createElement(j.Fragment,null,i,l))});d1(j.createElement);var B1=({id:e,className:t,style:n,onHeightUpdate:r,children:a})=>{let i=j.useCallback(l=>{if(l){let o=()=>{let c=l.getBoundingClientRect().height;r(e,c)};o(),new MutationObserver(o).observe(l,{subtree:!0,childList:!0,characterData:!0})}},[e,r]);return j.createElement("div",{ref:i,className:t,style:n},a)},U1=(e,t)=>{let n=e.includes("top"),r=n?{top:0}:{bottom:0},a=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:B0()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(n?1:-1)}px)`,...r,...a}},q1=kc` - z-index: 9999; - > * { - pointer-events: auto; - } -`,to=16,V1=({reverseOrder:e,position:t="top-center",toastOptions:n,gutter:r,children:a,toasterId:i,containerStyle:l,containerClassName:o})=>{let{toasts:c,handlers:d}=v1(n,i);return j.createElement("div",{"data-rht-toaster":i||"",style:{position:"fixed",zIndex:9999,top:to,left:to,right:to,bottom:to,pointerEvents:"none",...l},className:o,onMouseEnter:d.startPause,onMouseLeave:d.endPause},c.map(u=>{let h=u.position||t,x=d.calculateOffset(u,{reverseOrder:e,gutter:r,defaultPosition:t}),m=U1(h,x);return j.createElement(B1,{id:u.id,key:u.id,onHeightUpdate:d.updateHeight,className:u.visible?q1:"",style:m},u.type==="custom"?Jo(u.message,u):a?a(u):j.createElement(K1,{toast:u,position:h}))}))},Re=wt;function H0(e,t){return function(){return e.apply(t,arguments)}}const{toString:Q1}=Object.prototype,{getPrototypeOf:rh}=Object,{iterator:Ec,toStringTag:W0}=Symbol,Dc=(e=>t=>{const n=Q1.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Qs=e=>(e=e.toLowerCase(),t=>Dc(t)===e),Ac=e=>t=>typeof t===e,{isArray:ri}=Array,Ja=Ac("undefined");function El(e){return e!==null&&!Ja(e)&&e.constructor!==null&&!Ja(e.constructor)&&us(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const G0=Qs("ArrayBuffer");function H1(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&G0(e.buffer),t}const W1=Ac("string"),us=Ac("function"),Z0=Ac("number"),Dl=e=>e!==null&&typeof e=="object",G1=e=>e===!0||e===!1,vo=e=>{if(Dc(e)!=="object")return!1;const t=rh(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(W0 in e)&&!(Ec in e)},Z1=e=>{if(!Dl(e)||El(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},J1=Qs("Date"),X1=Qs("File"),Y1=Qs("Blob"),e2=Qs("FileList"),t2=e=>Dl(e)&&us(e.pipe),s2=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||us(e.append)&&((t=Dc(e))==="formdata"||t==="object"&&us(e.toString)&&e.toString()==="[object FormData]"))},n2=Qs("URLSearchParams"),[r2,a2,i2,l2]=["ReadableStream","Request","Response","Headers"].map(Qs),o2=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Al(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,a;if(typeof e!="object"&&(e=[e]),ri(e))for(r=0,a=e.length;r0;)if(a=n[r],t===a.toLowerCase())return a;return null}const Ar=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,X0=e=>!Ja(e)&&e!==Ar;function Bu(){const{caseless:e,skipUndefined:t}=X0(this)&&this||{},n={},r=(a,i)=>{const l=e&&J0(n,i)||i;vo(n[l])&&vo(a)?n[l]=Bu(n[l],a):vo(a)?n[l]=Bu({},a):ri(a)?n[l]=a.slice():(!t||!Ja(a))&&(n[l]=a)};for(let a=0,i=arguments.length;a(Al(t,(a,i)=>{n&&us(a)?e[i]=H0(a,n):e[i]=a},{allOwnKeys:r}),e),d2=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),u2=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},m2=(e,t,n,r)=>{let a,i,l;const o={};if(t=t||{},e==null)return t;do{for(a=Object.getOwnPropertyNames(e),i=a.length;i-- >0;)l=a[i],(!r||r(l,e,t))&&!o[l]&&(t[l]=e[l],o[l]=!0);e=n!==!1&&rh(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},h2=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},f2=e=>{if(!e)return null;if(ri(e))return e;let t=e.length;if(!Z0(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},p2=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&rh(Uint8Array)),x2=(e,t)=>{const r=(e&&e[Ec]).call(e);let a;for(;(a=r.next())&&!a.done;){const i=a.value;t.call(e,i[0],i[1])}},g2=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},y2=Qs("HTMLFormElement"),v2=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,a){return r.toUpperCase()+a}),Wp=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),j2=Qs("RegExp"),Y0=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Al(n,(a,i)=>{let l;(l=t(a,i,e))!==!1&&(r[i]=l||a)}),Object.defineProperties(e,r)},b2=e=>{Y0(e,(t,n)=>{if(us(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(us(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},N2=(e,t)=>{const n={},r=a=>{a.forEach(i=>{n[i]=!0})};return ri(e)?r(e):r(String(e).split(t)),n},w2=()=>{},S2=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function k2(e){return!!(e&&us(e.append)&&e[W0]==="FormData"&&e[Ec])}const C2=e=>{const t=new Array(10),n=(r,a)=>{if(Dl(r)){if(t.indexOf(r)>=0)return;if(El(r))return r;if(!("toJSON"in r)){t[a]=r;const i=ri(r)?[]:{};return Al(r,(l,o)=>{const c=n(l,a+1);!Ja(c)&&(i[o]=c)}),t[a]=void 0,i}}return r};return n(e,0)},E2=Qs("AsyncFunction"),D2=e=>e&&(Dl(e)||us(e))&&us(e.then)&&us(e.catch),ev=((e,t)=>e?setImmediate:t?((n,r)=>(Ar.addEventListener("message",({source:a,data:i})=>{a===Ar&&i===n&&r.length&&r.shift()()},!1),a=>{r.push(a),Ar.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",us(Ar.postMessage)),A2=typeof queueMicrotask<"u"?queueMicrotask.bind(Ar):typeof process<"u"&&process.nextTick||ev,P2=e=>e!=null&&us(e[Ec]),V={isArray:ri,isArrayBuffer:G0,isBuffer:El,isFormData:s2,isArrayBufferView:H1,isString:W1,isNumber:Z0,isBoolean:G1,isObject:Dl,isPlainObject:vo,isEmptyObject:Z1,isReadableStream:r2,isRequest:a2,isResponse:i2,isHeaders:l2,isUndefined:Ja,isDate:J1,isFile:X1,isBlob:Y1,isRegExp:j2,isFunction:us,isStream:t2,isURLSearchParams:n2,isTypedArray:p2,isFileList:e2,forEach:Al,merge:Bu,extend:c2,trim:o2,stripBOM:d2,inherits:u2,toFlatObject:m2,kindOf:Dc,kindOfTest:Qs,endsWith:h2,toArray:f2,forEachEntry:x2,matchAll:g2,isHTMLForm:y2,hasOwnProperty:Wp,hasOwnProp:Wp,reduceDescriptors:Y0,freezeMethods:b2,toObjectSet:N2,toCamelCase:v2,noop:w2,toFiniteNumber:S2,findKey:J0,global:Ar,isContextDefined:X0,isSpecCompliantForm:k2,toJSONObject:C2,isAsyncFn:E2,isThenable:D2,setImmediate:ev,asap:A2,isIterable:P2};function Se(e,t,n,r,a){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),a&&(this.response=a,this.status=a.status?a.status:null)}V.inherits(Se,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:V.toJSONObject(this.config),code:this.code,status:this.status}}});const tv=Se.prototype,sv={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sv[e]={value:e}});Object.defineProperties(Se,sv);Object.defineProperty(tv,"isAxiosError",{value:!0});Se.from=(e,t,n,r,a,i)=>{const l=Object.create(tv);V.toFlatObject(e,l,function(u){return u!==Error.prototype},d=>d!=="isAxiosError");const o=e&&e.message?e.message:"Error",c=t==null&&e?e.code:t;return Se.call(l,o,c,n,r,a),e&&l.cause==null&&Object.defineProperty(l,"cause",{value:e,configurable:!0}),l.name=e&&e.name||"Error",i&&Object.assign(l,i),l};const M2=null;function Uu(e){return V.isPlainObject(e)||V.isArray(e)}function nv(e){return V.endsWith(e,"[]")?e.slice(0,-2):e}function Gp(e,t,n){return e?e.concat(t).map(function(a,i){return a=nv(a),!n&&i?"["+a+"]":a}).join(n?".":""):t}function T2(e){return V.isArray(e)&&!e.some(Uu)}const F2=V.toFlatObject(V,{},null,function(t){return/^is[A-Z]/.test(t)});function Pc(e,t,n){if(!V.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=V.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,b){return!V.isUndefined(b[p])});const r=n.metaTokens,a=n.visitor||u,i=n.dots,l=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&V.isSpecCompliantForm(t);if(!V.isFunction(a))throw new TypeError("visitor must be a function");function d(f){if(f===null)return"";if(V.isDate(f))return f.toISOString();if(V.isBoolean(f))return f.toString();if(!c&&V.isBlob(f))throw new Se("Blob is not supported. Use a Buffer instead.");return V.isArrayBuffer(f)||V.isTypedArray(f)?c&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function u(f,p,b){let g=f;if(f&&!b&&typeof f=="object"){if(V.endsWith(p,"{}"))p=r?p:p.slice(0,-2),f=JSON.stringify(f);else if(V.isArray(f)&&T2(f)||(V.isFileList(f)||V.endsWith(p,"[]"))&&(g=V.toArray(f)))return p=nv(p),g.forEach(function(v,N){!(V.isUndefined(v)||v===null)&&t.append(l===!0?Gp([p],N,i):l===null?p:p+"[]",d(v))}),!1}return Uu(f)?!0:(t.append(Gp(b,p,i),d(f)),!1)}const h=[],x=Object.assign(F2,{defaultVisitor:u,convertValue:d,isVisitable:Uu});function m(f,p){if(!V.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+p.join("."));h.push(f),V.forEach(f,function(g,y){(!(V.isUndefined(g)||g===null)&&a.call(t,g,V.isString(y)?y.trim():y,p,x))===!0&&m(g,p?p.concat(y):[y])}),h.pop()}}if(!V.isObject(e))throw new TypeError("data must be an object");return m(e),t}function Zp(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function ah(e,t){this._pairs=[],e&&Pc(e,this,t)}const rv=ah.prototype;rv.append=function(t,n){this._pairs.push([t,n])};rv.toString=function(t){const n=t?function(r){return t.call(this,r,Zp)}:Zp;return this._pairs.map(function(a){return n(a[0])+"="+n(a[1])},"").join("&")};function I2(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function av(e,t,n){if(!t)return e;const r=n&&n.encode||I2;V.isFunction(n)&&(n={serialize:n});const a=n&&n.serialize;let i;if(a?i=a(t,n):i=V.isURLSearchParams(t)?t.toString():new ah(t,n).toString(r),i){const l=e.indexOf("#");l!==-1&&(e=e.slice(0,l)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class Jp{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){V.forEach(this.handlers,function(r){r!==null&&t(r)})}}const iv={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},R2=typeof URLSearchParams<"u"?URLSearchParams:ah,L2=typeof FormData<"u"?FormData:null,O2=typeof Blob<"u"?Blob:null,z2={isBrowser:!0,classes:{URLSearchParams:R2,FormData:L2,Blob:O2},protocols:["http","https","file","blob","url","data"]},ih=typeof window<"u"&&typeof document<"u",qu=typeof navigator=="object"&&navigator||void 0,$2=ih&&(!qu||["ReactNative","NativeScript","NS"].indexOf(qu.product)<0),_2=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",K2=ih&&window.location.href||"http://localhost",B2=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ih,hasStandardBrowserEnv:$2,hasStandardBrowserWebWorkerEnv:_2,navigator:qu,origin:K2},Symbol.toStringTag,{value:"Module"})),Bt={...B2,...z2};function U2(e,t){return Pc(e,new Bt.classes.URLSearchParams,{visitor:function(n,r,a,i){return Bt.isNode&&V.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function q2(e){return V.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function V2(e){const t={},n=Object.keys(e);let r;const a=n.length;let i;for(r=0;r=n.length;return l=!l&&V.isArray(a)?a.length:l,c?(V.hasOwnProp(a,l)?a[l]=[a[l],r]:a[l]=r,!o):((!a[l]||!V.isObject(a[l]))&&(a[l]=[]),t(n,r,a[l],i)&&V.isArray(a[l])&&(a[l]=V2(a[l])),!o)}if(V.isFormData(e)&&V.isFunction(e.entries)){const n={};return V.forEachEntry(e,(r,a)=>{t(q2(r),a,n,0)}),n}return null}function Q2(e,t,n){if(V.isString(e))try{return(t||JSON.parse)(e),V.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const Pl={transitional:iv,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",a=r.indexOf("application/json")>-1,i=V.isObject(t);if(i&&V.isHTMLForm(t)&&(t=new FormData(t)),V.isFormData(t))return a?JSON.stringify(lv(t)):t;if(V.isArrayBuffer(t)||V.isBuffer(t)||V.isStream(t)||V.isFile(t)||V.isBlob(t)||V.isReadableStream(t))return t;if(V.isArrayBufferView(t))return t.buffer;if(V.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let o;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return U2(t,this.formSerializer).toString();if((o=V.isFileList(t))||r.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return Pc(o?{"files[]":t}:t,c&&new c,this.formSerializer)}}return i||a?(n.setContentType("application/json",!1),Q2(t)):t}],transformResponse:[function(t){const n=this.transitional||Pl.transitional,r=n&&n.forcedJSONParsing,a=this.responseType==="json";if(V.isResponse(t)||V.isReadableStream(t))return t;if(t&&V.isString(t)&&(r&&!this.responseType||a)){const l=!(n&&n.silentJSONParsing)&&a;try{return JSON.parse(t,this.parseReviver)}catch(o){if(l)throw o.name==="SyntaxError"?Se.from(o,Se.ERR_BAD_RESPONSE,this,null,this.response):o}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Bt.classes.FormData,Blob:Bt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};V.forEach(["delete","get","head","post","put","patch"],e=>{Pl.headers[e]={}});const H2=V.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),W2=e=>{const t={};let n,r,a;return e&&e.split(` -`).forEach(function(l){a=l.indexOf(":"),n=l.substring(0,a).trim().toLowerCase(),r=l.substring(a+1).trim(),!(!n||t[n]&&H2[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},Xp=Symbol("internals");function vi(e){return e&&String(e).trim().toLowerCase()}function jo(e){return e===!1||e==null?e:V.isArray(e)?e.map(jo):String(e)}function G2(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const Z2=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function hd(e,t,n,r,a){if(V.isFunction(r))return r.call(this,t,n);if(a&&(t=n),!!V.isString(t)){if(V.isString(r))return t.indexOf(r)!==-1;if(V.isRegExp(r))return r.test(t)}}function J2(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function X2(e,t){const n=V.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(a,i,l){return this[r].call(this,t,a,i,l)},configurable:!0})})}let ms=class{constructor(t){t&&this.set(t)}set(t,n,r){const a=this;function i(o,c,d){const u=vi(c);if(!u)throw new Error("header name must be a non-empty string");const h=V.findKey(a,u);(!h||a[h]===void 0||d===!0||d===void 0&&a[h]!==!1)&&(a[h||c]=jo(o))}const l=(o,c)=>V.forEach(o,(d,u)=>i(d,u,c));if(V.isPlainObject(t)||t instanceof this.constructor)l(t,n);else if(V.isString(t)&&(t=t.trim())&&!Z2(t))l(W2(t),n);else if(V.isObject(t)&&V.isIterable(t)){let o={},c,d;for(const u of t){if(!V.isArray(u))throw TypeError("Object iterator must return a key-value pair");o[d=u[0]]=(c=o[d])?V.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}l(o,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=vi(t),t){const r=V.findKey(this,t);if(r){const a=this[r];if(!n)return a;if(n===!0)return G2(a);if(V.isFunction(n))return n.call(this,a,r);if(V.isRegExp(n))return n.exec(a);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=vi(t),t){const r=V.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||hd(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let a=!1;function i(l){if(l=vi(l),l){const o=V.findKey(r,l);o&&(!n||hd(r,r[o],o,n))&&(delete r[o],a=!0)}}return V.isArray(t)?t.forEach(i):i(t),a}clear(t){const n=Object.keys(this);let r=n.length,a=!1;for(;r--;){const i=n[r];(!t||hd(this,this[i],i,t,!0))&&(delete this[i],a=!0)}return a}normalize(t){const n=this,r={};return V.forEach(this,(a,i)=>{const l=V.findKey(r,i);if(l){n[l]=jo(a),delete n[i];return}const o=t?J2(i):String(i).trim();o!==i&&delete n[i],n[o]=jo(a),r[o]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return V.forEach(this,(r,a)=>{r!=null&&r!==!1&&(n[a]=t&&V.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` -`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(a=>r.set(a)),r}static accessor(t){const r=(this[Xp]=this[Xp]={accessors:{}}).accessors,a=this.prototype;function i(l){const o=vi(l);r[o]||(X2(a,l),r[o]=!0)}return V.isArray(t)?t.forEach(i):i(t),this}};ms.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);V.reduceDescriptors(ms.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});V.freezeMethods(ms);function fd(e,t){const n=this||Pl,r=t||n,a=ms.from(r.headers);let i=r.data;return V.forEach(e,function(o){i=o.call(n,i,a.normalize(),t?t.status:void 0)}),a.normalize(),i}function ov(e){return!!(e&&e.__CANCEL__)}function ai(e,t,n){Se.call(this,e??"canceled",Se.ERR_CANCELED,t,n),this.name="CanceledError"}V.inherits(ai,Se,{__CANCEL__:!0});function cv(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Se("Request failed with status code "+n.status,[Se.ERR_BAD_REQUEST,Se.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Y2(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function eS(e,t){e=e||10;const n=new Array(e),r=new Array(e);let a=0,i=0,l;return t=t!==void 0?t:1e3,function(c){const d=Date.now(),u=r[i];l||(l=d),n[a]=c,r[a]=d;let h=i,x=0;for(;h!==a;)x+=n[h++],h=h%e;if(a=(a+1)%e,a===i&&(i=(i+1)%e),d-l{n=u,a=null,i&&(clearTimeout(i),i=null),e(...d)};return[(...d)=>{const u=Date.now(),h=u-n;h>=r?l(d,u):(a=d,i||(i=setTimeout(()=>{i=null,l(a)},r-h)))},()=>a&&l(a)]}const Xo=(e,t,n=3)=>{let r=0;const a=eS(50,250);return tS(i=>{const l=i.loaded,o=i.lengthComputable?i.total:void 0,c=l-r,d=a(c),u=l<=o;r=l;const h={loaded:l,total:o,progress:o?l/o:void 0,bytes:c,rate:d||void 0,estimated:d&&o&&u?(o-l)/d:void 0,event:i,lengthComputable:o!=null,[t?"download":"upload"]:!0};e(h)},n)},Yp=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},ex=e=>(...t)=>V.asap(()=>e(...t)),sS=Bt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Bt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Bt.origin),Bt.navigator&&/(msie|trident)/i.test(Bt.navigator.userAgent)):()=>!0,nS=Bt.hasStandardBrowserEnv?{write(e,t,n,r,a,i,l){if(typeof document>"u")return;const o=[`${e}=${encodeURIComponent(t)}`];V.isNumber(n)&&o.push(`expires=${new Date(n).toUTCString()}`),V.isString(r)&&o.push(`path=${r}`),V.isString(a)&&o.push(`domain=${a}`),i===!0&&o.push("secure"),V.isString(l)&&o.push(`SameSite=${l}`),document.cookie=o.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function rS(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function aS(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function dv(e,t,n){let r=!rS(t);return e&&(r||n==!1)?aS(e,t):t}const tx=e=>e instanceof ms?{...e}:e;function Jr(e,t){t=t||{};const n={};function r(d,u,h,x){return V.isPlainObject(d)&&V.isPlainObject(u)?V.merge.call({caseless:x},d,u):V.isPlainObject(u)?V.merge({},u):V.isArray(u)?u.slice():u}function a(d,u,h,x){if(V.isUndefined(u)){if(!V.isUndefined(d))return r(void 0,d,h,x)}else return r(d,u,h,x)}function i(d,u){if(!V.isUndefined(u))return r(void 0,u)}function l(d,u){if(V.isUndefined(u)){if(!V.isUndefined(d))return r(void 0,d)}else return r(void 0,u)}function o(d,u,h){if(h in t)return r(d,u);if(h in e)return r(void 0,d)}const c={url:i,method:i,data:i,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:o,headers:(d,u,h)=>a(tx(d),tx(u),h,!0)};return V.forEach(Object.keys({...e,...t}),function(u){const h=c[u]||a,x=h(e[u],t[u],u);V.isUndefined(x)&&h!==o||(n[u]=x)}),n}const uv=e=>{const t=Jr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:a,xsrfCookieName:i,headers:l,auth:o}=t;if(t.headers=l=ms.from(l),t.url=av(dv(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),o&&l.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),V.isFormData(n)){if(Bt.hasStandardBrowserEnv||Bt.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if(V.isFunction(n.getHeaders)){const c=n.getHeaders(),d=["content-type","content-length"];Object.entries(c).forEach(([u,h])=>{d.includes(u.toLowerCase())&&l.set(u,h)})}}if(Bt.hasStandardBrowserEnv&&(r&&V.isFunction(r)&&(r=r(t)),r||r!==!1&&sS(t.url))){const c=a&&i&&nS.read(i);c&&l.set(a,c)}return t},iS=typeof XMLHttpRequest<"u",lS=iS&&function(e){return new Promise(function(n,r){const a=uv(e);let i=a.data;const l=ms.from(a.headers).normalize();let{responseType:o,onUploadProgress:c,onDownloadProgress:d}=a,u,h,x,m,f;function p(){m&&m(),f&&f(),a.cancelToken&&a.cancelToken.unsubscribe(u),a.signal&&a.signal.removeEventListener("abort",u)}let b=new XMLHttpRequest;b.open(a.method.toUpperCase(),a.url,!0),b.timeout=a.timeout;function g(){if(!b)return;const v=ms.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),E={data:!o||o==="text"||o==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:v,config:e,request:b};cv(function(I){n(I),p()},function(I){r(I),p()},E),b=null}"onloadend"in b?b.onloadend=g:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(g)},b.onabort=function(){b&&(r(new Se("Request aborted",Se.ECONNABORTED,e,b)),b=null)},b.onerror=function(N){const E=N&&N.message?N.message:"Network Error",P=new Se(E,Se.ERR_NETWORK,e,b);P.event=N||null,r(P),b=null},b.ontimeout=function(){let N=a.timeout?"timeout of "+a.timeout+"ms exceeded":"timeout exceeded";const E=a.transitional||iv;a.timeoutErrorMessage&&(N=a.timeoutErrorMessage),r(new Se(N,E.clarifyTimeoutError?Se.ETIMEDOUT:Se.ECONNABORTED,e,b)),b=null},i===void 0&&l.setContentType(null),"setRequestHeader"in b&&V.forEach(l.toJSON(),function(N,E){b.setRequestHeader(E,N)}),V.isUndefined(a.withCredentials)||(b.withCredentials=!!a.withCredentials),o&&o!=="json"&&(b.responseType=a.responseType),d&&([x,f]=Xo(d,!0),b.addEventListener("progress",x)),c&&b.upload&&([h,m]=Xo(c),b.upload.addEventListener("progress",h),b.upload.addEventListener("loadend",m)),(a.cancelToken||a.signal)&&(u=v=>{b&&(r(!v||v.type?new ai(null,e,b):v),b.abort(),b=null)},a.cancelToken&&a.cancelToken.subscribe(u),a.signal&&(a.signal.aborted?u():a.signal.addEventListener("abort",u)));const y=Y2(a.url);if(y&&Bt.protocols.indexOf(y)===-1){r(new Se("Unsupported protocol "+y+":",Se.ERR_BAD_REQUEST,e));return}b.send(i||null)})},oS=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,a;const i=function(d){if(!a){a=!0,o();const u=d instanceof Error?d:this.reason;r.abort(u instanceof Se?u:new ai(u instanceof Error?u.message:u))}};let l=t&&setTimeout(()=>{l=null,i(new Se(`timeout ${t} of ms exceeded`,Se.ETIMEDOUT))},t);const o=()=>{e&&(l&&clearTimeout(l),l=null,e.forEach(d=>{d.unsubscribe?d.unsubscribe(i):d.removeEventListener("abort",i)}),e=null)};e.forEach(d=>d.addEventListener("abort",i));const{signal:c}=r;return c.unsubscribe=()=>V.asap(o),c}},cS=function*(e,t){let n=e.byteLength;if(n{const a=dS(e,t);let i=0,l,o=c=>{l||(l=!0,r&&r(c))};return new ReadableStream({async pull(c){try{const{done:d,value:u}=await a.next();if(d){o(),c.close();return}let h=u.byteLength;if(n){let x=i+=h;n(x)}c.enqueue(new Uint8Array(u))}catch(d){throw o(d),d}},cancel(c){return o(c),a.return()}},{highWaterMark:2})},nx=64*1024,{isFunction:so}=V,mS=(({Request:e,Response:t})=>({Request:e,Response:t}))(V.global),{ReadableStream:rx,TextEncoder:ax}=V.global,ix=(e,...t)=>{try{return!!e(...t)}catch{return!1}},hS=e=>{e=V.merge.call({skipUndefined:!0},mS,e);const{fetch:t,Request:n,Response:r}=e,a=t?so(t):typeof fetch=="function",i=so(n),l=so(r);if(!a)return!1;const o=a&&so(rx),c=a&&(typeof ax=="function"?(f=>p=>f.encode(p))(new ax):async f=>new Uint8Array(await new n(f).arrayBuffer())),d=i&&o&&ix(()=>{let f=!1;const p=new n(Bt.origin,{body:new rx,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!p}),u=l&&o&&ix(()=>V.isReadableStream(new r("").body)),h={stream:u&&(f=>f.body)};a&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(p,b)=>{let g=p&&p[f];if(g)return g.call(p);throw new Se(`Response type '${f}' is not supported`,Se.ERR_NOT_SUPPORT,b)})});const x=async f=>{if(f==null)return 0;if(V.isBlob(f))return f.size;if(V.isSpecCompliantForm(f))return(await new n(Bt.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(V.isArrayBufferView(f)||V.isArrayBuffer(f))return f.byteLength;if(V.isURLSearchParams(f)&&(f=f+""),V.isString(f))return(await c(f)).byteLength},m=async(f,p)=>{const b=V.toFiniteNumber(f.getContentLength());return b??x(p)};return async f=>{let{url:p,method:b,data:g,signal:y,cancelToken:v,timeout:N,onDownloadProgress:E,onUploadProgress:P,responseType:I,headers:w,withCredentials:S="same-origin",fetchOptions:A}=uv(f),O=t||fetch;I=I?(I+"").toLowerCase():"text";let R=oS([y,v&&v.toAbortSignal()],N),q=null;const D=R&&R.unsubscribe&&(()=>{R.unsubscribe()});let z;try{if(P&&d&&b!=="get"&&b!=="head"&&(z=await m(w,g))!==0){let le=new n(p,{method:"POST",body:g,duplex:"half"}),de;if(V.isFormData(g)&&(de=le.headers.get("content-type"))&&w.setContentType(de),le.body){const[Ke,Ve]=Yp(z,Xo(ex(P)));g=sx(le.body,nx,Ke,Ve)}}V.isString(S)||(S=S?"include":"omit");const k=i&&"credentials"in n.prototype,K={...A,signal:R,method:b.toUpperCase(),headers:w.normalize().toJSON(),body:g,duplex:"half",credentials:k?S:void 0};q=i&&new n(p,K);let B=await(i?O(q,A):O(p,K));const _=u&&(I==="stream"||I==="response");if(u&&(E||_&&D)){const le={};["status","statusText","headers"].forEach(st=>{le[st]=B[st]});const de=V.toFiniteNumber(B.headers.get("content-length")),[Ke,Ve]=E&&Yp(de,Xo(ex(E),!0))||[];B=new r(sx(B.body,nx,Ke,()=>{Ve&&Ve(),D&&D()}),le)}I=I||"text";let Q=await h[V.findKey(h,I)||"text"](B,f);return!_&&D&&D(),await new Promise((le,de)=>{cv(le,de,{data:Q,headers:ms.from(B.headers),status:B.status,statusText:B.statusText,config:f,request:q})})}catch(k){throw D&&D(),k&&k.name==="TypeError"&&/Load failed|fetch/i.test(k.message)?Object.assign(new Se("Network Error",Se.ERR_NETWORK,f,q),{cause:k.cause||k}):Se.from(k,k&&k.code,f,q)}}},fS=new Map,mv=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:a}=t,i=[r,a,n];let l=i.length,o=l,c,d,u=fS;for(;o--;)c=i[o],d=u.get(c),d===void 0&&u.set(c,d=o?new Map:hS(t)),u=d;return d};mv();const lh={http:M2,xhr:lS,fetch:{get:mv}};V.forEach(lh,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const lx=e=>`- ${e}`,pS=e=>V.isFunction(e)||e===null||e===!1;function xS(e,t){e=V.isArray(e)?e:[e];const{length:n}=e;let r,a;const i={};for(let l=0;l`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let o=n?l.length>1?`since : -`+l.map(lx).join(` -`):" "+lx(l[0]):"as no adapter specified";throw new Se("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return a}const hv={getAdapter:xS,adapters:lh};function pd(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ai(null,e)}function ox(e){return pd(e),e.headers=ms.from(e.headers),e.data=fd.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hv.getAdapter(e.adapter||Pl.adapter,e)(e).then(function(r){return pd(e),r.data=fd.call(e,e.transformResponse,r),r.headers=ms.from(r.headers),r},function(r){return ov(r)||(pd(e),r&&r.response&&(r.response.data=fd.call(e,e.transformResponse,r.response),r.response.headers=ms.from(r.response.headers))),Promise.reject(r)})}const fv="1.13.2",Mc={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Mc[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const cx={};Mc.transitional=function(t,n,r){function a(i,l){return"[Axios v"+fv+"] Transitional option '"+i+"'"+l+(r?". "+r:"")}return(i,l,o)=>{if(t===!1)throw new Se(a(l," has been removed"+(n?" in "+n:"")),Se.ERR_DEPRECATED);return n&&!cx[l]&&(cx[l]=!0,console.warn(a(l," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,l,o):!0}};Mc.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function gS(e,t,n){if(typeof e!="object")throw new Se("options must be an object",Se.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let a=r.length;for(;a-- >0;){const i=r[a],l=t[i];if(l){const o=e[i],c=o===void 0||l(o,i,e);if(c!==!0)throw new Se("option "+i+" must be "+c,Se.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Se("Unknown option "+i,Se.ERR_BAD_OPTION)}}const bo={assertOptions:gS,validators:Mc},Gs=bo.validators;let Br=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Jp,response:new Jp}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let a={};Error.captureStackTrace?Error.captureStackTrace(a):a=new Error;const i=a.stack?a.stack.replace(/^.+\n/,""):"";try{r.stack?i&&!String(r.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(r.stack+=` -`+i):r.stack=i}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jr(this.defaults,n);const{transitional:r,paramsSerializer:a,headers:i}=n;r!==void 0&&bo.assertOptions(r,{silentJSONParsing:Gs.transitional(Gs.boolean),forcedJSONParsing:Gs.transitional(Gs.boolean),clarifyTimeoutError:Gs.transitional(Gs.boolean)},!1),a!=null&&(V.isFunction(a)?n.paramsSerializer={serialize:a}:bo.assertOptions(a,{encode:Gs.function,serialize:Gs.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),bo.assertOptions(n,{baseUrl:Gs.spelling("baseURL"),withXsrfToken:Gs.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let l=i&&V.merge(i.common,i[n.method]);i&&V.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),n.headers=ms.concat(l,i);const o=[];let c=!0;this.interceptors.request.forEach(function(p){typeof p.runWhen=="function"&&p.runWhen(n)===!1||(c=c&&p.synchronous,o.unshift(p.fulfilled,p.rejected))});const d=[];this.interceptors.response.forEach(function(p){d.push(p.fulfilled,p.rejected)});let u,h=0,x;if(!c){const f=[ox.bind(this),void 0];for(f.unshift(...o),f.push(...d),x=f.length,u=Promise.resolve(n);h{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](a);r._listeners=null}),this.promise.then=a=>{let i;const l=new Promise(o=>{r.subscribe(o),i=o}).then(a);return l.cancel=function(){r.unsubscribe(i)},l},t(function(i,l,o){r.reason||(r.reason=new ai(i,l,o),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new pv(function(a){t=a}),cancel:t}}};function vS(e){return function(n){return e.apply(null,n)}}function jS(e){return V.isObject(e)&&e.isAxiosError===!0}const Vu={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Vu).forEach(([e,t])=>{Vu[t]=e});function xv(e){const t=new Br(e),n=H0(Br.prototype.request,t);return V.extend(n,Br.prototype,t,{allOwnKeys:!0}),V.extend(n,t,null,{allOwnKeys:!0}),n.create=function(a){return xv(Jr(e,a))},n}const pt=xv(Pl);pt.Axios=Br;pt.CanceledError=ai;pt.CancelToken=yS;pt.isCancel=ov;pt.VERSION=fv;pt.toFormData=Pc;pt.AxiosError=Se;pt.Cancel=pt.CanceledError;pt.all=function(t){return Promise.all(t)};pt.spread=vS;pt.isAxiosError=jS;pt.mergeConfig=Jr;pt.AxiosHeaders=ms;pt.formToJSON=e=>lv(V.isHTMLForm(e)?new FormData(e):e);pt.getAdapter=hv.getAdapter;pt.HttpStatusCode=Vu;pt.default=pt;const{Axios:y4,AxiosError:v4,CanceledError:j4,isCancel:b4,CancelToken:N4,VERSION:w4,all:S4,Cancel:k4,isAxiosError:C4,spread:E4,toFormData:D4,AxiosHeaders:A4,HttpStatusCode:P4,formToJSON:M4,getAdapter:T4,mergeConfig:F4}=pt,$=pt.create({baseURL:"/api",headers:{"Content-Type":"application/json"}});$.interceptors.request.use(e=>{const t=localStorage.getItem("token");return t&&(e.headers.Authorization=`Bearer ${t}`),e});$.interceptors.response.use(e=>e,e=>{var a,i,l,o,c,d,u;const t=((i=(a=e.config)==null?void 0:a.url)==null?void 0:i.includes("/auth/login"))||((o=(l=e.config)==null?void 0:l.url)==null?void 0:o.includes("/auth/customer-login"));((c=e.response)==null?void 0:c.status)===401&&!t&&(localStorage.removeItem("token"),localStorage.removeItem("user"),window.location.href="/login");const n=((u=(d=e.response)==null?void 0:d.data)==null?void 0:u.error)||e.message||"Ein Fehler ist aufgetreten",r=new Error(n);return Promise.reject(r)});const no={login:async(e,t)=>(await $.post("/auth/login",{email:e,password:t})).data,customerLogin:async(e,t)=>(await $.post("/auth/customer-login",{email:e,password:t})).data,me:async()=>(await $.get("/auth/me")).data},At={getAll:async e=>(await $.get("/customers",{params:e})).data,getById:async e=>(await $.get(`/customers/${e}`)).data,create:async e=>(await $.post("/customers",e)).data,update:async(e,t)=>(await $.put(`/customers/${e}`,t)).data,delete:async e=>(await $.delete(`/customers/${e}`)).data,getPortalSettings:async e=>(await $.get(`/customers/${e}/portal`)).data,updatePortalSettings:async(e,t)=>(await $.put(`/customers/${e}/portal`,t)).data,setPortalPassword:async(e,t)=>(await $.post(`/customers/${e}/portal/password`,{password:t})).data,getPortalPassword:async e=>(await $.get(`/customers/${e}/portal/password`)).data,getRepresentatives:async e=>(await $.get(`/customers/${e}/representatives`)).data,addRepresentative:async(e,t,n)=>(await $.post(`/customers/${e}/representatives`,{representativeId:t,notes:n})).data,removeRepresentative:async(e,t)=>(await $.delete(`/customers/${e}/representatives/${t}`)).data,searchForRepresentative:async(e,t)=>(await $.get(`/customers/${e}/representatives/search`,{params:{search:t}})).data},Qu={getByCustomer:async e=>(await $.get(`/customers/${e}/addresses`)).data,create:async(e,t)=>(await $.post(`/customers/${e}/addresses`,t)).data,update:async(e,t)=>(await $.put(`/addresses/${e}`,t)).data,delete:async e=>(await $.delete(`/addresses/${e}`)).data},Yo={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/bank-cards`,{params:{showInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/bank-cards`,t)).data,update:async(e,t)=>(await $.put(`/bank-cards/${e}`,t)).data,delete:async e=>(await $.delete(`/bank-cards/${e}`)).data},ec={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/documents`,{params:{showInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/documents`,t)).data,update:async(e,t)=>(await $.put(`/documents/${e}`,t)).data,delete:async e=>(await $.delete(`/documents/${e}`)).data},ln={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/meters`,{params:{showInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/meters`,t)).data,update:async(e,t)=>(await $.put(`/meters/${e}`,t)).data,delete:async e=>(await $.delete(`/meters/${e}`)).data,getReadings:async e=>(await $.get(`/meters/${e}/readings`)).data,addReading:async(e,t)=>(await $.post(`/meters/${e}/readings`,t)).data,updateReading:async(e,t,n)=>(await $.put(`/meters/${e}/readings/${t}`,n)).data,deleteReading:async(e,t)=>(await $.delete(`/meters/${e}/readings/${t}`)).data},aa={getInvoices:async e=>(await $.get(`/energy-details/${e}/invoices`)).data,addInvoice:async(e,t)=>(await $.post(`/energy-details/${e}/invoices`,t)).data,updateInvoice:async(e,t,n)=>(await $.put(`/energy-details/${e}/invoices/${t}`,n)).data,deleteInvoice:async(e,t)=>(await $.delete(`/energy-details/${e}/invoices/${t}`)).data,uploadDocument:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/invoices/${e}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteDocument:async e=>(await $.delete(`/upload/invoices/${e}`)).data},xs={getByCustomer:async(e,t=!1)=>(await $.get(`/customers/${e}/stressfrei-emails`,{params:{includeInactive:t}})).data,create:async(e,t)=>(await $.post(`/customers/${e}/stressfrei-emails`,t)).data,update:async(e,t)=>(await $.put(`/stressfrei-emails/${e}`,t)).data,delete:async e=>(await $.delete(`/stressfrei-emails/${e}`)).data,enableMailbox:async e=>(await $.post(`/stressfrei-emails/${e}/enable-mailbox`)).data,syncMailboxStatus:async e=>(await $.post(`/stressfrei-emails/${e}/sync-mailbox-status`)).data,getMailboxCredentials:async e=>(await $.get(`/stressfrei-emails/${e}/credentials`)).data,resetPassword:async e=>(await $.post(`/stressfrei-emails/${e}/reset-password`)).data,syncEmails:async(e,t=!1)=>(await $.post(`/stressfrei-emails/${e}/sync`,{},{params:{full:t}})).data,sendEmail:async(e,t)=>(await $.post(`/stressfrei-emails/${e}/send`,t)).data,getFolderCounts:async e=>(await $.get(`/stressfrei-emails/${e}/folder-counts`)).data},Pe={getForCustomer:async(e,t)=>(await $.get(`/customers/${e}/emails`,{params:t})).data,getForContract:async(e,t)=>(await $.get(`/contracts/${e}/emails`,{params:t})).data,getContractFolderCounts:async e=>(await $.get(`/contracts/${e}/emails/folder-counts`)).data,getMailboxAccounts:async e=>(await $.get(`/customers/${e}/mailbox-accounts`)).data,getById:async e=>(await $.get(`/emails/${e}`)).data,getThread:async e=>(await $.get(`/emails/${e}/thread`)).data,markAsRead:async(e,t)=>(await $.patch(`/emails/${e}/read`,{isRead:t})).data,toggleStar:async e=>(await $.post(`/emails/${e}/star`)).data,assignToContract:async(e,t)=>(await $.post(`/emails/${e}/assign`,{contractId:t})).data,unassignFromContract:async e=>(await $.delete(`/emails/${e}/assign`)).data,delete:async e=>(await $.delete(`/emails/${e}`)).data,getAttachmentUrl:(e,t,n)=>{const r=localStorage.getItem("token"),a=encodeURIComponent(t),i=n?"&view=true":"";return`${$.defaults.baseURL}/emails/${e}/attachments/${a}?token=${r}${i}`},getUnreadCount:async e=>(await $.get("/emails/unread-count",{params:e})).data,getTrash:async e=>(await $.get(`/customers/${e}/emails/trash`)).data,getTrashCount:async e=>(await $.get(`/customers/${e}/emails/trash/count`)).data,restore:async e=>(await $.post(`/emails/${e}/restore`)).data,permanentDelete:async e=>(await $.delete(`/emails/${e}/permanent`)).data,getAttachmentTargets:async e=>(await $.get(`/emails/${e}/attachment-targets`)).data,saveAttachmentTo:async(e,t,n)=>{const r=encodeURIComponent(t);return(await $.post(`/emails/${e}/attachments/${r}/save-to`,n)).data},saveEmailAsPdf:async(e,t)=>(await $.post(`/emails/${e}/save-as-pdf`,t)).data,saveEmailAsInvoice:async(e,t)=>(await $.post(`/emails/${e}/save-as-invoice`,t)).data,saveAttachmentAsInvoice:async(e,t,n)=>{const r=encodeURIComponent(t);return(await $.post(`/emails/${e}/attachments/${r}/save-as-invoice`,n)).data}},Oe={getAll:async e=>(await $.get("/contracts",{params:e})).data,getTreeForCustomer:async e=>(await $.get("/contracts",{params:{customerId:e,tree:"true"}})).data,getById:async e=>(await $.get(`/contracts/${e}`)).data,create:async e=>(await $.post("/contracts",e)).data,update:async(e,t)=>(await $.put(`/contracts/${e}`,t)).data,delete:async e=>(await $.delete(`/contracts/${e}`)).data,createFollowUp:async e=>(await $.post(`/contracts/${e}/follow-up`)).data,getPassword:async e=>(await $.get(`/contracts/${e}/password`)).data,getSimCardCredentials:async e=>(await $.get(`/contracts/simcard/${e}/credentials`)).data,getInternetCredentials:async e=>(await $.get(`/contracts/${e}/internet-credentials`)).data,getSipCredentials:async e=>(await $.get(`/contracts/phonenumber/${e}/sip-credentials`)).data,getCockpit:async()=>(await $.get("/contracts/cockpit")).data,snooze:async(e,t)=>(await $.patch(`/contracts/${e}/snooze`,t)).data},tc={getByContract:async e=>(await $.get(`/contracts/${e}/history`)).data,create:async(e,t)=>(await $.post(`/contracts/${e}/history`,t)).data,update:async(e,t,n)=>(await $.put(`/contracts/${e}/history/${t}`,n)).data,delete:async(e,t)=>(await $.delete(`/contracts/${e}/history/${t}`)).data},et={getAll:async e=>(await $.get("/tasks",{params:e})).data,getStats:async()=>(await $.get("/tasks/stats")).data,getByContract:async(e,t)=>(await $.get(`/contracts/${e}/tasks`,{params:{status:t}})).data,create:async(e,t)=>(await $.post(`/contracts/${e}/tasks`,t)).data,update:async(e,t)=>(await $.put(`/tasks/${e}`,t)).data,complete:async e=>(await $.post(`/tasks/${e}/complete`)).data,reopen:async e=>(await $.post(`/tasks/${e}/reopen`)).data,delete:async e=>(await $.delete(`/tasks/${e}`)).data,createSubtask:async(e,t)=>(await $.post(`/tasks/${e}/subtasks`,{title:t})).data,createReply:async(e,t)=>(await $.post(`/tasks/${e}/reply`,{title:t})).data,updateSubtask:async(e,t)=>(await $.put(`/subtasks/${e}`,{title:t})).data,completeSubtask:async e=>(await $.post(`/subtasks/${e}/complete`)).data,reopenSubtask:async e=>(await $.post(`/subtasks/${e}/reopen`)).data,deleteSubtask:async e=>(await $.delete(`/subtasks/${e}`)).data,createSupportTicket:async(e,t)=>(await $.post(`/contracts/${e}/support-ticket`,t)).data},Xr={getPublic:async()=>(await $.get("/settings/public")).data,getAll:async()=>(await $.get("/settings")).data,update:async e=>(await $.put("/settings",e)).data,updateOne:async(e,t)=>(await $.put(`/settings/${e}`,{value:t})).data},br={list:async()=>(await $.get("/settings/backups")).data,create:async()=>(await $.post("/settings/backup")).data,restore:async e=>(await $.post(`/settings/backup/${e}/restore`)).data,delete:async e=>(await $.delete(`/settings/backup/${e}`)).data,getDownloadUrl:e=>`/api/settings/backup/${e}/download`,upload:async e=>{const t=new FormData;return t.append("backup",e),(await $.post("/settings/backup/upload",t,{headers:{"Content-Type":"multipart/form-data"}})).data},factoryReset:async()=>(await $.post("/settings/factory-reset")).data},il={getAll:async(e=!1)=>(await $.get("/platforms",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/platforms/${e}`)).data,create:async e=>(await $.post("/platforms",e)).data,update:async(e,t)=>(await $.put(`/platforms/${e}`,t)).data,delete:async e=>(await $.delete(`/platforms/${e}`)).data},ll={getAll:async(e=!1)=>(await $.get("/cancellation-periods",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/cancellation-periods/${e}`)).data,create:async e=>(await $.post("/cancellation-periods",e)).data,update:async(e,t)=>(await $.put(`/cancellation-periods/${e}`,t)).data,delete:async e=>(await $.delete(`/cancellation-periods/${e}`)).data},ol={getAll:async(e=!1)=>(await $.get("/contract-durations",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/contract-durations/${e}`)).data,create:async e=>(await $.post("/contract-durations",e)).data,update:async(e,t)=>(await $.put(`/contract-durations/${e}`,t)).data,delete:async e=>(await $.delete(`/contract-durations/${e}`)).data},cl={getAll:async(e=!1)=>(await $.get("/contract-categories",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/contract-categories/${e}`)).data,create:async e=>(await $.post("/contract-categories",e)).data,update:async(e,t)=>(await $.put(`/contract-categories/${e}`,t)).data,delete:async e=>(await $.delete(`/contract-categories/${e}`)).data},Xa={getAll:async(e=!1)=>(await $.get("/providers",{params:{includeInactive:e}})).data,getById:async e=>(await $.get(`/providers/${e}`)).data,create:async e=>(await $.post("/providers",e)).data,update:async(e,t)=>(await $.put(`/providers/${e}`,t)).data,delete:async e=>(await $.delete(`/providers/${e}`)).data,getTariffs:async(e,t=!1)=>(await $.get(`/providers/${e}/tariffs`,{params:{includeInactive:t}})).data,createTariff:async(e,t)=>(await $.post(`/providers/${e}/tariffs`,t)).data},gv={getById:async e=>(await $.get(`/tariffs/${e}`)).data,update:async(e,t)=>(await $.put(`/tariffs/${e}`,t)).data,delete:async e=>(await $.delete(`/tariffs/${e}`)).data},ut={uploadBankCardDocument:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/bank-cards/${e}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},uploadIdentityDocument:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/documents/${e}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteBankCardDocument:async e=>(await $.delete(`/upload/bank-cards/${e}`)).data,deleteIdentityDocument:async e=>(await $.delete(`/upload/documents/${e}`)).data,uploadBusinessRegistration:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/customers/${e}/business-registration`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteBusinessRegistration:async e=>(await $.delete(`/upload/customers/${e}/business-registration`)).data,uploadCommercialRegister:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/customers/${e}/commercial-register`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCommercialRegister:async e=>(await $.delete(`/upload/customers/${e}/commercial-register`)).data,uploadPrivacyPolicy:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/customers/${e}/privacy-policy`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deletePrivacyPolicy:async e=>(await $.delete(`/upload/customers/${e}/privacy-policy`)).data,uploadCancellationLetter:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-letter`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationLetter:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-letter`)).data,uploadCancellationConfirmation:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-confirmation`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationConfirmation:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-confirmation`)).data,uploadCancellationLetterOptions:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-letter-options`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationLetterOptions:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-letter-options`)).data,uploadCancellationConfirmationOptions:async(e,t)=>{const n=new FormData;return n.append("document",t),(await $.post(`/upload/contracts/${e}/cancellation-confirmation-options`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationConfirmationOptions:async e=>(await $.delete(`/upload/contracts/${e}/cancellation-confirmation-options`)).data},Li={getAll:async e=>(await $.get("/users",{params:e})).data,getById:async e=>(await $.get(`/users/${e}`)).data,create:async e=>(await $.post("/users",e)).data,update:async(e,t)=>(await $.put(`/users/${e}`,t)).data,delete:async e=>(await $.delete(`/users/${e}`)).data,getRoles:async()=>(await $.get("/users/roles/list")).data},Ci={getSchema:async()=>(await $.get("/developer/schema")).data,getTableData:async(e,t=1,n=50)=>(await $.get(`/developer/table/${e}`,{params:{page:t,limit:n}})).data,updateRow:async(e,t,n)=>(await $.put(`/developer/table/${e}/${t}`,n)).data,deleteRow:async(e,t)=>(await $.delete(`/developer/table/${e}/${t}`)).data,getReference:async e=>(await $.get(`/developer/reference/${e}`)).data},yn={getConfigs:async()=>(await $.get("/email-providers/configs")).data,getConfig:async e=>(await $.get(`/email-providers/configs/${e}`)).data,createConfig:async e=>(await $.post("/email-providers/configs",e)).data,updateConfig:async(e,t)=>(await $.put(`/email-providers/configs/${e}`,t)).data,deleteConfig:async e=>(await $.delete(`/email-providers/configs/${e}`)).data,testConnection:async e=>{const t=e!=null&&e.testData?{...e.testData}:e!=null&&e.id?{id:e.id}:{};return(await $.post("/email-providers/test-connection",t)).data},getDomain:async()=>(await $.get("/email-providers/domain")).data,checkEmailExists:async e=>(await $.get(`/email-providers/check/${e}`)).data,provisionEmail:async(e,t)=>(await $.post("/email-providers/provision",{localPart:e,customerEmail:t})).data,deprovisionEmail:async e=>(await $.delete(`/email-providers/deprovision/${e}`)).data},yv=j.createContext(null);function bS({children:e}){const[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(()=>localStorage.getItem("developerMode")==="true"),o=p=>{l(p),localStorage.setItem("developerMode",String(p))};j.useEffect(()=>{var p;console.log("useEffect check - user:",t==null?void 0:t.email,"developerMode:",i,"has developer:access:",(p=t==null?void 0:t.permissions)==null?void 0:p.includes("developer:access")),t&&i&&!t.permissions.includes("developer:access")&&(console.log("Disabling developer mode because user lacks developer:access permission"),o(!1))},[t,i]),j.useEffect(()=>{localStorage.getItem("token")?no.me().then(b=>{b.success&&b.data?n(b.data):localStorage.removeItem("token")}).catch(()=>{localStorage.removeItem("token")}).finally(()=>{a(!1)}):a(!1)},[]);const c=async(p,b)=>{const g=await no.login(p,b);if(g.success&&g.data)localStorage.setItem("token",g.data.token),n(g.data.user);else throw new Error(g.error||"Login fehlgeschlagen")},d=async(p,b)=>{const g=await no.customerLogin(p,b);if(g.success&&g.data)localStorage.setItem("token",g.data.token),n(g.data.user);else throw new Error(g.error||"Login fehlgeschlagen")},u=()=>{localStorage.removeItem("token"),n(null)},h=async()=>{var b;if(localStorage.getItem("token"))try{const g=await no.me();console.log("refreshUser response:",g),console.log("permissions:",(b=g.data)==null?void 0:b.permissions),g.success&&g.data&&n(g.data)}catch(g){console.error("refreshUser error:",g)}},x=p=>t?t.permissions.includes(p):!1,m=!!(t!=null&&t.customerId),f=!!(t!=null&&t.isCustomerPortal);return s.jsx(yv.Provider,{value:{user:t,isLoading:r,isAuthenticated:!!t,login:c,customerLogin:d,logout:u,hasPermission:x,isCustomer:m,isCustomerPortal:f,developerMode:i,setDeveloperMode:o,refreshUser:h},children:e})}function We(){const e=j.useContext(yv);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}const xd={scrollToTopThreshold:.7},vv=j.createContext(void 0),dx="opencrm_app_settings";function NS({children:e}){const[t,n]=j.useState(()=>{const a=localStorage.getItem(dx);if(a)try{return{...xd,...JSON.parse(a)}}catch{return xd}return xd});j.useEffect(()=>{localStorage.setItem(dx,JSON.stringify(t))},[t]);const r=a=>{n(i=>({...i,...a}))};return s.jsx(vv.Provider,{value:{settings:t,updateSettings:r},children:e})}function jv(){const e=j.useContext(vv);if(!e)throw new Error("useAppSettings must be used within AppSettingsProvider");return e}function wS(){const{pathname:e}=Rn();return j.useEffect(()=>{window.scrollTo(0,0)},[e]),null}/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const SS=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),bv=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */var kS={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const CS=j.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>j.createElement("svg",{ref:c,...kS,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:bv("lucide",a),...o},[...l.map(([d,u])=>j.createElement(d,u)),...Array.isArray(i)?i:[i]]));/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const se=(e,t)=>{const n=j.forwardRef(({className:r,...a},i)=>j.createElement(CS,{ref:i,iconNode:t,className:bv(`lucide-${SS(e)}`,r),...a}));return n.displayName=`${e}`,n};/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ES=se("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Vs=se("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Nv=se("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const wv=se("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const DS=se("Bomb",[["circle",{cx:"11",cy:"13",r:"9",key:"hd149"}],["path",{d:"M14.35 4.65 16.3 2.7a2.41 2.41 0 0 1 3.4 0l1.6 1.6a2.4 2.4 0 0 1 0 3.4l-1.95 1.95",key:"jp4j1b"}],["path",{d:"m22 2-1.5 1.5",key:"ay92ug"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const AS=se("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const PS=se("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const MS=se("Cable",[["path",{d:"M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1",key:"10bnsj"}],["path",{d:"M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9",key:"1eqmu1"}],["path",{d:"M21 21v-2h-4",key:"14zm7j"}],["path",{d:"M3 5h4V3",key:"z442eg"}],["path",{d:"M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3",key:"ebdjd7"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const TS=se("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Sv=se("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const kv=se("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const xr=se("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dn=se("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const FS=se("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ft=se("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Tc=se("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const kn=se("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const As=se("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ux=se("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const No=se("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dl=se("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const on=se("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Fc=se("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const oh=se("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ch=se("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ic=se("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ps=se("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dh=se("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const It=se("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ae=se("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const IS=se("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Be=se("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const RS=se("FileType",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 13v-1h6v1",key:"1bb014"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M11 18h2",key:"12mj7e"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Cv=se("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const LS=se("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ev=se("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const mx=se("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const uh=se("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const OS=se("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const hx=se("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const zS=se("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Dv=se("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ur=se("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ml=se("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const $S=se("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const _S=se("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const fx=se("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const KS=se("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Av=se("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const nn=se("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const BS=se("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const US=se("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ul=se("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const qS=se("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const VS=se("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Rc=se("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const _e=se("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const mh=se("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Sr=se("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const QS=se("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Pv=se("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Mv=se("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Tl=se("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Fl=se("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Tv=se("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const hh=se("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const He=se("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const fh=se("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const HS=se("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7",key:"6c3vgh"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const WS=se("Table",[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ne=se("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const hs=se("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Fv=se("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Iv=se("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Hu=se("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const GS=se("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ZS=se("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ii=se("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ca=se("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const px=se("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ea=se("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const qt=se("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ph=se("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const JS=se("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** - * @license lucide-react v0.454.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const XS=se("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function YS(){const{user:e,logout:t,hasPermission:n,isCustomer:r,developerMode:a}=We(),i=[{to:"/",icon:_S,label:"Dashboard",show:!0,end:!0},{to:"/customers",icon:Ca,label:"Kunden",show:n("customers:read")&&!r},{to:"/contracts",icon:Be,label:"Verträge",show:n("contracts:read"),end:!0},{to:"/contracts/cockpit",icon:kn,label:"Vertrags-Cockpit",show:n("contracts:read")&&!r},{to:"/tasks",icon:r?ul:dl,label:r?"Support-Anfragen":"Aufgaben",show:n("contracts:read")}],l=[{to:"/developer/database",icon:Ic,label:"Datenbankstruktur"}];return s.jsxs("aside",{className:"w-64 bg-gray-900 text-white min-h-screen flex flex-col",children:[s.jsx("div",{className:"p-4 border-b border-gray-800",children:s.jsx("h1",{className:"text-xl font-bold",children:"OpenCRM"})}),s.jsxs("nav",{className:"flex-1 p-4 overflow-y-auto",children:[s.jsx("ul",{className:"space-y-2",children:i.filter(o=>o.show).map(o=>s.jsx("li",{children:s.jsxs(md,{to:o.to,end:o.end,className:({isActive:c})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${c?"bg-blue-600 text-white":"text-gray-300 hover:bg-gray-800"}`,children:[s.jsx(o.icon,{className:"w-5 h-5"}),o.label]})},o.to))}),a&&n("developer:access")&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mt-6 mb-2 px-4",children:s.jsxs("p",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider flex items-center gap-2",children:[s.jsx(Fc,{className:"w-3 h-3"}),"Entwickler"]})}),s.jsx("ul",{className:"space-y-2",children:l.map(o=>s.jsx("li",{children:s.jsxs(md,{to:o.to,className:({isActive:c})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${c?"bg-purple-600 text-white":"text-purple-300 hover:bg-gray-800"}`,children:[s.jsx(o.icon,{className:"w-5 h-5"}),o.label]})},o.to))})]}),s.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800",children:s.jsxs(md,{to:"/settings",className:({isActive:o})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${o?"bg-blue-600 text-white":"text-gray-300 hover:bg-gray-800"}`,children:[s.jsx(Tv,{className:"w-5 h-5"}),"Einstellungen"]})})]}),s.jsxs("div",{className:"p-4 border-t border-gray-800",children:[s.jsxs("div",{className:"mb-4 text-sm",children:[s.jsx("p",{className:"text-gray-400",children:"Angemeldet als"}),s.jsxs("p",{className:"font-medium",children:[e==null?void 0:e.firstName," ",e==null?void 0:e.lastName]})]}),s.jsxs("button",{onClick:t,className:"flex items-center gap-3 w-full px-4 py-2 text-gray-300 hover:bg-gray-800 rounded-lg transition-colors",children:[s.jsx(KS,{className:"w-5 h-5"}),"Abmelden"]})]})]})}function ek(){const{settings:e}=jv(),[t,n]=j.useState(!1);j.useEffect(()=>{const a=()=>{window.scrollY>window.innerHeight*e.scrollToTopThreshold?n(!0):n(!1)};return window.addEventListener("scroll",a),()=>window.removeEventListener("scroll",a)},[e.scrollToTopThreshold]);const r=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?s.jsx("button",{onClick:r,className:"fixed bottom-6 right-6 p-3 bg-gray-200 hover:bg-gray-300 text-gray-600 rounded-full shadow-md transition-all duration-300 opacity-70 hover:opacity-100 z-50","aria-label":"Nach oben scrollen",title:"Nach oben",children:s.jsx(Tc,{className:"w-5 h-5"})}):null}function tk(){return s.jsxs("div",{className:"flex min-h-screen",children:[s.jsx(YS,{}),s.jsx("main",{className:"flex-1 p-8 overflow-auto",children:s.jsx(uw,{})}),s.jsx(ek,{})]})}const T=j.forwardRef(({className:e="",variant:t="primary",size:n="md",children:r,disabled:a,...i},l)=>{const o="inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-gray-200 text-gray-900 hover:bg-gray-300 focus:ring-gray-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",ghost:"bg-transparent text-gray-700 hover:bg-gray-100 focus:ring-gray-500"},d={sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-sm",lg:"px-6 py-3 text-base"};return s.jsx("button",{ref:l,className:`${o} ${c[t]} ${d[n]} ${e}`,disabled:a,...i,children:r})});T.displayName="Button";const H=j.forwardRef(({className:e="",label:t,error:n,id:r,onClear:a,...i},l)=>{const o=r||i.name,c=i.type==="date",d=i.value!==void 0&&i.value!==null&&i.value!=="",u=c&&a&&d;return s.jsxs("div",{className:"w-full",children:[t&&s.jsx("label",{htmlFor:o,className:"block text-sm font-medium text-gray-700 mb-1",children:t}),s.jsxs("div",{className:u?"flex gap-2":"",children:[s.jsx("input",{ref:l,id:o,className:`block w-full px-3 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${n?"border-red-500":"border-gray-300"} ${e}`,...i}),u&&s.jsx("button",{type:"button",onClick:a,className:"px-3 py-2 text-gray-400 hover:text-red-500 hover:bg-red-50 border border-gray-300 rounded-lg transition-colors",title:"Datum löschen",children:s.jsx(Ne,{className:"w-4 h-4"})})]}),n&&s.jsx("p",{className:"mt-1 text-sm text-red-600",children:n})]})});H.displayName="Input";function X({children:e,className:t="",title:n,actions:r}){return s.jsxs("div",{className:`bg-white rounded-lg shadow ${t}`,children:[(n||r)&&s.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[n&&s.jsx("div",{className:"text-lg font-medium text-gray-900",children:n}),r&&s.jsx("div",{className:"flex items-center gap-2",children:r})]}),s.jsx("div",{className:"p-6",children:e})]})}function sk(){const[e,t]=j.useState(""),[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(!1),{login:c,customerLogin:d}=We(),u=Yt(),h=async x=>{x.preventDefault(),i(""),o(!0);try{await c(e,n),u("/");return}catch{}try{await d(e,n),u("/")}catch{i("Ungültige Anmeldedaten"),o(!1)}};return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-100",children:s.jsxs(X,{className:"w-full max-w-md",children:[s.jsxs("div",{className:"text-center mb-8",children:[s.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"OpenCRM"}),s.jsx("p",{className:"text-gray-600 mt-2",children:"Melden Sie sich an"})]}),a&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:a}),s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(H,{label:"E-Mail",type:"email",value:e,onChange:x=>t(x.target.value),required:!0,autoComplete:"email"}),s.jsx(H,{label:"Passwort",type:"password",value:n,onChange:x=>r(x.target.value),required:!0,autoComplete:"current-password"}),s.jsx(T,{type:"submit",className:"w-full",disabled:l,children:l?"Anmeldung...":"Anmelden"})]})]})})}function qe({isOpen:e,onClose:t,title:n,children:r,size:a="md"}){if(j.useEffect(()=>(e?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[e]),!e)return null;const i={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"};return s.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto",children:s.jsxs("div",{className:"flex min-h-full items-center justify-center p-4",children:[s.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:t}),s.jsxs("div",{className:`relative bg-white rounded-lg shadow-xl w-full ${i[a]}`,children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",children:[s.jsx("h2",{className:"text-lg font-semibold",children:n}),s.jsx(T,{variant:"ghost",size:"sm",onClick:t,children:s.jsx(qt,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"p-6",children:r})]})]})})}function nk(){var w,S,A,O,R,q;const{user:e,isCustomer:t,isCustomerPortal:n}=We(),[r,a]=j.useState(!1),{data:i,isLoading:l}=fe({queryKey:["app-settings-public"],queryFn:()=>Xr.getPublic(),enabled:n,staleTime:0}),o=!l&&((w=i==null?void 0:i.data)==null?void 0:w.customerSupportTicketsEnabled)==="true",{data:c}=fe({queryKey:["customers-count"],queryFn:()=>At.getAll({limit:1}),enabled:!t}),{data:d}=fe({queryKey:["contracts",t?e==null?void 0:e.customerId:void 0],queryFn:()=>Oe.getAll(t?{customerId:e==null?void 0:e.customerId}:{limit:1})}),{data:u}=fe({queryKey:["contracts-active",t?e==null?void 0:e.customerId:void 0],queryFn:()=>Oe.getAll({status:"ACTIVE",...t?{customerId:e==null?void 0:e.customerId}:{limit:1}})}),{data:h}=fe({queryKey:["contracts-pending",t?e==null?void 0:e.customerId:void 0],queryFn:()=>Oe.getAll({status:"PENDING",...t?{customerId:e==null?void 0:e.customerId}:{limit:1}})}),{data:x}=fe({queryKey:["task-stats"],queryFn:()=>et.getStats()}),{data:m}=fe({queryKey:["contract-cockpit"],queryFn:()=>Oe.getCockpit(),enabled:!t,staleTime:0}),{ownContracts:f,representedContracts:p}=j.useMemo(()=>{if(!n||!(d!=null&&d.data))return{ownContracts:[],representedContracts:[]};const D=[],z={};for(const k of d.data)if(k.customerId===(e==null?void 0:e.customerId))D.push(k);else{const K=k.customerId;if(!z[K]){const B=k.customer?k.customer.companyName||`${k.customer.firstName} ${k.customer.lastName}`:`Kunde ${K}`;z[K]={customerName:B,contracts:[]}}z[K].contracts.push(k)}return{ownContracts:D,representedContracts:Object.values(z).sort((k,K)=>k.customerName.localeCompare(K.customerName))}},[d==null?void 0:d.data,n,e==null?void 0:e.customerId]),b=j.useMemo(()=>f.filter(D=>D.status==="ACTIVE").length,[f]),g=j.useMemo(()=>f.filter(D=>D.status==="PENDING").length,[f]),y=j.useMemo(()=>f.filter(D=>D.status==="EXPIRED").length,[f]),v=j.useMemo(()=>p.reduce((D,z)=>D+z.contracts.length,0),[p]),N=j.useMemo(()=>p.reduce((D,z)=>D+z.contracts.filter(k=>k.status==="ACTIVE").length,0),[p]),E=j.useMemo(()=>p.reduce((D,z)=>D+z.contracts.filter(k=>k.status==="EXPIRED").length,0),[p]),P=((S=x==null?void 0:x.data)==null?void 0:S.openCount)||0,I=D=>s.jsx(X,{className:D.link?"cursor-pointer hover:shadow-md transition-shadow":"",children:D.link?s.jsx(ke,{to:D.link,className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:`p-3 rounded-lg ${D.color}`,children:s.jsx(D.icon,{className:"w-6 h-6 text-white"})}),s.jsxs("div",{className:"ml-4",children:[s.jsx("p",{className:"text-sm text-gray-500",children:D.label}),s.jsx("p",{className:"text-2xl font-bold",children:D.value})]})]})}):s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:`p-3 rounded-lg ${D.color}`,children:s.jsx(D.icon,{className:"w-6 h-6 text-white"})}),s.jsxs("div",{className:"ml-4",children:[s.jsx("p",{className:"text-sm text-gray-500",children:D.label}),s.jsx("p",{className:"text-2xl font-bold",children:D.value})]})]})},D.label);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("h1",{className:"text-2xl font-bold",children:["Willkommen, ",e==null?void 0:e.firstName,"!"]}),n&&o&&s.jsxs(T,{onClick:()=>a(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Support-Anfrage"]})]}),n?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(ii,{className:"w-5 h-5 text-blue-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Meine Verträge"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[I({label:"Eigene Verträge",value:f.length,icon:Be,color:"bg-blue-500",link:"/contracts"}),I({label:"Davon aktiv",value:b,icon:As,color:"bg-green-500"}),I({label:"Davon ausstehend",value:g,icon:on,color:"bg-yellow-500"}),I({label:"Davon abgelaufen",value:y,icon:ux,color:"bg-red-500"})]})]}),v>0&&s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(Ca,{className:"w-5 h-5 text-purple-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Fremdverträge"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[I({label:"Fremdverträge",value:v,icon:Ca,color:"bg-purple-500",link:"/contracts"}),I({label:"Davon aktiv",value:N,icon:As,color:"bg-green-500"}),s.jsx("div",{className:"hidden lg:block"}),I({label:"Davon abgelaufen",value:E,icon:ux,color:"bg-red-500"})]})]}),s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(ul,{className:"w-5 h-5 text-orange-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Support-Anfragen"})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:I({label:"Offene Anfragen",value:P,icon:ul,color:"bg-orange-500",link:"/tasks"})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6",children:[I({label:"Kunden",value:((A=c==null?void 0:c.pagination)==null?void 0:A.total)||0,icon:Ca,color:"bg-blue-500",link:"/customers"}),I({label:"Verträge gesamt",value:((O=d==null?void 0:d.pagination)==null?void 0:O.total)||0,icon:Be,color:"bg-purple-500",link:"/contracts"}),I({label:"Aktive Verträge",value:((R=u==null?void 0:u.pagination)==null?void 0:R.total)||0,icon:As,color:"bg-green-500"}),I({label:"Ausstehende Verträge",value:((q=h==null?void 0:h.pagination)==null?void 0:q.total)||0,icon:kn,color:"bg-yellow-500"})]}),(m==null?void 0:m.data)&&s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(kn,{className:"w-5 h-5 text-red-500"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Vertrags-Cockpit"})]}),s.jsx(ke,{to:"/contracts/cockpit",className:"text-sm text-blue-600 hover:underline",children:"Alle anzeigen"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[s.jsx(X,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit?filter=critical",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-red-100",children:s.jsx(kn,{className:"w-6 h-6 text-red-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Kritisch (<",m.data.thresholds.criticalDays," Tage)"]}),s.jsx("p",{className:"text-2xl font-bold text-red-600",children:m.data.summary.criticalCount})]})]})})}),s.jsx(X,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit?filter=warning",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-yellow-100",children:s.jsx(hs,{className:"w-6 h-6 text-yellow-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Warnung (<",m.data.thresholds.warningDays," Tage)"]}),s.jsx("p",{className:"text-2xl font-bold text-yellow-600",children:m.data.summary.warningCount})]})]})})}),s.jsx(X,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit?filter=ok",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-green-100",children:s.jsx(As,{className:"w-6 h-6 text-green-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["OK (<",m.data.thresholds.okDays," Tage)"]}),s.jsx("p",{className:"text-2xl font-bold text-green-600",children:m.data.summary.okCount})]})]})})}),s.jsx(X,{className:"cursor-pointer hover:shadow-md transition-shadow",children:s.jsx(ke,{to:"/contracts/cockpit",className:"block",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"p-3 rounded-lg bg-gray-100",children:s.jsx(Be,{className:"w-6 h-6 text-gray-500"})}),s.jsxs("div",{className:"ml-4",children:[s.jsx("p",{className:"text-sm text-gray-500",children:"Handlungsbedarf"}),s.jsx("p",{className:"text-2xl font-bold text-gray-600",children:m.data.summary.totalContracts})]})]})})})]})]}),s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(dl,{className:"w-5 h-5 text-orange-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"Aufgaben"})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:I({label:"Offene Aufgaben",value:P,icon:dl,color:"bg-orange-500",link:"/tasks"})})]})]}),n&&s.jsx(rk,{isOpen:r,onClose:()=>a(!1)})]})}function rk({isOpen:e,onClose:t}){const{user:n}=We(),r=Yt(),a=ge(),[i,l]=j.useState("own"),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,x]=j.useState(""),[m,f]=j.useState(!1),[p,b]=j.useState(""),{data:g}=fe({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>Oe.getAll({customerId:n==null?void 0:n.customerId}),enabled:e}),y=j.useMemo(()=>{if(!(g!=null&&g.data))return{own:[],represented:{}};const w=[],S={};for(const A of g.data)if(A.customerId===(n==null?void 0:n.customerId))w.push(A);else{if(!S[A.customerId]){const O=A.customer?A.customer.companyName||`${A.customer.firstName} ${A.customer.lastName}`:`Kunde ${A.customerId}`;S[A.customerId]={name:O,contracts:[]}}S[A.customerId].contracts.push(A)}return{own:w,represented:S}},[g==null?void 0:g.data,n==null?void 0:n.customerId]),v=Object.keys(y.represented).length>0,N=j.useMemo(()=>{var w;return i==="own"?y.own:((w=y.represented[i])==null?void 0:w.contracts)||[]},[i,y]),E=j.useMemo(()=>{if(!p)return N;const w=p.toLowerCase();return N.filter(S=>S.contractNumber.toLowerCase().includes(w)||(S.providerName||"").toLowerCase().includes(w)||(S.tariffName||"").toLowerCase().includes(w))},[N,p]),P=async()=>{if(!(!o||!d.trim())){f(!0);try{await et.createSupportTicket(o,{title:d.trim(),description:h.trim()||void 0}),a.invalidateQueries({queryKey:["task-stats"]}),a.invalidateQueries({queryKey:["all-tasks"]}),t(),u(""),x(""),c(null),l("own"),r(`/contracts/${o}`)}catch(w){console.error("Fehler beim Erstellen der Support-Anfrage:",w),alert("Fehler beim Erstellen der Support-Anfrage. Bitte versuchen Sie es erneut.")}finally{f(!1)}}},I=()=>{u(""),x(""),c(null),l("own"),b(""),t()};return s.jsx(qe,{isOpen:e,onClose:I,title:"Neue Support-Anfrage",children:s.jsxs("div",{className:"space-y-4",children:[v&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde"}),s.jsxs("select",{value:i,onChange:w=>{const S=w.target.value;l(S==="own"?"own":parseInt(S)),c(null),b("")},className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",children:[s.jsx("option",{value:"own",children:"Eigene Verträge"}),Object.entries(y.represented).map(([w,{name:S}])=>s.jsx("option",{value:w,children:S},w))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(H,{placeholder:"Vertrag suchen...",value:p,onChange:w=>b(w.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-lg",children:E.length>0?E.map(w=>s.jsxs("div",{onClick:()=>c(w.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${o===w.id?"bg-blue-50 border-blue-200":""}`,children:[s.jsx("div",{className:"font-medium",children:w.contractNumber}),s.jsxs("div",{className:"text-sm text-gray-500",children:[w.providerName||"Kein Anbieter",w.tariffName&&` - ${w.tariffName}`]})]},w.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Verträge gefunden."})})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),s.jsx(H,{value:d,onChange:w=>u(w.target.value),placeholder:"Kurze Beschreibung Ihres Anliegens"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),s.jsx("textarea",{value:h,onChange:w=>x(w.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:4,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:I,children:"Abbrechen"}),s.jsx(T,{onClick:P,disabled:!o||!d.trim()||m,children:m?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function ve({children:e,variant:t="default",className:n="",onClick:r}){const a={default:"bg-gray-100 text-gray-800",success:"bg-green-100 text-green-800",warning:"bg-yellow-100 text-yellow-800",danger:"bg-red-100 text-red-800",info:"bg-blue-100 text-blue-800"};return s.jsx("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${a[t]} ${n}`,onClick:r,children:e})}function ak(){const[e,t]=j.useState(""),[n,r]=j.useState(""),[a,i]=j.useState(1),{hasPermission:l}=We(),{data:o,isLoading:c}=fe({queryKey:["customers",e,n,a],queryFn:()=>At.getAll({search:e,type:n||void 0,page:a,limit:20})});return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Kunden"}),l("customers:create")&&s.jsx(ke,{to:"/customers/new",children:s.jsxs(T,{children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neuer Kunde"]})})]}),s.jsx(X,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx(H,{placeholder:"Suchen...",value:e,onChange:d=>t(d.target.value),className:"flex-1"}),s.jsxs("select",{value:n,onChange:d=>r(d.target.value),className:"px-3 py-2 border border-gray-300 rounded-lg w-28 flex-shrink-0",children:[s.jsx("option",{value:"",children:"Alle"}),s.jsx("option",{value:"PRIVATE",children:"Privat"}),s.jsx("option",{value:"BUSINESS",children:"Firma"})]}),s.jsx(T,{variant:"secondary",className:"flex-shrink-0",children:s.jsx(Tl,{className:"w-4 h-4"})})]})}),s.jsx(X,{children:c?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):o!=null&&o.data&&o.data.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kundennr."}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Typ"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"E-Mail"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Verträge"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:o.data.map(d=>{var u;return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono text-sm",children:d.customerNumber}),s.jsx("td",{className:"py-3 px-4",children:d.type==="BUSINESS"&&d.companyName?d.companyName:`${d.firstName} ${d.lastName}`}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ve,{variant:d.type==="BUSINESS"?"info":"default",children:d.type==="BUSINESS"?"Firma":"Privat"})}),s.jsx("td",{className:"py-3 px-4",children:d.email||"-"}),s.jsx("td",{className:"py-3 px-4",children:((u=d._count)==null?void 0:u.contracts)||0}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ke,{to:`/customers/${d.id}`,children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(Ae,{className:"w-4 h-4"})})}),l("customers:update")&&s.jsx(ke,{to:`/customers/${d.id}/edit`,children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(He,{className:"w-4 h-4"})})})]})})]},d.id)})})]})}),o.pagination&&o.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",o.pagination.page," von ",o.pagination.totalPages," (",o.pagination.total," Einträge)"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>i(d=>Math.max(1,d-1)),disabled:a===1,children:"Zurück"}),s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>i(d=>d+1),disabled:a>=o.pagination.totalPages,children:"Weiter"})]})]})]}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Kunden gefunden."})})]})}function ik({emails:e,selectedEmailId:t,onSelectEmail:n,onEmailDeleted:r,isLoading:a,folder:i="INBOX",accountId:l}){const o=i==="SENT",[c,d]=j.useState(null),{hasPermission:u}=We(),h=S=>{if(o)try{const A=JSON.parse(S.toAddresses);if(A.length>0)return`An: ${A[0]}${A.length>1?` (+${A.length-1})`:""}`}catch{return"An: (Unbekannt)"}return S.fromName||S.fromAddress},x=ge(),m=G({mutationFn:S=>Pe.toggleStar(S),onSuccess:(S,A)=>{x.invalidateQueries({queryKey:["emails"]}),x.invalidateQueries({queryKey:["email",A]})}}),f=G({mutationFn:({emailId:S,isRead:A})=>Pe.markAsRead(S,A),onSuccess:(S,A)=>{x.invalidateQueries({queryKey:["emails"]}),x.invalidateQueries({queryKey:["email",A.emailId]}),l&&x.invalidateQueries({queryKey:["folder-counts",l]})}}),p=G({mutationFn:S=>Pe.delete(S),onSuccess:(S,A)=>{x.invalidateQueries({queryKey:["emails"]}),l&&x.invalidateQueries({queryKey:["folder-counts",l]}),Re.success("E-Mail in Papierkorb verschoben"),d(null),r==null||r(A)},onError:S=>{console.error("Delete error:",S),Re.error(S.message||"Fehler beim Löschen der E-Mail"),d(null)}}),b=G({mutationFn:S=>Pe.unassignFromContract(S),onSuccess:()=>{x.invalidateQueries({queryKey:["emails"]}),Re.success("Vertragszuordnung aufgehoben")},onError:S=>{console.error("Unassign error:",S),Re.error(S.message||"Fehler beim Aufheben der Zuordnung")}}),g=(S,A)=>{S.stopPropagation(),b.mutate(A)},y=(S,A)=>{S.stopPropagation(),d(A)},v=S=>{S.stopPropagation(),c&&p.mutate(c)},N=S=>{S.stopPropagation(),d(null)},E=S=>{const A=new Date(S),O=new Date;return A.toDateString()===O.toDateString()?A.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):A.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},P=(S,A)=>{S.stopPropagation(),m.mutate(A)},I=(S,A)=>{S.stopPropagation(),f.mutate({emailId:A.id,isRead:!A.isRead})},w=S=>{S.isRead||f.mutate({emailId:S.id,isRead:!0}),n(S)};return a?s.jsx("div",{className:"flex items-center justify-center h-64",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):e.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[s.jsx(nn,{className:"w-12 h-12 mb-2 opacity-50"}),s.jsx("p",{children:"Keine E-Mails vorhanden"})]}):s.jsxs("div",{className:"divide-y divide-gray-200",children:[e.map(S=>s.jsxs("div",{onClick:()=>w(S),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",t===S.id?"bg-blue-100":["hover:bg-gray-100",S.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:t===S.id?"4px solid #2563eb":"4px solid transparent"},children:[s.jsx("button",{onClick:A=>I(A,S),className:` - flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 - ${S.isRead?"text-gray-400":"text-blue-600"} - `,title:S.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:S.isRead?s.jsx(Av,{className:"w-4 h-4"}):s.jsx(nn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:A=>P(A,S.id),className:` - flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 - ${S.isStarred?"text-yellow-500":"text-gray-400"} - `,title:S.isStarred?"Stern entfernen":"Als wichtig markieren",children:s.jsx(fh,{className:`w-4 h-4 ${S.isStarred?"fill-current":""}`})}),u("emails:delete")&&s.jsx("button",{onClick:A=>y(A,S.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"E-Mail löschen",children:s.jsx(Ne,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[s.jsx("span",{className:`text-sm truncate ${S.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:h(S)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:E(S.receivedAt)})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm truncate ${S.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:S.subject||"(Kein Betreff)"}),S.hasAttachments&&s.jsx(Rc,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),S.contract&&s.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[s.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:S.contract.contractNumber}),(i==="INBOX"||i==="SENT"&&!S.isAutoAssigned)&&s.jsx("button",{onClick:A=>g(A,S.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:b.isPending,children:s.jsx(qt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Ft,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},S.id)),c&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:N,disabled:p.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"danger",onClick:v,disabled:p.isPending,children:p.isPending?"Löschen...":"Löschen"})]})]})})]})}const Ie=j.forwardRef(({className:e="",label:t,error:n,options:r,id:a,placeholder:i="Bitte wählen...",...l},o)=>{const c=a||l.name,d=/\bw-\d+\b|\bw-\[|\bflex-/.test(e);return s.jsxs("div",{className:d?e:"w-full",children:[t&&s.jsx("label",{htmlFor:c,className:"block text-sm font-medium text-gray-700 mb-1",children:t}),s.jsxs("select",{ref:o,id:c,className:`block w-full px-3 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${n?"border-red-500":"border-gray-300"}`,...l,children:[s.jsx("option",{value:"",children:i}),r.map(u=>s.jsx("option",{value:u.value,children:u.label},u.value))]}),n&&s.jsx("p",{className:"mt-1 text-sm text-red-600",children:n})]})});Ie.displayName="Select";function lk({isOpen:e,onClose:t,emailId:n,attachmentFilename:r,onSuccess:a}){var O,R,q;const[i,l]=j.useState(null),[o,c]=j.useState(new Set(["customer"])),[d,u]=j.useState("document"),[h,x]=j.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),m=ge(),{data:f,isLoading:p,error:b}=fe({queryKey:["attachment-targets",n],queryFn:()=>Pe.getAttachmentTargets(n),enabled:e}),g=f==null?void 0:f.data,y=((O=g==null?void 0:g.contract)==null?void 0:O.type)==="ELECTRICITY"||((R=g==null?void 0:g.contract)==null?void 0:R.type)==="GAS",v=G({mutationFn:()=>{if(!i)throw new Error("Kein Ziel ausgewählt");return Pe.saveAttachmentTo(n,r,{entityType:i.entityType,entityId:i.entityId,targetKey:i.targetKey})},onSuccess:()=>{var D,z;Re.success("Anhang gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(D=g==null?void 0:g.customer)!=null&&D.id&&m.invalidateQueries({queryKey:["customer",g.customer.id.toString()]}),(z=g==null?void 0:g.contract)!=null&&z.id&&m.invalidateQueries({queryKey:["contract",g.contract.id.toString()]}),a==null||a(),E()},onError:D=>{Re.error(D.message||"Fehler beim Speichern")}}),N=G({mutationFn:()=>Pe.saveAttachmentAsInvoice(n,r,{invoiceDate:h.invoiceDate,invoiceType:h.invoiceType,notes:h.notes||void 0}),onSuccess:()=>{var D;Re.success("Anhang als Rechnung gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(D=g==null?void 0:g.contract)!=null&&D.id&&m.invalidateQueries({queryKey:["contract",g.contract.id.toString()]}),a==null||a(),E()},onError:D=>{Re.error(D.message||"Fehler beim Speichern der Rechnung")}}),E=()=>{l(null),u("document"),x({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),t()},P=D=>{const z=new Set(o);z.has(D)?z.delete(D):z.add(D),c(z)},I=(D,z,k,K)=>{l({entityType:D,entityId:k,targetKey:z.key,hasDocument:z.hasDocument,label:K?`${K} → ${z.label}`:z.label})},w=(D,z,k,K)=>D.map(B=>{const _=(i==null?void 0:i.entityType)===z&&(i==null?void 0:i.entityId)===k&&(i==null?void 0:i.targetKey)===B.key;return s.jsxs("div",{onClick:()=>I(z,B,k,K),className:` - flex items-center gap-3 p-3 cursor-pointer transition-colors rounded-lg ml-4 - ${_?"bg-blue-100 ring-2 ring-blue-500":"hover:bg-gray-100"} - `,children:[s.jsx("div",{className:"flex-1 min-w-0",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-medium text-gray-900",children:B.label}),B.hasDocument&&s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Vorhanden"]})]})}),_&&s.jsx(xr,{className:"w-5 h-5 text-blue-600"})]},B.key)}),S=(D,z)=>s.jsxs("div",{className:"mb-2",children:[s.jsx("div",{className:"text-sm font-medium text-gray-700 px-3 py-1 bg-gray-50 rounded",children:D.label}),w(D.slots,z,D.id,D.label)]},D.id),A=(D,z,k,K,B=!1)=>{const _=o.has(z);return s.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>P(z),className:"w-full flex items-center gap-2 p-3 bg-gray-50 hover:bg-gray-100 transition-colors",children:[_?s.jsx(dn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"}),k,s.jsx("span",{className:"font-medium text-gray-900",children:D})]}),_&&s.jsx("div",{className:"p-2",children:B?s.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):K})]})};return s.jsx(qe,{isOpen:e,onClose:E,title:"Anhang speichern unter",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-gray-50 rounded-lg",children:s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:"Datei:"})," ",r]})}),p&&s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}),b&&s.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),g&&s.jsxs(s.Fragment,{children:[y&&s.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[s.jsxs("button",{onClick:()=>u("document"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${d==="document"?"bg-white text-blue-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Be,{className:"w-4 h-4"}),"Als Dokument"]}),s.jsxs("button",{onClick:()=>u("invoice"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${d==="invoice"?"bg-white text-green-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(mh,{className:"w-4 h-4"}),"Als Rechnung"]})]}),d==="document"&&s.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[A(`Kunde: ${g.customer.name}`,"customer",s.jsx(ii,{className:"w-4 h-4 text-blue-600"}),w(g.customer.slots,"customer"),g.customer.slots.length===0),A("Ausweisdokumente","identityDocuments",s.jsx(Dv,{className:"w-4 h-4 text-green-600"}),g.identityDocuments.map(D=>S(D,"identityDocument")),g.identityDocuments.length===0),A("Bankkarten","bankCards",s.jsx(ch,{className:"w-4 h-4 text-purple-600"}),g.bankCards.map(D=>S(D,"bankCard")),g.bankCards.length===0),g.contract&&A(`Vertrag: ${g.contract.contractNumber}`,"contract",s.jsx(Be,{className:"w-4 h-4 text-orange-600"}),w(g.contract.slots,"contract"),g.contract.slots.length===0),!g.contract&&s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[s.jsx(Be,{className:"w-4 h-4 inline-block mr-2 text-gray-400"}),"E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um Vertragsdokumente als Ziel auswählen zu können."]})]}),d==="invoice"&&y&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:s.jsxs("p",{className:"text-sm text-green-700",children:["Der Anhang wird als Rechnung für den Vertrag ",s.jsx("strong",{children:(q=g.contract)==null?void 0:q.contractNumber})," gespeichert."]})}),s.jsx(H,{label:"Rechnungsdatum",type:"date",value:h.invoiceDate,onChange:D=>x({...h,invoiceDate:D.target.value}),required:!0}),s.jsx(Ie,{label:"Rechnungstyp",value:h.invoiceType,onChange:D=>x({...h,invoiceType:D.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),s.jsx(H,{label:"Notizen (optional)",value:h.notes,onChange:D=>x({...h,notes:D.target.value}),placeholder:"Optionale Anmerkungen..."})]})]}),d==="document"&&(i==null?void 0:i.hasDocument)&&s.jsxs("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2",children:[s.jsx(hs,{className:"w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-yellow-800",children:[s.jsx("strong",{children:"Achtung:"})," An diesem Feld ist bereits ein Dokument hinterlegt. Das vorhandene Dokument wird durch den neuen Anhang ersetzt."]})]}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:E,children:"Abbrechen"}),d==="document"?s.jsx(T,{onClick:()=>v.mutate(),disabled:!i||v.isPending||N.isPending,children:v.isPending?"Wird gespeichert...":"Speichern"}):s.jsx(T,{onClick:()=>N.mutate(),disabled:!h.invoiceDate||v.isPending||N.isPending,children:N.isPending?"Wird gespeichert...":"Als Rechnung speichern"})]})]})})}function ok({isOpen:e,onClose:t,emailId:n,onSuccess:r}){var O,R,q;const[a,i]=j.useState(null),[l,o]=j.useState(new Set(["customer"])),[c,d]=j.useState("document"),[u,h]=j.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),x=ge(),{data:m,isLoading:f,error:p}=fe({queryKey:["attachment-targets",n],queryFn:()=>Pe.getAttachmentTargets(n),enabled:e}),b=m==null?void 0:m.data,g=((O=b==null?void 0:b.contract)==null?void 0:O.type)==="ELECTRICITY"||((R=b==null?void 0:b.contract)==null?void 0:R.type)==="GAS",y=G({mutationFn:()=>{if(!a)throw new Error("Kein Ziel ausgewählt");return Pe.saveEmailAsPdf(n,{entityType:a.entityType,entityId:a.entityId,targetKey:a.targetKey})},onSuccess:()=>{var D,z;Re.success("E-Mail als PDF gespeichert"),x.invalidateQueries({queryKey:["attachment-targets",n]}),x.invalidateQueries({queryKey:["customers"]}),x.invalidateQueries({queryKey:["contracts"]}),(D=b==null?void 0:b.customer)!=null&&D.id&&x.invalidateQueries({queryKey:["customer",b.customer.id.toString()]}),(z=b==null?void 0:b.contract)!=null&&z.id&&x.invalidateQueries({queryKey:["contract",b.contract.id.toString()]}),r==null||r(),N()},onError:D=>{Re.error(D.message||"Fehler beim Speichern")}}),v=G({mutationFn:()=>Pe.saveEmailAsInvoice(n,{invoiceDate:u.invoiceDate,invoiceType:u.invoiceType,notes:u.notes||void 0}),onSuccess:()=>{var D;Re.success("E-Mail als Rechnung gespeichert"),x.invalidateQueries({queryKey:["attachment-targets",n]}),x.invalidateQueries({queryKey:["customers"]}),x.invalidateQueries({queryKey:["contracts"]}),(D=b==null?void 0:b.contract)!=null&&D.id&&x.invalidateQueries({queryKey:["contract",b.contract.id.toString()]}),r==null||r(),N()},onError:D=>{Re.error(D.message||"Fehler beim Speichern der Rechnung")}}),N=()=>{i(null),d("document"),h({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),t()},E=D=>{const z=new Set(l);z.has(D)?z.delete(D):z.add(D),o(z)},P=(D,z,k,K)=>{i({entityType:D,entityId:k,targetKey:z.key,hasDocument:z.hasDocument,label:K?`${K} → ${z.label}`:z.label})},I=(D,z,k,K)=>D.map(B=>{const _=(a==null?void 0:a.entityType)===z&&(a==null?void 0:a.entityId)===k&&(a==null?void 0:a.targetKey)===B.key;return s.jsxs("div",{onClick:()=>P(z,B,k,K),className:` - flex items-center gap-3 p-3 cursor-pointer transition-colors rounded-lg ml-4 - ${_?"bg-blue-100 ring-2 ring-blue-500":"hover:bg-gray-100"} - `,children:[s.jsx("div",{className:"flex-1 min-w-0",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-medium text-gray-900",children:B.label}),B.hasDocument&&s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Vorhanden"]})]})}),_&&s.jsx(xr,{className:"w-5 h-5 text-blue-600"})]},B.key)}),w=(D,z)=>s.jsxs("div",{className:"mb-2",children:[s.jsx("div",{className:"text-sm font-medium text-gray-700 px-3 py-1 bg-gray-50 rounded",children:D.label}),I(D.slots,z,D.id,D.label)]},D.id),S=(D,z,k,K,B=!1)=>{const _=l.has(z);return s.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>E(z),className:"w-full flex items-center gap-2 p-3 bg-gray-50 hover:bg-gray-100 transition-colors",children:[_?s.jsx(dn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"}),k,s.jsx("span",{className:"font-medium text-gray-900",children:D})]}),_&&s.jsx("div",{className:"p-2",children:B?s.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):K})]})},A=y.isPending||v.isPending;return s.jsx(qe,{isOpen:e,onClose:N,title:"E-Mail als PDF speichern",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-blue-50 rounded-lg",children:s.jsx("p",{className:"text-sm text-blue-700",children:"Die E-Mail wird als PDF exportiert (inkl. Absender, Empfänger, Datum und Inhalt) und im gewählten Dokumentenfeld gespeichert."})}),f&&s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}),p&&s.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),b&&s.jsxs(s.Fragment,{children:[g&&s.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[s.jsxs("button",{onClick:()=>d("document"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${c==="document"?"bg-white text-blue-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Be,{className:"w-4 h-4"}),"Als Dokument"]}),s.jsxs("button",{onClick:()=>d("invoice"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${c==="invoice"?"bg-white text-green-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(mh,{className:"w-4 h-4"}),"Als Rechnung"]})]}),c==="document"&&s.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[S(`Kunde: ${b.customer.name}`,"customer",s.jsx(ii,{className:"w-4 h-4 text-blue-600"}),I(b.customer.slots,"customer"),b.customer.slots.length===0),S("Ausweisdokumente","identityDocuments",s.jsx(Dv,{className:"w-4 h-4 text-green-600"}),b.identityDocuments.map(D=>w(D,"identityDocument")),b.identityDocuments.length===0),S("Bankkarten","bankCards",s.jsx(ch,{className:"w-4 h-4 text-purple-600"}),b.bankCards.map(D=>w(D,"bankCard")),b.bankCards.length===0),b.contract&&S(`Vertrag: ${b.contract.contractNumber}`,"contract",s.jsx(Be,{className:"w-4 h-4 text-orange-600"}),I(b.contract.slots,"contract"),b.contract.slots.length===0),!b.contract&&s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[s.jsx(Be,{className:"w-4 h-4 inline-block mr-2 text-gray-400"}),"E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um Vertragsdokumente als Ziel auswählen zu können."]})]}),c==="invoice"&&g&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:s.jsxs("p",{className:"text-sm text-green-700",children:["Die E-Mail wird als Rechnung für den Vertrag ",s.jsx("strong",{children:(q=b.contract)==null?void 0:q.contractNumber})," gespeichert."]})}),s.jsx(H,{label:"Rechnungsdatum",type:"date",value:u.invoiceDate,onChange:D=>h({...u,invoiceDate:D.target.value}),required:!0}),s.jsx(Ie,{label:"Rechnungstyp",value:u.invoiceType,onChange:D=>h({...u,invoiceType:D.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),s.jsx(H,{label:"Notizen (optional)",value:u.notes,onChange:D=>h({...u,notes:D.target.value}),placeholder:"Optionale Anmerkungen..."})]})]}),c==="document"&&(a==null?void 0:a.hasDocument)&&s.jsxs("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2",children:[s.jsx(hs,{className:"w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-yellow-800",children:[s.jsx("strong",{children:"Achtung:"})," An diesem Feld ist bereits ein Dokument hinterlegt. Das vorhandene Dokument wird durch die PDF ersetzt."]})]}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:N,children:"Abbrechen"}),c==="document"?s.jsx(T,{onClick:()=>y.mutate(),disabled:!a||A,children:A?"Wird erstellt...":"Als PDF speichern"}):s.jsx(T,{onClick:()=>v.mutate(),disabled:!u.invoiceDate||A,children:A?"Wird erstellt...":"Als Rechnung speichern"})]})]})})}function Rv({email:e,onReply:t,onAssignContract:n,onDeleted:r,isSentFolder:a=!1,isContractView:i=!1,isTrashView:l=!1,onRestored:o,accountId:c}){const[d,u]=j.useState(!0),[h,x]=j.useState(e.isStarred),[m,f]=j.useState(!1),[p,b]=j.useState(!1),[g,y]=j.useState(!1),[v,N]=j.useState(null),[E,P]=j.useState(!1),I=ge(),{hasPermission:w}=We();j.useEffect(()=>{x(e.isStarred)},[e.id,e.isStarred]);const S=G({mutationFn:()=>Pe.toggleStar(e.id),onMutate:()=>{x(Q=>!Q)},onSuccess:()=>{I.invalidateQueries({queryKey:["emails"]}),I.invalidateQueries({queryKey:["email",e.id]})},onError:()=>{x(e.isStarred)}}),A=G({mutationFn:()=>Pe.unassignFromContract(e.id),onSuccess:()=>{I.invalidateQueries({queryKey:["emails"]}),I.invalidateQueries({queryKey:["email",e.id]}),e.contractId&&I.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Re.success("Vertragszuordnung aufgehoben")},onError:Q=>{console.error("Unassign error:",Q),Re.error(Q.message||"Fehler beim Aufheben der Zuordnung")}}),O=G({mutationFn:()=>Pe.delete(e.id),onSuccess:()=>{I.invalidateQueries({queryKey:["emails"]}),c&&I.invalidateQueries({queryKey:["folder-counts",c]}),e.contractId&&I.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Re.success("E-Mail in Papierkorb verschoben"),f(!1),r==null||r()},onError:Q=>{console.error("Delete error:",Q),Re.error(Q.message||"Fehler beim Löschen der E-Mail"),f(!1)}}),R=G({mutationFn:()=>Pe.restore(e.id),onSuccess:()=>{I.invalidateQueries({queryKey:["emails"]}),c&&I.invalidateQueries({queryKey:["folder-counts",c]}),e.contractId&&I.invalidateQueries({queryKey:["contract-folder-counts",e.contractId]}),Re.success("E-Mail wiederhergestellt"),b(!1),o==null||o()},onError:Q=>{console.error("Restore error:",Q),Re.error(Q.message||"Fehler beim Wiederherstellen der E-Mail"),b(!1)}}),q=G({mutationFn:()=>Pe.permanentDelete(e.id),onSuccess:()=>{I.invalidateQueries({queryKey:["emails"]}),c&&I.invalidateQueries({queryKey:["folder-counts",c]}),Re.success("E-Mail endgültig gelöscht"),y(!1),r==null||r()},onError:Q=>{console.error("Permanent delete error:",Q),Re.error(Q.message||"Fehler beim endgültigen Löschen der E-Mail"),y(!1)}}),D=Q=>new Date(Q).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),z=Q=>{try{return JSON.parse(Q)}catch{return[]}},k=Q=>{if(!Q)return[];try{return JSON.parse(Q)}catch{return[]}},K=z(e.toAddresses),B=e.ccAddresses?z(e.ccAddresses):[],_=k(e.attachmentNames);return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"p-4 border-b border-gray-200 space-y-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:e.subject||"(Kein Betreff)"}),s.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:l?s.jsxs(s.Fragment,{children:[s.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>b(!0),title:"Wiederherstellen",children:[s.jsx(Iv,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),s.jsxs(T,{variant:"danger",size:"sm",onClick:()=>y(!0),title:"Endgültig löschen",children:[s.jsx(Ne,{className:"w-4 h-4 mr-1"}),"Endgültig löschen"]})]}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>S.mutate(),className:`p-2 rounded-lg hover:bg-gray-100 ${h?"text-yellow-500":"text-gray-400"}`,title:h?"Stern entfernen":"Als wichtig markieren",children:s.jsx(fh,{className:`w-5 h-5 ${h?"fill-current":""}`})}),s.jsxs(T,{variant:"secondary",size:"sm",onClick:t,children:[s.jsx(QS,{className:"w-4 h-4 mr-1"}),"Antworten"]}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>P(!0),title:"E-Mail als PDF speichern",children:s.jsx(IS,{className:"w-4 h-4"})}),w("emails:delete")&&s.jsx(T,{variant:"danger",size:"sm",onClick:()=>f(!0),title:"E-Mail löschen",children:s.jsx(Ne,{className:"w-4 h-4"})})]})})]}),s.jsxs("div",{className:"text-sm space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"Von:"}),s.jsxs("span",{className:"font-medium text-gray-900",children:[e.fromName&&`${e.fromName} `,s.jsxs("span",{className:"text-gray-600",children:["<",e.fromAddress,">"]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"An:"}),s.jsx("span",{className:"text-gray-700",children:K.join(", ")})]}),B.length>0&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"CC:"}),s.jsx("span",{className:"text-gray-700",children:B.join(", ")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-gray-500 w-12",children:"Am:"}),s.jsx("span",{className:"text-gray-700",children:D(e.receivedAt)})]})]}),s.jsx("div",{className:"flex items-center gap-2 pt-2",children:e.contract?s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-green-50 border border-green-200 rounded-lg",children:[s.jsx(fx,{className:"w-4 h-4 text-green-600"}),s.jsxs("span",{className:"text-sm text-green-800",children:["Zugeordnet zu:"," ",s.jsx(ke,{to:`/contracts/${e.contract.id}`,className:"font-medium hover:underline",children:e.contract.contractNumber})]}),!e.isAutoAssigned&&s.jsx("button",{onClick:()=>A.mutate(),className:"ml-2 p-1 hover:bg-green-100 rounded",title:"Zuordnung aufheben",children:s.jsx(qt,{className:"w-4 h-4 text-green-600"})})]}):!i&&s.jsxs(T,{variant:"secondary",size:"sm",onClick:n,children:[s.jsx(fx,{className:"w-4 h-4 mr-1"}),"Vertrag zuordnen"]})}),_.length>0&&s.jsxs("div",{className:"pt-2",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(Rc,{className:"w-4 h-4 text-gray-400"}),s.jsxs("span",{className:"text-sm text-gray-500",children:[_.length," Anhang",_.length>1?"e":""]})]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:_.map((Q,le)=>s.jsxs("div",{className:"inline-flex items-center gap-1 px-3 py-2 bg-gray-100 rounded-lg text-sm text-gray-700",children:[s.jsx("span",{className:"max-w-[200px] truncate mr-1",children:Q}),s.jsx("a",{href:Pe.getAttachmentUrl(e.id,Q,!0),target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${Q} öffnen`,children:s.jsx(dh,{className:"w-4 h-4 text-gray-500"})}),s.jsx("a",{href:Pe.getAttachmentUrl(e.id,Q),download:Q,className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${Q} herunterladen`,children:s.jsx(Ps,{className:"w-4 h-4 text-gray-500"})}),!l&&s.jsx("button",{onClick:()=>N(Q),className:"p-1 hover:bg-blue-100 rounded transition-colors",title:`${Q} speichern unter...`,children:s.jsx(Mv,{className:"w-4 h-4 text-blue-500"})})]},le))})]})]}),e.htmlBody&&e.textBody&&s.jsxs("div",{className:"px-4 py-2 border-b border-gray-200 flex items-center gap-2",children:[s.jsx("button",{onClick:()=>u(!0),className:`px-3 py-1 text-sm rounded ${d?"bg-blue-100 text-blue-700":"text-gray-600 hover:bg-gray-100"}`,children:"HTML"}),s.jsx("button",{onClick:()=>u(!1),className:`px-3 py-1 text-sm rounded ${d?"text-gray-600 hover:bg-gray-100":"bg-blue-100 text-blue-700"}`,children:"Text"})]}),s.jsx("div",{className:"flex-1 overflow-auto p-4",children:d&&e.htmlBody?s.jsx("div",{className:"prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:e.htmlBody}}):s.jsx("pre",{className:"whitespace-pre-wrap text-sm text-gray-700 font-sans",children:e.textBody||"Kein Inhalt"})}),m&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:()=>f(!1),disabled:O.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"danger",onClick:()=>O.mutate(),disabled:O.isPending,children:O.isPending?"Löschen...":"Löschen"})]})]})}),p&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail wiederherstellen?"}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Die E-Mail wird wieder in den ursprünglichen Ordner (",e.folder==="SENT"?"Gesendet":"Posteingang",") verschoben."]}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:()=>b(!1),disabled:R.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"primary",onClick:()=>R.mutate(),disabled:R.isPending,children:R.isPending?"Wird wiederhergestellt...":"Wiederherstellen"})]})]})}),g&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail endgültig löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Diese Aktion kann nicht rückgängig gemacht werden. Die E-Mail wird unwiderruflich gelöscht."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:()=>y(!1),disabled:q.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"danger",onClick:()=>q.mutate(),disabled:q.isPending,children:q.isPending?"Wird gelöscht...":"Endgültig löschen"})]})]})}),v&&s.jsx(lk,{isOpen:!0,onClose:()=>N(null),emailId:e.id,attachmentFilename:v}),E&&s.jsx(ok,{isOpen:!0,onClose:()=>P(!1),emailId:e.id})]})}function Lv({isOpen:e,onClose:t,account:n,replyTo:r,onSuccess:a,contractId:i}){const[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[x,m]=j.useState(""),[f,p]=j.useState([]),[b,g]=j.useState(null),y=j.useRef(null);j.useEffect(()=>{if(e){if(r){o(r.fromAddress||"");const R=r.subject||"",q=/^(Re|Aw|Fwd|Wg):\s*/i.test(R);h(q?R:`Re: ${R}`);const D=new Date(r.receivedAt).toLocaleString("de-DE"),z=r.textBody?` - ---- Ursprüngliche Nachricht --- -Von: ${r.fromName||r.fromAddress} -Am: ${D} - -${r.textBody}`:"";m(z)}else o(""),h(""),m("");d(""),p([]),g(null)}},[e,r]);const v=10*1024*1024,N=25*1024*1024,E=R=>new Promise((q,D)=>{const z=new FileReader;z.readAsDataURL(R),z.onload=()=>{const K=z.result.split(",")[1];q(K)},z.onerror=D}),P=async R=>{const q=R.target.files;if(!q)return;const D=[];let z=f.reduce((k,K)=>k+K.content.length*.75,0);for(const k of Array.from(q)){if(k.size>v){g(`Datei "${k.name}" ist zu groß (max. 10 MB)`);continue}if(z+k.size>N){g("Maximale Gesamtgröße der Anhänge erreicht (25 MB)");break}try{const K=await E(k);D.push({filename:k.name,content:K,contentType:k.type||"application/octet-stream"}),z+=k.size}catch{g(`Fehler beim Lesen von "${k.name}"`)}}D.length>0&&p(k=>[...k,...D]),y.current&&(y.current.value="")},I=R=>{p(q=>q.filter((D,z)=>z!==R))},w=R=>{const q=R.length*.75;return q<1024?`${Math.round(q)} B`:q<1024*1024?`${(q/1024).toFixed(1)} KB`:`${(q/(1024*1024)).toFixed(1)} MB`},S=G({mutationFn:()=>xs.sendEmail(n.id,{to:l.split(",").map(R=>R.trim()).filter(Boolean),cc:c?c.split(",").map(R=>R.trim()).filter(Boolean):void 0,subject:u,text:x,inReplyTo:r==null?void 0:r.messageId,references:r!=null&&r.messageId?[r.messageId]:void 0,attachments:f.length>0?f:void 0,contractId:i}),onSuccess:()=>{a==null||a(),A()},onError:R=>{g(R instanceof Error?R.message:"Fehler beim Senden")}}),A=()=>{t()},O=()=>{if(!l.trim()){g("Bitte Empfänger angeben");return}if(!u.trim()){g("Bitte Betreff angeben");return}g(null),S.mutate()};return s.jsx(qe,{isOpen:e,onClose:A,title:r?"Antworten":"Neue E-Mail",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Von"}),s.jsx("div",{className:"px-3 py-2 bg-gray-100 rounded-lg text-sm text-gray-700",children:n.email})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["An ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:l,onChange:R=>o(R.target.value),placeholder:"empfaenger@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"}),s.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Mehrere Empfänger mit Komma trennen"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"CC"}),s.jsx("input",{type:"text",value:c,onChange:R=>d(R.target.value),placeholder:"cc@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Betreff ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:u,onChange:R=>h(R.target.value),placeholder:"Betreff eingeben",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Nachricht"}),s.jsx("textarea",{value:x,onChange:R=>m(R.target.value),rows:10,placeholder:"Ihre Nachricht...",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Anhänge"}),s.jsx("input",{type:"file",ref:y,onChange:P,multiple:!0,className:"hidden"}),s.jsxs("button",{type:"button",onClick:()=>{var R;return(R=y.current)==null?void 0:R.click()},className:"inline-flex items-center px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:[s.jsx(Rc,{className:"w-4 h-4 mr-2"}),"Datei anhängen"]}),f.length>0&&s.jsx("div",{className:"mt-2 space-y-2",children:f.map((R,q)=>s.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 rounded-lg",children:[s.jsxs("div",{className:"flex items-center min-w-0",children:[s.jsx(Be,{className:"w-4 h-4 text-gray-500 mr-2 flex-shrink-0"}),s.jsx("span",{className:"text-sm text-gray-700 truncate",children:R.filename}),s.jsxs("span",{className:"ml-2 text-xs text-gray-500 flex-shrink-0",children:["(",w(R.content),")"]})]}),s.jsx("button",{type:"button",onClick:()=>I(q),className:"ml-2 p-1 text-gray-400 hover:text-red-500 transition-colors",title:"Anhang entfernen",children:s.jsx(qt,{className:"w-4 h-4"})})]},q))}),s.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Max. 10 MB pro Datei, 25 MB gesamt"})]}),b&&s.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:b}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:A,children:"Abbrechen"}),s.jsxs(T,{onClick:O,disabled:S.isPending,children:[s.jsx(Fl,{className:"w-4 h-4 mr-2"}),S.isPending?"Wird gesendet...":"Senden"]})]})]})})}function ck({isOpen:e,onClose:t,email:n,customerId:r,onSuccess:a}){const[i,l]=j.useState(""),[o,c]=j.useState(null),d=ge(),{data:u,isLoading:h}=fe({queryKey:["contracts","customer",r],queryFn:()=>Oe.getAll({customerId:r}),enabled:e}),m=((u==null?void 0:u.data)||[]).filter(y=>{var N,E,P,I;if(!i)return!0;const v=i.toLowerCase();return y.contractNumber.toLowerCase().includes(v)||((E=(N=y.contractCategory)==null?void 0:N.name)==null?void 0:E.toLowerCase().includes(v))||((I=(P=y.provider)==null?void 0:P.name)==null?void 0:I.toLowerCase().includes(v))}),f=G({mutationFn:y=>Pe.assignToContract(n.id,y),onSuccess:(y,v)=>{d.invalidateQueries({queryKey:["emails"]}),d.invalidateQueries({queryKey:["email",n.id]}),d.invalidateQueries({queryKey:["contract-folder-counts",v]}),a==null||a(),p()}}),p=()=>{l(""),c(null),t()},b=()=>{o&&f.mutate(o)},g=y=>y?new Date(y).toLocaleDateString("de-DE"):"-";return s.jsx(qe,{isOpen:e,onClose:p,title:"E-Mail Vertrag zuordnen",size:"lg",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:"Betreff:"})," ",n.subject||"(Kein Betreff)"]}),s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:"Von:"})," ",n.fromAddress]})]}),s.jsxs("div",{className:"relative",children:[s.jsx(Tl,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),s.jsx("input",{type:"text",value:i,onChange:y=>l(y.target.value),placeholder:"Vertrag suchen...",className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),s.jsx("div",{className:"border border-gray-200 rounded-lg max-h-80 overflow-auto",children:h?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):m.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(Be,{className:"w-8 h-8 mb-2 opacity-50"}),s.jsx("p",{className:"text-sm",children:"Keine Verträge gefunden"})]}):s.jsx("div",{className:"divide-y divide-gray-200",children:m.map(y=>{var v;return s.jsx("div",{onClick:()=>c(y.id),className:` - flex items-center gap-3 p-3 cursor-pointer transition-colors - ${o===y.id?"bg-blue-50 border-l-2 border-l-blue-500":"hover:bg-gray-50"} - `,children:s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-medium text-gray-900",children:y.contractNumber}),s.jsx("span",{className:` - px-2 py-0.5 text-xs rounded-full - ${y.status==="ACTIVE"?"bg-green-100 text-green-800":y.status==="PENDING"?"bg-yellow-100 text-yellow-800":y.status==="CANCELLED"?"bg-red-100 text-red-800":"bg-gray-100 text-gray-800"} - `,children:y.status})]}),s.jsxs("div",{className:"text-sm text-gray-600 truncate",children:[(v=y.contractCategory)==null?void 0:v.name,y.provider&&` - ${y.provider.name}`]}),s.jsxs("div",{className:"text-xs text-gray-500",children:["Start: ",g(y.startDate)]})]})},y.id)})})}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:p,children:"Abbrechen"}),s.jsx(T,{onClick:b,disabled:!o||f.isPending,children:f.isPending?"Wird zugeordnet...":"Zuordnen"})]})]})})}function Ov({emails:e,selectedEmailId:t,onSelectEmail:n,onEmailRestored:r,onEmailDeleted:a,isLoading:i}){const[l,o]=j.useState(null),[c,d]=j.useState(null),u=ge(),h=P=>{if(P.folder==="SENT")try{const I=JSON.parse(P.toAddresses);if(I.length>0)return`An: ${I[0]}${I.length>1?` (+${I.length-1})`:""}`}catch{return"An: (Unbekannt)"}return P.fromName||P.fromAddress},x=G({mutationFn:P=>Pe.restore(P),onSuccess:(P,I)=>{u.invalidateQueries({queryKey:["emails"]}),Re.success("E-Mail wiederhergestellt"),o(null),d(null),r==null||r(I)},onError:P=>{console.error("Restore error:",P),Re.error(P.message||"Fehler beim Wiederherstellen"),o(null),d(null)}}),m=G({mutationFn:P=>Pe.permanentDelete(P),onSuccess:(P,I)=>{u.invalidateQueries({queryKey:["emails"]}),Re.success("E-Mail endgültig gelöscht"),o(null),d(null),a==null||a(I)},onError:P=>{console.error("Permanent delete error:",P),Re.error(P.message||"Fehler beim endgültigen Löschen"),o(null),d(null)}}),f=G({mutationFn:P=>Pe.unassignFromContract(P),onSuccess:()=>{u.invalidateQueries({queryKey:["emails"]}),Re.success("Vertragszuordnung aufgehoben")},onError:P=>{console.error("Unassign error:",P),Re.error(P.message||"Fehler beim Aufheben der Zuordnung")}}),p=(P,I)=>{P.stopPropagation(),f.mutate(I)},b=(P,I)=>{P.stopPropagation(),o(I),d("restore")},g=(P,I)=>{P.stopPropagation(),o(I),d("delete")},y=P=>{P.stopPropagation(),l&&c&&(c==="restore"?x.mutate(l):m.mutate(l))},v=P=>{P.stopPropagation(),o(null),d(null)},N=P=>new Date(P).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"}),E=P=>{if(!P)return"";const I=new Date(P),w=new Date;return I.toDateString()===w.toDateString()?`Gelöscht um ${I.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})}`:`Gelöscht am ${I.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})}`};return i?s.jsx("div",{className:"flex items-center justify-center h-64",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"})}):e.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[s.jsx(Ne,{className:"w-12 h-12 mb-2 opacity-50"}),s.jsx("p",{children:"Papierkorb ist leer"})]}):s.jsxs("div",{className:"divide-y divide-gray-200",children:[e.map(P=>s.jsxs("div",{onClick:()=>n(P),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",t===P.id?"bg-red-100":"hover:bg-gray-100 bg-gray-50/50"].join(" "),style:{borderLeft:t===P.id?"4px solid #dc2626":"4px solid transparent"},children:[s.jsx("div",{className:"flex-shrink-0 mt-1 p-1 -ml-1 text-gray-400",title:P.folder==="SENT"?"Aus Gesendet":"Aus Posteingang",children:P.folder==="SENT"?s.jsx(Fl,{className:"w-4 h-4"}):s.jsx(Ur,{className:"w-4 h-4"})}),s.jsx("button",{onClick:I=>b(I,P.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-green-100 text-gray-400 hover:text-green-600",title:"Wiederherstellen",children:s.jsx(Iv,{className:"w-4 h-4"})}),s.jsx("button",{onClick:I=>g(I,P.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"Endgültig löschen",children:s.jsx(Ne,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[s.jsx("span",{className:"text-sm truncate text-gray-700",children:h(P)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:N(P.receivedAt)})]}),s.jsx("div",{className:"text-sm truncate text-gray-600",children:P.subject||"(Kein Betreff)"}),s.jsx("div",{className:"text-xs text-red-500 mt-1",children:E(P.deletedAt)}),P.contract&&s.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[s.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:P.contract.contractNumber}),(P.folder==="INBOX"||P.folder==="SENT"&&!P.isAutoAssigned)&&s.jsx("button",{onClick:I=>p(I,P.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:f.isPending,children:s.jsx(qt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Ft,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},P.id)),l&&c&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:c==="restore"?"E-Mail wiederherstellen?":"E-Mail endgültig löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:c==="restore"?"Die E-Mail wird wieder in den ursprünglichen Ordner verschoben.":"Die E-Mail wird unwiderruflich gelöscht. Diese Aktion kann nicht rückgängig gemacht werden."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:v,disabled:x.isPending||m.isPending,children:"Abbrechen"}),s.jsx(T,{variant:c==="restore"?"primary":"danger",onClick:y,disabled:x.isPending||m.isPending,children:x.isPending||m.isPending?"Wird ausgeführt...":c==="restore"?"Wiederherstellen":"Endgültig löschen"})]})]})})]})}function dk({customerId:e}){const[t,n]=j.useState(null),[r,a]=j.useState("INBOX"),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,x]=j.useState(null),m=ge(),{hasPermission:f}=We(),p=f("emails:delete"),{data:b,isLoading:g}=fe({queryKey:["mailbox-accounts",e],queryFn:()=>Pe.getMailboxAccounts(e)}),y=(b==null?void 0:b.data)||[];j.useEffect(()=>{y.length>0&&!t&&n(y[0].id)},[y,t]);const v=y.find(de=>de.id===t),{data:N,isLoading:E,refetch:P}=fe({queryKey:["emails","customer",e,t,r],queryFn:()=>Pe.getForCustomer(e,{accountId:t||void 0,folder:r}),enabled:!!t&&r!=="TRASH"}),I=(N==null?void 0:N.data)||[],{data:w,isLoading:S}=fe({queryKey:["emails","trash",e],queryFn:()=>Pe.getTrash(e),enabled:r==="TRASH"&&p}),A=(w==null?void 0:w.data)||[],{data:O}=fe({queryKey:["folder-counts",t],queryFn:()=>xs.getFolderCounts(t),enabled:!!t}),R=(O==null?void 0:O.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0,trash:0,trashUnread:0},{data:q}=fe({queryKey:["email",i==null?void 0:i.id],queryFn:()=>Pe.getById(i.id),enabled:!!(i!=null&&i.id)}),D=(q==null?void 0:q.data)||i,z=G({mutationFn:de=>xs.syncEmails(de),onSuccess:()=>{m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]}),m.invalidateQueries({queryKey:["mailbox-accounts",e]})}}),k=()=>{t&&z.mutate(t)},K=de=>{l(de)},B=()=>{x(D||null),c(!0)},_=()=>{x(null),c(!0)},Q=()=>{u(!0)};if(!g&&y.length===0)return s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[s.jsx(nn,{className:"w-16 h-16 mb-4 opacity-30"}),s.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"Keine E-Mail-Konten vorhanden"}),s.jsx("p",{className:"text-sm text-center max-w-md",children:"Erstellen Sie eine Stressfrei-Wechseln E-Mail-Adresse mit aktivierter Mailbox, um E-Mails hier empfangen und versenden zu können."})]});const le=de=>{a(de),l(null)};return s.jsxs("div",{className:"flex flex-col h-full",style:{minHeight:"600px"},children:[s.jsxs("div",{className:"flex items-center justify-between gap-4 p-4 border-b border-gray-200 bg-gray-50",children:[y.length>1?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ur,{className:"w-5 h-5 text-gray-500"}),s.jsx("select",{value:t||"",onChange:de=>{n(Number(de.target.value)),l(null)},className:"px-3 py-2 border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",children:y.map(de=>s.jsx("option",{value:de.id,children:de.email},de.id))})]}):s.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:[s.jsx(Ur,{className:"w-5 h-5 text-gray-500"}),s.jsx("span",{children:v==null?void 0:v.email})]}),s.jsxs("div",{className:"flex items-center gap-1 bg-gray-200 rounded-lg p-1",children:[s.jsxs("button",{onClick:()=>le("INBOX"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="INBOX"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ur,{className:"w-4 h-4"}),"Posteingang",R.inbox>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${R.inboxUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${R.inboxUnread} ungelesen / ${R.inbox} gesamt`,children:R.inboxUnread>0?`${R.inboxUnread}/${R.inbox}`:R.inbox})]}),s.jsxs("button",{onClick:()=>le("SENT"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="SENT"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Fl,{className:"w-4 h-4"}),"Gesendet",R.sent>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${R.sentUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${R.sentUnread} ungelesen / ${R.sent} gesamt`,children:R.sentUnread>0?`${R.sentUnread}/${R.sent}`:R.sent})]}),p&&s.jsxs("button",{onClick:()=>le("TRASH"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="TRASH"?"bg-white text-red-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ne,{className:"w-4 h-4"}),"Papierkorb",R.trash>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${R.trashUnread>0?"bg-red-100 text-red-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${R.trashUnread} ungelesen / ${R.trash} gesamt`,children:R.trashUnread>0?`${R.trashUnread}/${R.trash}`:R.trash})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r!=="TRASH"&&s.jsxs(T,{variant:"secondary",size:"sm",onClick:k,disabled:z.isPending||!t,children:[s.jsx(Sr,{className:`w-4 h-4 mr-1 ${z.isPending?"animate-spin":""}`}),z.isPending?"Sync...":"Synchronisieren"]}),s.jsxs(T,{size:"sm",onClick:_,disabled:!v,children:[s.jsx(_e,{className:"w-4 h-4 mr-1"}),"Neue E-Mail"]})]})]}),s.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[s.jsx("div",{className:"w-1/3 border-r border-gray-200 overflow-auto",children:r==="TRASH"?s.jsx(Ov,{emails:A,selectedEmailId:i==null?void 0:i.id,onSelectEmail:K,onEmailRestored:de=>{(i==null?void 0:i.id)===de&&l(null),m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},onEmailDeleted:de=>{(i==null?void 0:i.id)===de&&l(null),m.invalidateQueries({queryKey:["emails","trash"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},isLoading:S}):s.jsx(ik,{emails:I,selectedEmailId:i==null?void 0:i.id,onSelectEmail:K,onEmailDeleted:de=>{(i==null?void 0:i.id)===de&&l(null),m.invalidateQueries({queryKey:["folder-counts",t]})},isLoading:E,folder:r,accountId:t})}),s.jsx("div",{className:"flex-1 overflow-auto",children:D?s.jsx(Rv,{email:D,onReply:B,onAssignContract:Q,onDeleted:()=>{l(null),m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},isSentFolder:r==="SENT",isTrashView:r==="TRASH",onRestored:()=>{l(null),m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["folder-counts",t]})},accountId:t||void 0}):s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500",children:[s.jsx(nn,{className:"w-12 h-12 mb-2 opacity-30"}),s.jsx("p",{children:"Wählen Sie eine E-Mail aus"})]})})]}),v&&s.jsx(Lv,{isOpen:o,onClose:()=>{c(!1),x(null)},account:v,replyTo:h||void 0,onSuccess:()=>{m.invalidateQueries({queryKey:["emails","customer",e,t,"SENT"]}),m.invalidateQueries({queryKey:["folder-counts",t]}),r==="SENT"&&P()}}),D&&s.jsx(ck,{isOpen:d,onClose:()=>u(!1),email:D,customerId:e,onSuccess:()=>{P()}})]})}function uk({contractId:e,customerId:t}){const[n,r]=j.useState(null),[a,i]=j.useState("INBOX"),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[x,m]=j.useState(null),f=ge(),{hasPermission:p}=We(),b=p("emails:delete"),{data:g,isLoading:y}=fe({queryKey:["mailbox-accounts",t],queryFn:()=>Pe.getMailboxAccounts(t)}),v=(g==null?void 0:g.data)||[];j.useEffect(()=>{v.length>0&&!n&&r(v[0].id)},[v,n]);const N=v.find(J=>J.id===n),{data:E,isLoading:P,refetch:I}=fe({queryKey:["emails","contract",e,a],queryFn:()=>Pe.getForContract(e,{folder:a}),enabled:a!=="TRASH"}),w=(E==null?void 0:E.data)||[],{data:S,isLoading:A}=fe({queryKey:["emails","trash",t],queryFn:()=>Pe.getTrash(t),enabled:a==="TRASH"&&b}),O=(S==null?void 0:S.data)||[],{data:R}=fe({queryKey:["contract-folder-counts",e],queryFn:()=>Pe.getContractFolderCounts(e)}),q=(R==null?void 0:R.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0},{data:D}=fe({queryKey:["folder-counts",n],queryFn:()=>xs.getFolderCounts(n),enabled:!!n&&b}),z=(D==null?void 0:D.data)||{trash:0,trashUnread:0},{data:k}=fe({queryKey:["email",l==null?void 0:l.id],queryFn:()=>Pe.getById(l.id),enabled:!!(l!=null&&l.id)}),K=(k==null?void 0:k.data)||l,B=G({mutationFn:J=>xs.syncEmails(J),onSuccess:()=>{f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]}),Re.success("Synchronisation abgeschlossen")},onError:J=>{Re.error(J.message||"Synchronisation fehlgeschlagen")}}),_=G({mutationFn:J=>Pe.toggleStar(J),onSuccess:(J,ue)=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["email",ue]})}}),Q=G({mutationFn:({emailId:J,isRead:ue})=>Pe.markAsRead(J,ue),onSuccess:(J,ue)=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["email",ue.emailId]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]})}}),le=G({mutationFn:J=>Pe.unassignFromContract(J),onSuccess:()=>{f.invalidateQueries({queryKey:["emails","contract",e]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),o(null),Re.success("Zuordnung aufgehoben")},onError:J=>{Re.error(J.message||"Fehler beim Aufheben der Zuordnung")}}),de=G({mutationFn:J=>Pe.delete(J),onSuccess:(J,ue)=>{f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]}),Re.success("E-Mail in Papierkorb verschoben"),m(null),(l==null?void 0:l.id)===ue&&o(null)},onError:J=>{Re.error(J.message||"Fehler beim Löschen der E-Mail"),m(null)}}),Ke=()=>{n&&B.mutate(n)},Ve=J=>{const ue=new Date(J),ts=new Date;return ue.toDateString()===ts.toDateString()?ue.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):ue.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},st=(J,ue)=>{J.stopPropagation(),_.mutate(ue)},C=(J,ue)=>{J.stopPropagation(),Q.mutate({emailId:ue.id,isRead:!ue.isRead})},nt=J=>{J.isRead||Q.mutate({emailId:J.id,isRead:!0}),o(J)},es=()=>{h(K||null),d(!0)},Vt=()=>{h(null),d(!0)},ae=(J,ue)=>{J.stopPropagation(),(l==null?void 0:l.id)===ue&&o(null),le.mutate(ue)},Ge=(J,ue)=>{J.stopPropagation(),m(ue)},xt=J=>{J.stopPropagation(),x&&de.mutate(x)},Z=J=>{J.stopPropagation(),m(null)},Fe=J=>{i(J),o(null)},Xe=J=>{if(a==="SENT")try{const ue=JSON.parse(J.toAddresses);if(ue.length>0)return`An: ${ue[0]}${ue.length>1?` (+${ue.length-1})`:""}`}catch{return"An: (Unbekannt)"}return J.fromName||J.fromAddress};return!y&&v.length===0?s.jsx(X,{title:"E-Mails",children:s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(nn,{className:"w-10 h-10 mb-2 opacity-30"}),s.jsx("p",{className:"text-sm",children:"Keine E-Mail-Konten vorhanden"}),s.jsx("p",{className:"text-xs mt-1",children:"Erstellen Sie eine E-Mail-Adresse beim Kunden mit aktivierter Mailbox"})]})}):s.jsxs(X,{title:s.jsx("div",{className:"flex items-center gap-4",children:s.jsx("span",{children:"E-Mails"})}),actions:s.jsxs("div",{className:"flex items-center gap-2",children:[a!=="TRASH"&&s.jsxs(T,{variant:"secondary",size:"sm",onClick:Ke,disabled:B.isPending||!n,children:[s.jsx(Sr,{className:`w-4 h-4 mr-1 ${B.isPending?"animate-spin":""}`}),B.isPending?"Sync...":"Sync"]}),N&&s.jsxs(T,{size:"sm",onClick:Vt,children:[s.jsx(_e,{className:"w-4 h-4 mr-1"}),"Neue E-Mail"]})]}),children:[s.jsxs("div",{className:"flex items-center justify-between gap-4 pb-4 border-b border-gray-200 -mt-2",children:[v.length>1?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ur,{className:"w-4 h-4 text-gray-500"}),s.jsx("select",{value:n||"",onChange:J=>{r(Number(J.target.value)),o(null)},className:"px-2 py-1.5 border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",children:v.map(J=>s.jsx("option",{value:J.id,children:J.email},J.id))})]}):s.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[s.jsx(Ur,{className:"w-4 h-4 text-gray-500"}),s.jsx("span",{children:N==null?void 0:N.email})]}),s.jsxs("div",{className:"flex items-center gap-1 bg-gray-200 rounded-lg p-1",children:[s.jsxs("button",{onClick:()=>Fe("INBOX"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${a==="INBOX"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ur,{className:"w-4 h-4"}),"Posteingang",q.inbox>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${q.inboxUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${q.inboxUnread} ungelesen / ${q.inbox} gesamt`,children:q.inboxUnread>0?`${q.inboxUnread}/${q.inbox}`:q.inbox})]}),s.jsxs("button",{onClick:()=>Fe("SENT"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${a==="SENT"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Fl,{className:"w-4 h-4"}),"Gesendet",q.sent>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${q.sentUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${q.sentUnread} ungelesen / ${q.sent} gesamt`,children:q.sentUnread>0?`${q.sentUnread}/${q.sent}`:q.sent})]}),b&&s.jsxs("button",{onClick:()=>Fe("TRASH"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${a==="TRASH"?"bg-white text-red-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[s.jsx(Ne,{className:"w-4 h-4"}),"Papierkorb",z.trash>0&&s.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${z.trashUnread>0?"bg-red-100 text-red-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${z.trashUnread} ungelesen / ${z.trash} gesamt`,children:z.trashUnread>0?`${z.trashUnread}/${z.trash}`:z.trash})]})]})]}),(a==="TRASH"?A:P)?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):(a==="TRASH"?O.length===0:w.length===0)?s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[s.jsx(nn,{className:"w-10 h-10 mb-2 opacity-30"}),s.jsx("p",{className:"text-sm",children:a==="INBOX"?"Keine E-Mails zugeordnet":a==="SENT"?"Keine E-Mails über diesen Vertrag gesendet":"Papierkorb ist leer"}),a==="INBOX"&&s.jsx("p",{className:"text-xs mt-1",children:"E-Mails können im E-Mail-Tab des Kunden zugeordnet werden"})]}):s.jsxs("div",{className:"flex -mx-6 -mb-6",style:{minHeight:"400px"},children:[s.jsx("div",{className:"w-1/3 border-r border-gray-200 overflow-auto",children:a==="TRASH"?s.jsx(Ov,{emails:O,selectedEmailId:l==null?void 0:l.id,onSelectEmail:nt,onEmailRestored:J=>{(l==null?void 0:l.id)===J&&o(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["folder-counts",n]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]})},onEmailDeleted:J=>{(l==null?void 0:l.id)===J&&o(null),f.invalidateQueries({queryKey:["emails","trash"]}),f.invalidateQueries({queryKey:["folder-counts",n]})},isLoading:A}):s.jsx("div",{className:"divide-y divide-gray-200",children:w.map(J=>s.jsxs("div",{onClick:()=>nt(J),className:["flex items-start gap-2 p-3 cursor-pointer transition-colors",(l==null?void 0:l.id)===J.id?"bg-blue-100":["hover:bg-gray-100",J.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:(l==null?void 0:l.id)===J.id?"4px solid #2563eb":"4px solid transparent"},children:[s.jsx("button",{onClick:ue=>C(ue,J),className:` - flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 - ${J.isRead?"text-gray-400":"text-blue-600"} - `,title:J.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:J.isRead?s.jsx(Av,{className:"w-4 h-4"}):s.jsx(nn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:ue=>st(ue,J.id),className:` - flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 - ${J.isStarred?"text-yellow-500":"text-gray-400"} - `,title:J.isStarred?"Stern entfernen":"Als wichtig markieren",children:s.jsx(fh,{className:`w-4 h-4 ${J.isStarred?"fill-current":""}`})}),p("emails:delete")&&s.jsx("button",{onClick:ue=>Ge(ue,J.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"E-Mail löschen",children:s.jsx(Ne,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[s.jsx("span",{className:`text-sm truncate ${J.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:Xe(J)}),s.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:Ve(J.receivedAt)})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm truncate ${J.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:J.subject||"(Kein Betreff)"}),J.hasAttachments&&s.jsx(Rc,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),J.contract&&s.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[s.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:J.contract.contractNumber}),(a==="INBOX"||a==="SENT"&&!J.isAutoAssigned)&&s.jsx("button",{onClick:ue=>ae(ue,J.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:le.isPending,children:s.jsx(qt,{className:"w-3.5 h-3.5"})})]})]}),s.jsx(Ft,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},J.id))})}),s.jsx("div",{className:"flex-1 overflow-auto",children:K&&l?s.jsx(Rv,{email:K,onReply:es,onAssignContract:()=>{},onDeleted:()=>{o(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]})},isSentFolder:a==="SENT",isContractView:a!=="TRASH",isTrashView:a==="TRASH",onRestored:()=>{o(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),n&&f.invalidateQueries({queryKey:["folder-counts",n]})},accountId:K==null?void 0:K.stressfreiEmailId}):s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500",children:[s.jsx(nn,{className:"w-12 h-12 mb-2 opacity-30"}),s.jsx("p",{children:"Wählen Sie eine E-Mail aus"})]})})]}),x&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),s.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:Z,disabled:de.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"danger",onClick:xt,disabled:de.isPending,children:de.isPending?"Löschen...":"Löschen"})]})]})}),N&&s.jsx(Lv,{isOpen:c,onClose:()=>{d(!1),h(null)},account:N,replyTo:u||void 0,contractId:e,onSuccess:()=>{f.invalidateQueries({queryKey:["emails","contract",e,"SENT"]}),f.invalidateQueries({queryKey:["contract-folder-counts",e]}),a==="SENT"&&I()}})]})}function mk({tabs:e,defaultTab:t}){var a,i;const[n,r]=j.useState(t||((a=e[0])==null?void 0:a.id));return s.jsxs("div",{children:[s.jsx("div",{className:"border-b border-gray-200",children:s.jsx("nav",{className:"flex -mb-px space-x-8",children:e.map(l=>s.jsx("button",{onClick:()=>r(l.id),className:`py-4 px-1 border-b-2 font-medium text-sm whitespace-nowrap ${n===l.id?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:l.label},l.id))})}),s.jsx("div",{className:"mt-4",children:(i=e.find(l=>l.id===n))==null?void 0:i.content})]})}function Dt({onUpload:e,existingFile:t,accept:n=".pdf,.jpg,.jpeg,.png",label:r="Dokument hochladen",disabled:a=!1}){const i=j.useRef(null),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=async p=>{if(p){o(!0);try{await e(p)}catch(b){console.error("Upload failed:",b),alert("Upload fehlgeschlagen")}finally{o(!1)}}},h=p=>{var g;const b=(g=p.target.files)==null?void 0:g[0];b&&u(b)},x=p=>{var g;p.preventDefault(),d(!1);const b=(g=p.dataTransfer.files)==null?void 0:g[0];b&&u(b)},m=p=>{p.preventDefault(),d(!0)},f=()=>{d(!1)};return s.jsxs("div",{className:"space-y-2",children:[t?!a&&s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>{var p;return(p=i.current)==null?void 0:p.click()},disabled:l,children:l?"Wird hochgeladen...":"Ersetzen"}):s.jsx("div",{className:`border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${c?"border-blue-500 bg-blue-50":"border-gray-300 hover:border-gray-400"} ${a?"opacity-50 cursor-not-allowed":""}`,onClick:()=>{var p;return!a&&((p=i.current)==null?void 0:p.click())},onDrop:a?void 0:x,onDragOver:a?void 0:m,onDragLeave:a?void 0:f,children:l?s.jsxs("div",{className:"text-gray-500",children:[s.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"}),"Wird hochgeladen..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Hu,{className:"w-6 h-6 text-gray-400 mx-auto mb-2"}),s.jsx("p",{className:"text-sm text-gray-600",children:r}),s.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"PDF, JPG oder PNG (max. 10MB)"})]})}),s.jsx("input",{ref:i,type:"file",accept:n,onChange:h,className:"hidden",disabled:a||l})]})}function oe({value:e,className:t="",size:n="sm",title:r="In Zwischenablage kopieren"}){const[a,i]=j.useState(!1),l=async c=>{c.preventDefault(),c.stopPropagation();try{await navigator.clipboard.writeText(e),i(!0),setTimeout(()=>i(!1),1500)}catch(d){console.error("Failed to copy:",d)}},o=n==="sm"?"w-3.5 h-3.5":"w-4 h-4";return s.jsx("button",{type:"button",onClick:l,className:`inline-flex items-center justify-center p-1 rounded transition-colors ${a?"text-green-600 bg-green-50":"text-gray-400 hover:text-blue-600 hover:bg-blue-50"} ${t}`,title:a?"Kopiert!":r,children:a?s.jsx(xr,{className:o}):s.jsx(oh,{className:o})})}function Wu({values:e,separator:t=` -`,children:n,className:r=""}){const a=e.filter(i=>i!=null&&i!=="").map(String).join(t);return a?s.jsxs("div",{className:`relative group ${r}`,children:[n,s.jsx(oe,{value:a,className:"absolute top-0 right-0 opacity-60 group-hover:opacity-100",title:"Alles kopieren"})]}):s.jsx(s.Fragment,{children:n})}function hk(){var B,_;const{id:e}=Nc(),t=Yt(),n=ge(),{hasPermission:r}=We(),[a]=Sc(),i=parseInt(e),l=a.get("tab")||"addresses",[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,x]=j.useState(!1),[m,f]=j.useState(!1),[p,b]=j.useState(!1),[g,y]=j.useState(!1),[v,N]=j.useState(null),[E,P]=j.useState(null),[I,w]=j.useState(null),[S,A]=j.useState(null),[O,R]=j.useState(null),{data:q,isLoading:D}=fe({queryKey:["customer",e],queryFn:()=>At.getById(i)}),z=G({mutationFn:()=>At.delete(i),onSuccess:()=>{t("/customers")}});if(D)return s.jsx("div",{className:"text-center py-8",children:"Laden..."});if(!(q!=null&&q.data))return s.jsx("div",{className:"text-center py-8 text-red-600",children:"Kunde nicht gefunden"});const k=q.data,K=[{id:"addresses",label:"Adressen",content:s.jsx(xk,{customerId:i,addresses:k.addresses||[],canEdit:r("customers:update"),onAdd:()=>c(!0),onEdit:Q=>w(Q)})},{id:"bankcards",label:"Bankkarten",content:s.jsx(gk,{customerId:i,bankCards:k.bankCards||[],canEdit:r("customers:update"),showInactive:g,onToggleInactive:()=>y(!g),onAdd:()=>u(!0),onEdit:Q=>N(Q)})},{id:"documents",label:"Ausweise",content:s.jsx(yk,{customerId:i,documents:k.identityDocuments||[],canEdit:r("customers:update"),showInactive:g,onToggleInactive:()=>y(!g),onAdd:()=>x(!0),onEdit:Q=>P(Q)})},{id:"meters",label:"Zähler",content:s.jsx(vk,{customerId:i,meters:k.meters||[],canEdit:r("customers:update"),showInactive:g,onToggleInactive:()=>y(!g),onAdd:()=>f(!0),onEdit:Q=>A(Q)})},{id:"stressfrei",label:"Stressfrei-Wechseln",content:s.jsx(wk,{customerId:i,emails:k.stressfreiEmails||[],canEdit:r("customers:update"),showInactive:g,onToggleInactive:()=>y(!g),onAdd:()=>b(!0),onEdit:Q=>R(Q)})},{id:"emails",label:"E-Mail-Postfach",content:s.jsx(dk,{customerId:i})},{id:"contracts",label:"Verträge",content:s.jsx(jk,{customerId:i})},...r("customers:update")?[{id:"portal",label:"Portal",content:s.jsx(Nk,{customerId:i,canEdit:r("customers:update")})}]:[]];return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold",children:k.type==="BUSINESS"&&k.companyName?k.companyName:`${k.firstName} ${k.lastName}`}),s.jsxs("p",{className:"text-gray-500 font-mono flex items-center gap-1",children:[k.customerNumber,s.jsx(oe,{value:k.customerNumber})]})]}),s.jsxs("div",{className:"flex gap-2",children:[r("customers:update")&&s.jsx(ke,{to:`/customers/${e}/edit`,children:s.jsxs(T,{variant:"secondary",children:[s.jsx(He,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),r("customers:delete")&&s.jsxs(T,{variant:"danger",onClick:()=>{confirm("Kunde wirklich löschen?")&&z.mutate()},children:[s.jsx(Ne,{className:"w-4 h-4 mr-2"}),"Löschen"]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6",children:[s.jsx(X,{title:"Stammdaten",className:"lg:col-span-2",children:s.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Typ"}),s.jsx("dd",{children:s.jsx(ve,{variant:k.type==="BUSINESS"?"info":"default",children:k.type==="BUSINESS"?"Geschäftskunde":"Privatkunde"})})]}),k.salutation&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anrede"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.salutation,s.jsx(oe,{value:k.salutation})]})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorname"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.firstName,s.jsx(oe,{value:k.firstName})]})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Nachname"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.lastName,s.jsx(oe,{value:k.lastName})]})]}),k.companyName&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Firma"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.companyName,s.jsx(oe,{value:k.companyName})]})]}),k.foundingDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Gründungsdatum"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[new Date(k.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),s.jsx(oe,{value:new Date(k.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),k.birthDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Geburtsdatum"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[new Date(k.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),s.jsx(oe,{value:new Date(k.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),k.birthPlace&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Geburtsort"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[k.birthPlace,s.jsx(oe,{value:k.birthPlace})]})]})]})}),s.jsx(X,{title:"Kontakt",children:s.jsxs("dl",{className:"space-y-3",children:[k.email&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"E-Mail"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[s.jsx("a",{href:`mailto:${k.email}`,className:"text-blue-600 hover:underline",children:k.email}),s.jsx(oe,{value:k.email})]})]}),k.phone&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Telefon"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[s.jsx("a",{href:`tel:${k.phone}`,className:"text-blue-600 hover:underline",children:k.phone}),s.jsx(oe,{value:k.phone})]})]}),k.mobile&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Mobil"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[s.jsx("a",{href:`tel:${k.mobile}`,className:"text-blue-600 hover:underline",children:k.mobile}),s.jsx(oe,{value:k.mobile})]})]})]})})]}),k.type==="BUSINESS"&&s.jsx(fk,{customer:k,canEdit:r("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",e]})}),s.jsx(pk,{customer:k,canEdit:r("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",e]})}),k.notes&&s.jsx(X,{title:"Notizen",className:"mb-6",children:s.jsx("p",{className:"whitespace-pre-wrap",children:k.notes})}),s.jsx(X,{children:s.jsx(mk,{tabs:K,defaultTab:l})}),s.jsx(xx,{isOpen:o,onClose:()=>c(!1),customerId:i}),s.jsx(xx,{isOpen:!!I,onClose:()=>w(null),customerId:i,address:I}),s.jsx(gx,{isOpen:d,onClose:()=>u(!1),customerId:i}),s.jsx(gx,{isOpen:!!v,onClose:()=>N(null),customerId:i,bankCard:v}),s.jsx(yx,{isOpen:h,onClose:()=>x(!1),customerId:i}),s.jsx(yx,{isOpen:!!E,onClose:()=>P(null),customerId:i,document:E}),s.jsx(vx,{isOpen:m,onClose:()=>f(!1),customerId:i}),s.jsx(vx,{isOpen:!!S,onClose:()=>A(null),customerId:i,meter:S}),s.jsx(bx,{isOpen:p,onClose:()=>b(!1),customerId:i,customerEmail:(B=q==null?void 0:q.data)==null?void 0:B.email}),s.jsx(bx,{isOpen:!!O,onClose:()=>R(null),customerId:i,email:O,customerEmail:(_=q==null?void 0:q.data)==null?void 0:_.email})]})}function fk({customer:e,canEdit:t,onUpdate:n}){const r=async c=>{try{await ut.uploadBusinessRegistration(e.id,c),n()}catch(d){console.error("Upload fehlgeschlagen:",d),alert("Upload fehlgeschlagen")}},a=async()=>{if(confirm("Gewerbeanmeldung wirklich löschen?"))try{await ut.deleteBusinessRegistration(e.id),n()}catch(c){console.error("Löschen fehlgeschlagen:",c),alert("Löschen fehlgeschlagen")}},i=async c=>{try{await ut.uploadCommercialRegister(e.id,c),n()}catch(d){console.error("Upload fehlgeschlagen:",d),alert("Upload fehlgeschlagen")}},l=async()=>{if(confirm("Handelsregisterauszug wirklich löschen?"))try{await ut.deleteCommercialRegister(e.id),n()}catch(c){console.error("Löschen fehlgeschlagen:",c),alert("Löschen fehlgeschlagen")}};return!(e.taxNumber||e.commercialRegisterNumber||e.businessRegistrationPath||e.commercialRegisterPath)&&!t?null:s.jsxs(X,{title:"Geschäftsdaten",className:"mb-6",children:[s.jsxs("dl",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.taxNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Steuernummer"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[e.taxNumber,s.jsx(oe,{value:e.taxNumber})]})]}),e.commercialRegisterNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Handelsregisternummer"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[e.commercialRegisterNumber,s.jsx(oe,{value:e.commercialRegisterNumber})]})]})]}),s.jsxs("div",{className:"mt-4 pt-4 border-t grid grid-cols-1 md:grid-cols-2 gap-6",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Gewerbeanmeldung"}),e.businessRegistrationPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${e.businessRegistrationPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${e.businessRegistrationPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(Dt,{onUpload:r,existingFile:e.businessRegistrationPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:a,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(Dt,{onUpload:r,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Handelsregisterauszug"}),e.commercialRegisterPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${e.commercialRegisterPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${e.commercialRegisterPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(Dt,{onUpload:i,existingFile:e.commercialRegisterPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:l,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(Dt,{onUpload:i,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})]})]})}function pk({customer:e,canEdit:t,onUpdate:n}){const r=async i=>{try{await ut.uploadPrivacyPolicy(e.id,i),n()}catch(l){console.error("Upload fehlgeschlagen:",l),alert("Upload fehlgeschlagen")}},a=async()=>{if(confirm("Datenschutzerklärung wirklich löschen?"))try{await ut.deletePrivacyPolicy(e.id),n()}catch(i){console.error("Löschen fehlgeschlagen:",i),alert("Löschen fehlgeschlagen")}};return!e.privacyPolicyPath&&!t?null:s.jsx(X,{title:"Dokumente",className:"mb-6",children:s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Datenschutzerklärung"}),e.privacyPolicyPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${e.privacyPolicyPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${e.privacyPolicyPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),t&&s.jsxs(s.Fragment,{children:[s.jsx(Dt,{onUpload:r,existingFile:e.privacyPolicyPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:a,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]})]}):t?s.jsx(Dt,{onUpload:r,accept:".pdf",label:"PDF hochladen"}):s.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})})}function xk({customerId:e,addresses:t,canEdit:n,onAdd:r,onEdit:a}){const i=ge(),l=G({mutationFn:Qu.delete,onSuccess:()=>i.invalidateQueries({queryKey:["customer",e.toString()]})});return s.jsxs("div",{children:[n&&s.jsx("div",{className:"mb-4",children:s.jsxs(T,{size:"sm",onClick:r,children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Adresse hinzufügen"]})}),t.length>0?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.map(o=>s.jsxs("div",{className:"border rounded-lg p-4",children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(BS,{className:"w-4 h-4 text-gray-400"}),s.jsx(ve,{variant:o.type==="BILLING"?"info":"default",children:o.type==="BILLING"?"Rechnung":"Liefer-/Meldeadresse"}),o.isDefault&&s.jsx(ve,{variant:"success",children:"Standard"})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>a(o),title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&l.mutate(o.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs(Wu,{values:[`${o.street} ${o.houseNumber}`,`${o.postalCode} ${o.city}`,o.country],children:[s.jsxs("p",{children:[o.street," ",o.houseNumber]}),s.jsxs("p",{children:[o.postalCode," ",o.city]}),s.jsx("p",{className:"text-gray-500",children:o.country})]})]},o.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Adressen vorhanden."})]})}function gk({customerId:e,bankCards:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=ge(),c=G({mutationFn:({id:m,data:f})=>Yo.update(m,f),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=G({mutationFn:Yo.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=async(m,f)=>{try{await ut.uploadBankCardDocument(m,f),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(p){console.error("Upload fehlgeschlagen:",p),alert("Upload fehlgeschlagen")}},h=async m=>{if(confirm("Dokument wirklich löschen?"))try{await ut.deleteBankCardDocument(m),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(f){console.error("Löschen fehlgeschlagen:",f),alert("Löschen fehlgeschlagen")}},x=r?t:t.filter(m=>m.isActive);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(T,{size:"sm",onClick:i,children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Bankkarte hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),x.length>0?s.jsx("div",{className:"space-y-4",children:x.map(m=>s.jsxs("div",{className:`border rounded-lg p-4 ${m.isActive?"":"opacity-50 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(ch,{className:"w-4 h-4 text-gray-400"}),!m.isActive&&s.jsx(ve,{variant:"danger",children:"Inaktiv"}),m.expiryDate&&new Date(m.expiryDate)l(m),title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),m.isActive?s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte deaktivieren?")&&c.mutate({id:m.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wieder aktivieren?")&&c.mutate({id:m.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wirklich löschen?")&&d.mutate(m.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-medium flex items-center gap-1",children:[m.accountHolder,s.jsx(oe,{value:m.accountHolder})]}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[m.iban,s.jsx(oe,{value:m.iban})]}),m.bic&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["BIC: ",m.bic,s.jsx(oe,{value:m.bic})]}),m.bankName&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:[m.bankName,s.jsx(oe,{value:m.bankName})]}),m.expiryDate&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Gültig bis: ",new Date(m.expiryDate).toLocaleDateString("de-DE")]}),s.jsx("div",{className:"mt-3 pt-3 border-t",children:m.documentPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${m.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${m.documentPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),n&&s.jsxs(s.Fragment,{children:[s.jsx(Dt,{onUpload:f=>u(m.id,f),existingFile:m.documentPath,accept:".pdf",label:"Ersetzen",disabled:!m.isActive}),s.jsxs("button",{onClick:()=>h(m.id),className:"text-red-600 hover:underline text-sm flex items-center gap-1",title:"Dokument löschen",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&m.isActive&&s.jsx(Dt,{onUpload:f=>u(m.id,f),accept:".pdf",label:"PDF hochladen"})})]},m.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Bankkarten vorhanden."})]})}function yk({customerId:e,documents:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=ge(),c=G({mutationFn:({id:f,data:p})=>ec.update(f,p),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=G({mutationFn:ec.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=async(f,p)=>{try{await ut.uploadIdentityDocument(f,p),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(b){console.error("Upload fehlgeschlagen:",b),alert("Upload fehlgeschlagen")}},h=async f=>{if(confirm("Dokument wirklich löschen?"))try{await ut.deleteIdentityDocument(f),o.invalidateQueries({queryKey:["customer",e.toString()]})}catch(p){console.error("Löschen fehlgeschlagen:",p),alert("Löschen fehlgeschlagen")}},x=r?t:t.filter(f=>f.isActive),m={ID_CARD:"Personalausweis",PASSPORT:"Reisepass",DRIVERS_LICENSE:"Führerschein",OTHER:"Sonstiges"};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(T,{size:"sm",onClick:i,children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Ausweis hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),x.length>0?s.jsx("div",{className:"space-y-4",children:x.map(f=>s.jsxs("div",{className:`border rounded-lg p-4 ${f.isActive?"":"opacity-50 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(Be,{className:"w-4 h-4 text-gray-400"}),s.jsx(ve,{children:m[f.type]}),!f.isActive&&s.jsx(ve,{variant:"danger",children:"Inaktiv"}),f.expiryDate&&new Date(f.expiryDate)l(f),title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),f.isActive?s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis deaktivieren?")&&c.mutate({id:f.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wieder aktivieren?")&&c.mutate({id:f.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wirklich löschen?")&&d.mutate(f.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[f.documentNumber,s.jsx(oe,{value:f.documentNumber})]}),f.issuingAuthority&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Ausgestellt von: ",f.issuingAuthority,s.jsx(oe,{value:f.issuingAuthority})]}),f.expiryDate&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Gültig bis: ",new Date(f.expiryDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})]}),f.type==="DRIVERS_LICENSE"&&f.licenseClasses&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Klassen: ",f.licenseClasses,s.jsx(oe,{value:f.licenseClasses})]}),f.type==="DRIVERS_LICENSE"&&f.licenseIssueDate&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Klasse B seit: ",new Date(f.licenseIssueDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})]}),s.jsx("div",{className:"mt-3 pt-3 border-t",children:f.documentPath?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("a",{href:`/api${f.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${f.documentPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),n&&s.jsxs(s.Fragment,{children:[s.jsx(Dt,{onUpload:p=>u(f.id,p),existingFile:f.documentPath,accept:".pdf",label:"Ersetzen",disabled:!f.isActive}),s.jsxs("button",{onClick:()=>h(f.id),className:"text-red-600 hover:underline text-sm flex items-center gap-1",title:"Dokument löschen",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&f.isActive&&s.jsx(Dt,{onUpload:p=>u(f.id,p),accept:".pdf",label:"PDF hochladen"})})]},f.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Ausweise vorhanden."})]})}function vk({customerId:e,meters:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const[o,c]=j.useState(null),[d,u]=j.useState(null),[h,x]=j.useState(null),m=ge(),f=G({mutationFn:({id:v,data:N})=>ln.update(v,N),onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),p=G({mutationFn:ln.delete,onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),b=G({mutationFn:({meterId:v,readingId:N})=>ln.deleteReading(v,N),onSuccess:()=>m.invalidateQueries({queryKey:["customer",e.toString()]})}),g=r?t:t.filter(v=>v.isActive),y=v=>v?[...v].sort((N,E)=>new Date(E.readingDate).getTime()-new Date(N.readingDate).getTime()):[];return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(T,{size:"sm",onClick:i,children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Zähler hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),g.length>0?s.jsx("div",{className:"space-y-4",children:g.map(v=>{const N=y(v.readings),E=d===v.id;return s.jsxs("div",{className:`border rounded-lg p-4 ${v.isActive?"":"opacity-50 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(Ev,{className:"w-4 h-4 text-gray-400"}),s.jsx(ve,{variant:v.type==="ELECTRICITY"?"warning":"info",children:v.type==="ELECTRICITY"?"Strom":"Gas"}),!v.isActive&&s.jsx(ve,{variant:"danger",children:"Inaktiv"})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[v.isActive&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>c({meterId:v.id,meterType:v.type}),title:"Zählerstand hinzufügen",children:s.jsx(_e,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>l(v),title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),v.isActive?s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler deaktivieren?")&&f.mutate({id:v.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wieder aktivieren?")&&f.mutate({id:v.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wirklich löschen? Alle Zählerstände werden ebenfalls gelöscht.")&&p.mutate(v.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]}),s.jsxs("p",{className:"font-mono text-lg flex items-center gap-1",children:[v.meterNumber,s.jsx(oe,{value:v.meterNumber})]}),v.location&&s.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Standort: ",v.location,s.jsx(oe,{value:v.location})]}),N.length>0&&s.jsxs("div",{className:"mt-3 pt-3 border-t",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("p",{className:"text-sm font-medium",children:"Zählerstände:"}),N.length>3&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>u(E?null:v.id),children:E?"Weniger anzeigen":`Alle ${N.length} anzeigen`})]}),s.jsx("div",{className:"space-y-1",children:(E?N:N.slice(0,3)).map(P=>s.jsxs("div",{className:"flex justify-between items-center text-sm group",children:[s.jsxs("span",{className:"text-gray-500 flex items-center gap-1",children:[new Date(P.readingDate).toLocaleDateString("de-DE"),s.jsx(oe,{value:new Date(P.readingDate).toLocaleDateString("de-DE")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[P.value.toLocaleString("de-DE")," ",P.unit,s.jsx(oe,{value:P.value.toString(),title:"Nur Wert kopieren"}),s.jsx(oe,{value:`${P.value.toLocaleString("de-DE")} ${P.unit}`,title:"Mit Einheit kopieren"})]}),n&&s.jsxs("div",{className:"opacity-0 group-hover:opacity-100 flex gap-1",children:[s.jsx("button",{onClick:()=>x({meterId:v.id,meterType:v.type,reading:P}),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(He,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&b.mutate({meterId:v.id,readingId:P.id})},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:s.jsx(Ne,{className:"w-3 h-3"})})]})]})]},P.id))})]})]},v.id)})}):s.jsx("p",{className:"text-gray-500",children:"Keine Zähler vorhanden."}),o&&s.jsx(jx,{isOpen:!0,onClose:()=>c(null),meterId:o.meterId,meterType:o.meterType,customerId:e}),h&&s.jsx(jx,{isOpen:!0,onClose:()=>x(null),meterId:h.meterId,meterType:h.meterType,customerId:e,reading:h.reading})]})}function jk({customerId:e}){const{hasPermission:t}=We(),n=Yt(),r=ge(),[a,i]=j.useState(new Set),[l,o]=j.useState(!1),{data:c,isLoading:d}=fe({queryKey:["contract-tree",e],queryFn:()=>Oe.getTreeForCustomer(e)}),u=(c==null?void 0:c.data)||[],h=G({mutationFn:Oe.delete,onSuccess:()=>{r.invalidateQueries({queryKey:["customer",e.toString()]}),r.invalidateQueries({queryKey:["customers"]}),r.invalidateQueries({queryKey:["contracts"]}),r.invalidateQueries({queryKey:["contract-tree",e]})},onError:y=>{alert((y==null?void 0:y.message)||"Fehler beim Löschen des Vertrags")}}),x={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},m={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},f=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}],p=y=>{i(v=>{const N=new Set(v);return N.has(y)?N.delete(y):N.add(y),N})},b=(y,v)=>y.map(N=>s.jsx("div",{children:g(N,v)},N.contract.id)),g=(y,v=0)=>{var S,A,O,R,q,D,z;const{contract:N,predecessors:E,hasHistory:P}=y,I=a.has(N.id),w=v>0;return s.jsxs("div",{children:[s.jsxs("div",{className:` - border rounded-lg p-4 transition-colors - ${w?"ml-6 border-l-4 border-l-gray-300 bg-gray-50":"hover:bg-gray-50"} - `,children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[!w&&P?s.jsx("button",{onClick:()=>p(N.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:I?"Einklappen":"Vorgänger anzeigen",children:I?s.jsx(dn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"})}):w?null:s.jsx("div",{className:"w-6"}),s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[N.contractNumber,s.jsx(oe,{value:N.contractNumber})]}),s.jsx(ve,{children:x[N.type]||N.type}),s.jsx(ve,{variant:m[N.status]||"default",children:N.status}),v===0&&!w&&s.jsx("button",{onClick:k=>{k.stopPropagation(),o(!0)},className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Ml,{className:"w-4 h-4"})}),w&&s.jsx("span",{className:"text-xs text-gray-500 ml-2",children:"(Vorgänger)"})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${N.id}`,{state:{from:"customer",customerId:e.toString()}}),title:"Ansehen",children:s.jsx(Ae,{className:"w-4 h-4"})}),t("contracts:update")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${N.id}/edit`),title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),t("contracts:delete")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&h.mutate(N.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]}),(N.providerName||((S=N.provider)==null?void 0:S.name))&&s.jsxs("p",{className:`flex items-center gap-1 ${w?"ml-6":""}`,children:[N.providerName||((A=N.provider)==null?void 0:A.name),(N.tariffName||((O=N.tariff)==null?void 0:O.name))&&` - ${N.tariffName||((R=N.tariff)==null?void 0:R.name)}`,s.jsx(oe,{value:(N.providerName||((q=N.provider)==null?void 0:q.name)||"")+(N.tariffName||(D=N.tariff)!=null&&D.name?` - ${N.tariffName||((z=N.tariff)==null?void 0:z.name)}`:"")})]}),N.startDate&&s.jsxs("p",{className:`text-sm text-gray-500 ${w?"ml-6":""}`,children:["Beginn: ",new Date(N.startDate).toLocaleDateString("de-DE"),N.endDate&&` | Ende: ${new Date(N.endDate).toLocaleDateString("de-DE")}`]})]}),(v===0&&I||v>0)&&E.length>0&&s.jsx("div",{className:"mt-2",children:b(E,v+1)})]},N.id)};return d?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):s.jsxs("div",{children:[t("contracts:create")&&s.jsx("div",{className:"mb-4",children:s.jsx(ke,{to:`/contracts/new?customerId=${e}`,children:s.jsxs(T,{size:"sm",children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Vertrag anlegen"]})})}),u.length>0?s.jsx("div",{className:"space-y-4",children:u.map(y=>g(y,0))}):s.jsx("p",{className:"text-gray-500",children:"Keine Verträge vorhanden."}),l&&s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:()=>o(!1)}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:()=>o(!1),className:"text-gray-400 hover:text-gray-600",children:s.jsx(qt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:f.map(({status:y,label:v,description:N,color:E})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${E}`,children:v}),s.jsx("span",{className:"text-sm text-gray-600",children:N})]},y))})]})]})]})}function bk({customerId:e}){const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1),o=async()=>{var c;if(t){n(!1);return}l(!0);try{const d=await At.getPortalPassword(e);a(((c=d.data)==null?void 0:c.password)||null),n(!0)}catch(d){console.error("Fehler beim Laden des Passworts:",d),alert("Fehler beim Laden des Passworts")}finally{l(!1)}};return s.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[s.jsx("p",{className:"text-xs text-green-600",children:"Passwort ist gesetzt"}),s.jsx("button",{type:"button",onClick:o,className:"text-xs text-blue-600 hover:underline flex items-center gap-1",disabled:i,children:i?"Laden...":t?s.jsxs(s.Fragment,{children:[s.jsx(It,{className:"w-3 h-3"}),"Verbergen"]}):s.jsxs(s.Fragment,{children:[s.jsx(Ae,{className:"w-3 h-3"}),"Anzeigen"]})}),t&&r&&s.jsxs("span",{className:"text-xs font-mono bg-gray-100 px-2 py-1 rounded flex items-center gap-1",children:[r,s.jsx(oe,{value:r})]}),t&&!r&&s.jsx("span",{className:"text-xs text-gray-500",children:"(Passwort nicht verfügbar)"})]})}function Nk({customerId:e,canEdit:t}){const n=ge(),[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,x]=j.useState(!1),{data:m,isLoading:f}=fe({queryKey:["customer-portal",e],queryFn:()=>At.getPortalSettings(e)}),{data:p,isLoading:b}=fe({queryKey:["customer-representatives",e],queryFn:()=>At.getRepresentatives(e)}),g=G({mutationFn:w=>At.updatePortalSettings(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-portal",e]})}}),y=G({mutationFn:w=>At.setPortalPassword(e,w),onSuccess:()=>{l(""),n.invalidateQueries({queryKey:["customer-portal",e]}),alert("Passwort wurde gesetzt")},onError:w=>{alert(w.message)}}),v=G({mutationFn:w=>At.addRepresentative(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",e]}),c(""),u([])},onError:w=>{alert(w.message)}}),N=G({mutationFn:w=>At.removeRepresentative(e,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",e]})}}),E=async()=>{if(!(o.length<2)){x(!0);try{const w=await At.searchForRepresentative(e,o);u(w.data||[])}catch(w){console.error("Suche fehlgeschlagen:",w)}finally{x(!1)}}};if(f||b)return s.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."});const P=m==null?void 0:m.data,I=(p==null?void 0:p.data)||[];return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"border rounded-lg p-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(uh,{className:"w-5 h-5 text-gray-400"}),s.jsx("h3",{className:"font-medium",children:"Portal-Zugang"})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("label",{className:"flex items-center gap-3",children:[s.jsx("input",{type:"checkbox",checked:(P==null?void 0:P.portalEnabled)||!1,onChange:w=>g.mutate({portalEnabled:w.target.checked}),className:"rounded w-5 h-5",disabled:!t}),s.jsx("span",{children:"Portal aktiviert"}),(P==null?void 0:P.portalEnabled)&&s.jsx(ve,{variant:"success",children:"Aktiv"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Portal E-Mail"}),s.jsx("div",{className:"flex gap-2",children:s.jsx(H,{value:(P==null?void 0:P.portalEmail)||"",onChange:w=>g.mutate({portalEmail:w.target.value||null}),placeholder:"portal@example.com",disabled:!t||!(P!=null&&P.portalEnabled),className:"flex-1"})}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Diese E-Mail wird für den Login ins Kundenportal verwendet."})]}),(P==null?void 0:P.portalEnabled)&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:P!=null&&P.hasPassword?"Neues Passwort setzen":"Passwort setzen"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(H,{type:r?"text":"password",value:i,onChange:w=>l(w.target.value),placeholder:"Mindestens 6 Zeichen",disabled:!t}),s.jsx("button",{type:"button",onClick:()=>a(!r),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400",children:r?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]}),s.jsx(T,{onClick:()=>y.mutate(i),disabled:!t||i.length<6||y.isPending,children:y.isPending?"Speichern...":"Setzen"})]}),(P==null?void 0:P.hasPassword)&&s.jsx(bk,{customerId:e})]}),(P==null?void 0:P.portalLastLogin)&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Letzte Anmeldung: ",new Date(P.portalLastLogin).toLocaleString("de-DE")]})]})]}),s.jsxs("div",{className:"border rounded-lg p-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(ZS,{className:"w-5 h-5 text-gray-400"}),s.jsx("h3",{className:"font-medium",children:"Vertreter (können Verträge einsehen)"})]}),s.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie anderen Kunden erlauben, die Verträge dieses Kunden einzusehen. Beispiel: Der Sohn kann die Verträge seiner Mutter einsehen."}),t&&s.jsxs("div",{className:"mb-4",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx(H,{value:o,onChange:w=>c(w.target.value),placeholder:"Kunden suchen (Name, Kundennummer)...",onKeyDown:w=>w.key==="Enter"&&E(),className:"flex-1"}),s.jsx(T,{variant:"secondary",onClick:E,disabled:o.length<2||h,children:s.jsx(Tl,{className:"w-4 h-4"})})]}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Nur Kunden mit aktiviertem Portal können als Vertreter hinzugefügt werden."}),d.length>0&&s.jsx("div",{className:"mt-2 border rounded-lg divide-y",children:d.map(w=>s.jsxs("div",{className:"flex items-center justify-between p-3 hover:bg-gray-50",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:w.companyName||`${w.firstName} ${w.lastName}`}),s.jsx("p",{className:"text-sm text-gray-500",children:w.customerNumber})]}),s.jsxs(T,{size:"sm",onClick:()=>v.mutate(w.id),disabled:v.isPending,children:[s.jsx(_e,{className:"w-4 h-4 mr-1"}),"Hinzufügen"]})]},w.id))})]}),I.length>0?s.jsx("div",{className:"space-y-2",children:I.map(w=>{var S,A,O,R;return s.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:((S=w.representative)==null?void 0:S.companyName)||`${(A=w.representative)==null?void 0:A.firstName} ${(O=w.representative)==null?void 0:O.lastName}`}),s.jsx("p",{className:"text-sm text-gray-500",children:(R=w.representative)==null?void 0:R.customerNumber})]}),t&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertreter wirklich entfernen?")&&N.mutate(w.representativeId)},children:s.jsx(qt,{className:"w-4 h-4 text-red-500"})})]},w.id)})}):s.jsx("p",{className:"text-gray-500 text-sm",children:"Keine Vertreter konfiguriert."})]})]})}function xx({isOpen:e,onClose:t,customerId:n,address:r}){const a=ge(),i=!!r,l=()=>({type:(r==null?void 0:r.type)||"DELIVERY_RESIDENCE",street:(r==null?void 0:r.street)||"",houseNumber:(r==null?void 0:r.houseNumber)||"",postalCode:(r==null?void 0:r.postalCode)||"",city:(r==null?void 0:r.city)||"",country:(r==null?void 0:r.country)||"Deutschland",isDefault:(r==null?void 0:r.isDefault)||!1}),[o,c]=j.useState(l),d=G({mutationFn:m=>Qu.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({type:"DELIVERY_RESIDENCE",street:"",houseNumber:"",postalCode:"",city:"",country:"Deutschland",isDefault:!1})}}),u=G({mutationFn:m=>Qu.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault(),i?u.mutate(o):d.mutate(o)},x=d.isPending||u.isPending;return i&&o.street!==r.street&&c(l()),s.jsx(qe,{isOpen:e,onClose:t,title:i?"Adresse bearbeiten":"Adresse hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(Ie,{label:"Adresstyp",value:o.type,onChange:m=>c({...o,type:m.target.value}),options:[{value:"DELIVERY_RESIDENCE",label:"Liefer-/Meldeadresse"},{value:"BILLING",label:"Rechnungsadresse"}]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx("div",{className:"col-span-2",children:s.jsx(H,{label:"Straße",value:o.street,onChange:m=>c({...o,street:m.target.value}),required:!0})}),s.jsx(H,{label:"Hausnr.",value:o.houseNumber,onChange:m=>c({...o,houseNumber:m.target.value}),required:!0})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx(H,{label:"PLZ",value:o.postalCode,onChange:m=>c({...o,postalCode:m.target.value}),required:!0}),s.jsx("div",{className:"col-span-2",children:s.jsx(H,{label:"Ort",value:o.city,onChange:m=>c({...o,city:m.target.value}),required:!0})})]}),s.jsx(H,{label:"Land",value:o.country,onChange:m=>c({...o,country:m.target.value})}),s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isDefault,onChange:m=>c({...o,isDefault:m.target.checked}),className:"rounded"}),"Als Standard setzen"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:x,children:x?"Speichern...":"Speichern"})]})]})})}function gx({isOpen:e,onClose:t,customerId:n,bankCard:r}){const a=ge(),i=!!r,l=()=>({accountHolder:(r==null?void 0:r.accountHolder)||"",iban:(r==null?void 0:r.iban)||"",bic:(r==null?void 0:r.bic)||"",bankName:(r==null?void 0:r.bankName)||"",expiryDate:r!=null&&r.expiryDate?new Date(r.expiryDate).toISOString().split("T")[0]:"",isActive:(r==null?void 0:r.isActive)??!0}),[o,c]=j.useState(l);j.useState(()=>{c(l())});const d=G({mutationFn:m=>Yo.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({accountHolder:"",iban:"",bic:"",bankName:"",expiryDate:"",isActive:!0})}}),u=G({mutationFn:m=>Yo.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault();const f={...o,expiryDate:o.expiryDate?new Date(o.expiryDate):void 0};i?u.mutate(f):d.mutate(f)},x=d.isPending||u.isPending;return i&&o.iban!==r.iban&&c(l()),s.jsx(qe,{isOpen:e,onClose:t,title:i?"Bankkarte bearbeiten":"Bankkarte hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(H,{label:"Kontoinhaber",value:o.accountHolder,onChange:m=>c({...o,accountHolder:m.target.value}),required:!0}),s.jsx(H,{label:"IBAN",value:o.iban,onChange:m=>c({...o,iban:m.target.value}),required:!0}),s.jsx(H,{label:"BIC",value:o.bic,onChange:m=>c({...o,bic:m.target.value})}),s.jsx(H,{label:"Bank",value:o.bankName,onChange:m=>c({...o,bankName:m.target.value})}),s.jsx(H,{label:"Ablaufdatum",type:"date",value:o.expiryDate,onChange:m=>c({...o,expiryDate:m.target.value}),onClear:()=>c({...o,expiryDate:""})}),i&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isActive,onChange:m=>c({...o,isActive:m.target.checked}),className:"rounded"}),"Aktiv"]}),!i&&s.jsx("p",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded",children:"Dokument-Upload ist nach dem Speichern in der Übersicht möglich."}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:x,children:x?"Speichern...":"Speichern"})]})]})})}function yx({isOpen:e,onClose:t,customerId:n,document:r}){const a=ge(),i=!!r,l=()=>({type:(r==null?void 0:r.type)||"ID_CARD",documentNumber:(r==null?void 0:r.documentNumber)||"",issuingAuthority:(r==null?void 0:r.issuingAuthority)||"",issueDate:r!=null&&r.issueDate?new Date(r.issueDate).toISOString().split("T")[0]:"",expiryDate:r!=null&&r.expiryDate?new Date(r.expiryDate).toISOString().split("T")[0]:"",isActive:(r==null?void 0:r.isActive)??!0,licenseClasses:(r==null?void 0:r.licenseClasses)||"",licenseIssueDate:r!=null&&r.licenseIssueDate?new Date(r.licenseIssueDate).toISOString().split("T")[0]:""}),[o,c]=j.useState(l),d=G({mutationFn:m=>ec.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({type:"ID_CARD",documentNumber:"",issuingAuthority:"",issueDate:"",expiryDate:"",isActive:!0,licenseClasses:"",licenseIssueDate:""})}}),u=G({mutationFn:m=>ec.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault();const f={...o,issueDate:o.issueDate?new Date(o.issueDate):void 0,expiryDate:o.expiryDate?new Date(o.expiryDate):void 0};o.type==="DRIVERS_LICENSE"?(f.licenseClasses=o.licenseClasses||void 0,f.licenseIssueDate=o.licenseIssueDate?new Date(o.licenseIssueDate):void 0):(delete f.licenseClasses,delete f.licenseIssueDate),i?u.mutate(f):d.mutate(f)},x=d.isPending||u.isPending;return i&&o.documentNumber!==r.documentNumber&&c(l()),s.jsx(qe,{isOpen:e,onClose:t,title:i?"Ausweis bearbeiten":"Ausweis hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(Ie,{label:"Ausweistyp",value:o.type,onChange:m=>c({...o,type:m.target.value}),options:[{value:"ID_CARD",label:"Personalausweis"},{value:"PASSPORT",label:"Reisepass"},{value:"DRIVERS_LICENSE",label:"Führerschein"},{value:"OTHER",label:"Sonstiges"}]}),s.jsx(H,{label:"Ausweisnummer",value:o.documentNumber,onChange:m=>c({...o,documentNumber:m.target.value}),required:!0}),s.jsx(H,{label:"Ausstellende Behörde",value:o.issuingAuthority,onChange:m=>c({...o,issuingAuthority:m.target.value})}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(H,{label:"Ausstellungsdatum",type:"date",value:o.issueDate,onChange:m=>c({...o,issueDate:m.target.value}),onClear:()=>c({...o,issueDate:""})}),s.jsx(H,{label:"Ablaufdatum",type:"date",value:o.expiryDate,onChange:m=>c({...o,expiryDate:m.target.value}),onClear:()=>c({...o,expiryDate:""})})]}),o.type==="DRIVERS_LICENSE"&&s.jsxs(s.Fragment,{children:[s.jsx(H,{label:"Führerscheinklassen",value:o.licenseClasses,onChange:m=>c({...o,licenseClasses:m.target.value}),placeholder:"z.B. B, BE, AM, L"}),s.jsx(H,{label:"Erwerb Klasse B (Pkw)",type:"date",value:o.licenseIssueDate,onChange:m=>c({...o,licenseIssueDate:m.target.value}),onClear:()=>c({...o,licenseIssueDate:""})})]}),i&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isActive,onChange:m=>c({...o,isActive:m.target.checked}),className:"rounded"}),"Aktiv"]}),!i&&s.jsx("p",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded",children:"Dokument-Upload ist nach dem Speichern in der Übersicht möglich."}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:x,children:x?"Speichern...":"Speichern"})]})]})})}function vx({isOpen:e,onClose:t,customerId:n,meter:r}){const a=ge(),i=!!r,l=()=>({meterNumber:(r==null?void 0:r.meterNumber)||"",type:(r==null?void 0:r.type)||"ELECTRICITY",location:(r==null?void 0:r.location)||"",isActive:(r==null?void 0:r.isActive)??!0}),[o,c]=j.useState(l),d=G({mutationFn:m=>ln.create(n,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t(),c({meterNumber:"",type:"ELECTRICITY",location:"",isActive:!0})}}),u=G({mutationFn:m=>ln.update(r.id,m),onSuccess:()=>{a.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),h=m=>{m.preventDefault(),i?u.mutate(o):d.mutate(o)},x=d.isPending||u.isPending;return i&&o.meterNumber!==r.meterNumber&&c(l()),s.jsx(qe,{isOpen:e,onClose:t,title:i?"Zähler bearbeiten":"Zähler hinzufügen",children:s.jsxs("form",{onSubmit:h,className:"space-y-4",children:[s.jsx(H,{label:"Zählernummer",value:o.meterNumber,onChange:m=>c({...o,meterNumber:m.target.value}),required:!0}),s.jsx(Ie,{label:"Zählertyp",value:o.type,onChange:m=>c({...o,type:m.target.value}),options:[{value:"ELECTRICITY",label:"Strom"},{value:"GAS",label:"Gas"}]}),s.jsx(H,{label:"Standort",value:o.location,onChange:m=>c({...o,location:m.target.value}),placeholder:"z.B. Keller, Wohnung"}),i&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:o.isActive,onChange:m=>c({...o,isActive:m.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:x,children:x?"Speichern...":"Speichern"})]})]})})}function jx({isOpen:e,onClose:t,meterId:n,meterType:r,customerId:a,reading:i}){const l=ge(),o=!!i,c=r==="ELECTRICITY"?"kWh":"m³",d=()=>{var b;return{readingDate:i!=null&&i.readingDate?new Date(i.readingDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],value:((b=i==null?void 0:i.value)==null?void 0:b.toString())||"",notes:(i==null?void 0:i.notes)||""}},[u,h]=j.useState(d),x=G({mutationFn:b=>ln.addReading(n,b),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",a.toString()]}),t()}}),m=G({mutationFn:b=>ln.updateReading(n,i.id,b),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",a.toString()]}),t()}}),f=b=>{b.preventDefault();const g={readingDate:new Date(u.readingDate),value:parseFloat(u.value),unit:c,notes:u.notes||void 0};o?m.mutate(g):x.mutate(g)},p=x.isPending||m.isPending;return o&&u.value!==i.value.toString()&&h(d()),s.jsx(qe,{isOpen:e,onClose:t,title:o?"Zählerstand bearbeiten":"Zählerstand erfassen",children:s.jsxs("form",{onSubmit:f,className:"space-y-4",children:[s.jsx(H,{label:"Ablesedatum",type:"date",value:u.readingDate,onChange:b=>h({...u,readingDate:b.target.value}),required:!0}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx("div",{className:"col-span-2",children:s.jsx(H,{label:"Zählerstand",type:"number",step:"0.01",value:u.value,onChange:b=>h({...u,value:b.target.value}),required:!0})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Einheit"}),s.jsx("div",{className:"h-10 flex items-center px-3 bg-gray-100 border border-gray-300 rounded-md text-gray-700",children:c})]})]}),s.jsx(H,{label:"Notizen",value:u.notes,onChange:b=>h({...u,notes:b.target.value}),placeholder:"Optionale Notizen..."}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}const gd="@stressfrei-wechseln.de";function wk({customerId:e,emails:t,canEdit:n,showInactive:r,onToggleInactive:a,onAdd:i,onEdit:l}){const o=ge(),c=G({mutationFn:({id:h,data:x})=>xs.update(h,x),onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),d=G({mutationFn:xs.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",e.toString()]})}),u=r?t:t.filter(h=>h.isActive);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&s.jsxs(T,{size:"sm",onClick:i,children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Adresse hinzufügen"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:a,className:"rounded"}),"Inaktive anzeigen"]})]}),s.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[s.jsx("strong",{children:"Hinweis:"})," Hier werden E-Mail-Weiterleitungsadressen verwaltet, die für die Registrierung bei Anbietern verwendet werden. E-Mails an diese Adressen werden sowohl an den Kunden als auch an Sie weitergeleitet."]}),u.length>0?s.jsx("div",{className:"space-y-3",children:u.map(h=>s.jsx("div",{className:`border rounded-lg p-4 ${h.isActive?"":"opacity-50 bg-gray-50"}`,children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nn,{className:"w-4 h-4 text-gray-400"}),s.jsx("span",{className:"font-mono text-sm",children:h.email}),s.jsx(oe,{value:h.email}),!h.isActive&&s.jsx(ve,{variant:"danger",children:"Inaktiv"})]}),h.notes&&s.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-gray-500",children:[s.jsx(Be,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{children:h.notes})]})]}),n&&s.jsxs("div",{className:"flex gap-1",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>l(h),title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),h.isActive?s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse deaktivieren?")&&c.mutate({id:h.id,data:{isActive:!1}})},title:"Deaktivieren",children:s.jsx(It,{className:"w-4 h-4"})}):s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wieder aktivieren?")&&c.mutate({id:h.id,data:{isActive:!0}})},title:"Aktivieren",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&d.mutate(h.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]})},h.id))}):s.jsx("p",{className:"text-gray-500",children:"Keine Stressfrei-Wechseln Adressen vorhanden."})]})}function Sk({credentials:e,onHide:t,onResetPassword:n,isResettingPassword:r}){const[a,i]=j.useState(null),l=async(u,h)=>{try{await navigator.clipboard.writeText(u),i(h),setTimeout(()=>i(null),2e3)}catch{const x=document.createElement("textarea");x.value=u,document.body.appendChild(x),x.select(),document.execCommand("copy"),document.body.removeChild(x),i(h),setTimeout(()=>i(null),2e3)}},o=({text:u,fieldName:h})=>s.jsx("button",{type:"button",onClick:()=>l(u,h),className:"p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors",title:"In Zwischenablage kopieren",children:a===h?s.jsx(xr,{className:"w-4 h-4 text-green-600"}):s.jsx(oh,{className:"w-4 h-4"})}),c=e.imap?`${e.imap.server}:${e.imap.port}`:"",d=e.smtp?`${e.smtp.server}:${e.smtp.port}`:"";return s.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4 space-y-3",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide",children:"Zugangsdaten"}),s.jsx("button",{type:"button",onClick:t,className:"text-gray-400 hover:text-gray-600 p-1 hover:bg-gray-200 rounded",title:"Zugangsdaten ausblenden",children:s.jsx(It,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Benutzername"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1 break-all",children:e.email}),s.jsx(o,{text:e.email,fieldName:"email"})]})]}),s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Passwort"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1 break-all",children:e.password}),s.jsx(o,{text:e.password,fieldName:"password"})]}),s.jsx("button",{type:"button",onClick:n,disabled:r,className:"mt-2 text-xs text-blue-600 hover:text-blue-800 disabled:opacity-50",children:r?"Generiere...":"Neu generieren"})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.imap&&s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"IMAP (Empfang)"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1",children:c}),s.jsx(o,{text:c,fieldName:"imap"})]}),s.jsx("span",{className:"text-xs text-gray-400 mt-1 block",children:e.imap.encryption})]}),e.smtp&&s.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"SMTP (Versand)"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1",children:d}),s.jsx(o,{text:d,fieldName:"smtp"})]}),s.jsx("span",{className:"text-xs text-gray-400 mt-1 block",children:e.smtp.encryption})]})]})]})}function bx({isOpen:e,onClose:t,customerId:n,email:r,customerEmail:a}){const[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,x]=j.useState(!1),[m,f]=j.useState(null),[p,b]=j.useState("idle"),[g,y]=j.useState(!1),[v,N]=j.useState(!1),[E,P]=j.useState(!1),[I,w]=j.useState(!1),[S,A]=j.useState(null),[O,R]=j.useState(!1),[q,D]=j.useState(!1),z=ge(),k=!!r,{data:K}=fe({queryKey:["email-provider-configs"],queryFn:()=>yn.getConfigs(),enabled:e}),B=((K==null?void 0:K.data)||[]).some(ae=>ae.isActive&&ae.isDefault),_=ae=>{if(!ae)return"";const Ge=ae.indexOf("@");return Ge>0?ae.substring(0,Ge):ae},Q=async ae=>{var Ge;if(!(!B||!ae)){b("checking");try{const xt=await yn.checkEmailExists(ae);b((Ge=xt.data)!=null&&Ge.exists?"exists":"not_exists")}catch{b("error")}}},le=async()=>{var ae,Ge;if(!(!a||!i)){y(!0),f(null);try{const xt=await yn.provisionEmail(i,a);(ae=xt.data)!=null&&ae.success?b("exists"):f(((Ge=xt.data)==null?void 0:Ge.error)||"Provisionierung fehlgeschlagen")}catch(xt){f(xt instanceof Error?xt.message:"Fehler bei der Provisionierung")}finally{y(!1)}}},de=async()=>{if(r){N(!0),f(null);try{const ae=await xs.enableMailbox(r.id);ae.success?(P(!0),z.invalidateQueries({queryKey:["customer",n.toString()]}),z.invalidateQueries({queryKey:["mailbox-accounts",n]})):f(ae.error||"Mailbox-Aktivierung fehlgeschlagen")}catch(ae){f(ae instanceof Error?ae.message:"Fehler bei der Mailbox-Aktivierung")}finally{N(!1)}}},Ke=async()=>{if(r)try{const ae=await xs.syncMailboxStatus(r.id);ae.success&&ae.data&&(P(ae.data.hasMailbox),ae.data.wasUpdated&&z.invalidateQueries({queryKey:["customer",n.toString()]}))}catch(ae){console.error("Fehler beim Synchronisieren des Mailbox-Status:",ae)}},Ve=async()=>{if(r){R(!0);try{const ae=await xs.getMailboxCredentials(r.id);ae.success&&ae.data&&(A(ae.data),w(!0))}catch(ae){console.error("Fehler beim Laden der Zugangsdaten:",ae)}finally{R(!1)}}},st=async()=>{if(r&&confirm("Neues Passwort generieren? Das alte Passwort wird ungültig.")){D(!0);try{const ae=await xs.resetPassword(r.id);ae.success&&ae.data?(S&&A({...S,password:ae.data.password}),alert("Passwort wurde erfolgreich zurückgesetzt.")):alert(ae.error||"Fehler beim Zurücksetzen des Passworts")}catch(ae){console.error("Fehler beim Zurücksetzen des Passworts:",ae),alert(ae instanceof Error?ae.message:"Fehler beim Zurücksetzen des Passworts")}finally{D(!1)}}};j.useEffect(()=>{if(e){if(r){const ae=_(r.email);l(ae),c(r.notes||""),b("idle"),P(r.hasMailbox||!1),B&&(Q(ae),Ke())}else l(""),c(""),u(!1),x(!1),b("idle"),P(!1);f(null),w(!1),A(null)}},[e,r,B]);const C=G({mutationFn:async ae=>xs.create(n,{email:ae.email,notes:ae.notes,provisionAtProvider:ae.provision,createMailbox:ae.createMailbox}),onSuccess:()=>{z.invalidateQueries({queryKey:["customer",n.toString()]}),z.invalidateQueries({queryKey:["mailbox-accounts",n]}),l(""),c(""),u(!1),x(!1),t()},onError:ae=>{f(ae instanceof Error?ae.message:"Fehler bei der Provisionierung")}}),nt=G({mutationFn:ae=>xs.update(r.id,ae),onSuccess:()=>{z.invalidateQueries({queryKey:["customer",n.toString()]}),t()}}),es=ae=>{ae.preventDefault(),f(null);const Ge=i+gd;k?nt.mutate({email:Ge,notes:o||void 0}):C.mutate({email:Ge,notes:o||void 0,provision:d,createMailbox:d&&h})},Vt=C.isPending||nt.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:k?"Adresse bearbeiten":"Adresse hinzufügen",children:s.jsxs("form",{onSubmit:es,className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"E-Mail-Adresse"}),s.jsxs("div",{className:"flex",children:[s.jsx("input",{type:"text",value:i,onChange:ae=>l(ae.target.value.toLowerCase().replace(/[^a-z0-9._-]/g,"")),placeholder:"kunde-freenet",required:!0,className:"block w-full px-3 py-2 border border-gray-300 rounded-l-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("span",{className:"inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 bg-gray-100 text-gray-600 rounded-r-lg text-sm",children:gd})]}),s.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Vollständige Adresse: ",s.jsxs("span",{className:"font-mono",children:[i||"...",gd]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Notizen (optional)"}),s.jsx("textarea",{value:o,onChange:ae=>c(ae.target.value),rows:3,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"z.B. für Freenet-Konten, für Klarmobil..."})]}),B&&a&&s.jsx("div",{className:"bg-blue-50 p-3 rounded-lg",children:k?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"E-Mail-Provider Status"}),p==="checking"&&s.jsx("span",{className:"text-xs text-gray-500",children:"Prüfe..."}),p==="exists"&&s.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[s.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:s.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),"Beim Provider vorhanden"]}),p==="not_exists"&&s.jsx("span",{className:"text-xs text-orange-600",children:"Nicht beim Provider angelegt"}),p==="error"&&s.jsx("span",{className:"text-xs text-red-600",children:"Status konnte nicht geprüft werden"})]}),p==="not_exists"&&s.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[s.jsxs("p",{className:"text-xs text-gray-500 mb-2",children:["Die E-Mail-Weiterleitung ist noch nicht auf dem Server eingerichtet. Weiterleitungsziel: ",a]}),s.jsx(T,{type:"button",size:"sm",onClick:le,disabled:g,children:g?"Wird angelegt...":"Jetzt beim Provider anlegen"})]}),p==="error"&&s.jsx(T,{type:"button",size:"sm",variant:"secondary",onClick:()=>Q(i),children:"Erneut prüfen"}),p==="exists"&&s.jsxs("div",{className:"pt-3 mt-3 border-t border-blue-100",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Mailbox (IMAP/SMTP)"}),E?s.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[s.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:s.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),"Mailbox aktiv"]}):s.jsx("span",{className:"text-xs text-orange-600",children:"Keine Mailbox"})]}),!E&&s.jsxs("div",{className:"mt-2",children:[s.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"Aktiviere eine echte Mailbox um E-Mails direkt im CRM zu empfangen und zu versenden."}),s.jsx(T,{type:"button",size:"sm",onClick:de,disabled:v,children:v?"Wird aktiviert...":"Mailbox aktivieren"})]}),E&&s.jsx("div",{className:"mt-3",children:I?S&&s.jsx(Sk,{credentials:S,onHide:()=>w(!1),onResetPassword:st,isResettingPassword:q}):s.jsx(T,{type:"button",size:"sm",variant:"secondary",onClick:Ve,disabled:O,children:O?"Laden...":s.jsxs(s.Fragment,{children:[s.jsx(Ae,{className:"w-4 h-4 mr-1"}),"Zugangsdaten anzeigen"]})})})]})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:d,onChange:ae=>{u(ae.target.checked),ae.target.checked||x(!1)},className:"mt-1 rounded border-gray-300"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Beim E-Mail-Provider anlegen"}),s.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Die E-Mail-Weiterleitung wird automatisch auf dem konfigurierten Server erstellt. Weiterleitungsziel: ",a]})]})]}),d&&s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer ml-6",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:ae=>x(ae.target.checked),className:"mt-1 rounded border-gray-300"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Echte Mailbox erstellen (IMAP/SMTP-Zugang)"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Ermöglicht E-Mails direkt im CRM zu empfangen und zu versenden."})]})]})]})}),m&&s.jsx("div",{className:"bg-red-50 p-3 rounded-lg text-red-700 text-sm",children:m}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:Vt||!i,children:Vt?"Speichern...":"Speichern"})]})]})})}var Il=e=>e.type==="checkbox",Pr=e=>e instanceof Date,as=e=>e==null;const zv=e=>typeof e=="object";var jt=e=>!as(e)&&!Array.isArray(e)&&zv(e)&&!Pr(e),kk=e=>jt(e)&&e.target?Il(e.target)?e.target.checked:e.target.value:e,Ck=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,Ek=(e,t)=>e.has(Ck(t)),Dk=e=>{const t=e.constructor&&e.constructor.prototype;return jt(t)&&t.hasOwnProperty("isPrototypeOf")},xh=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function bt(e){if(e instanceof Date)return new Date(e);const t=typeof FileList<"u"&&e instanceof FileList;if(xh&&(e instanceof Blob||t))return e;const n=Array.isArray(e);if(!n&&!(jt(e)&&Dk(e)))return e;const r=n?[]:Object.create(Object.getPrototypeOf(e));for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&(r[a]=bt(e[a]));return r}var Lc=e=>/^\w*$/.test(e),rt=e=>e===void 0,gh=e=>Array.isArray(e)?e.filter(Boolean):[],yh=e=>gh(e.replace(/["|']|\]/g,"").split(/\.|\[/)),xe=(e,t,n)=>{if(!t||!jt(e))return n;const r=(Lc(t)?[t]:yh(t)).reduce((a,i)=>as(a)?a:a[i],e);return rt(r)||r===e?rt(e[t])?n:e[t]:r},Js=e=>typeof e=="boolean",_s=e=>typeof e=="function",Ye=(e,t,n)=>{let r=-1;const a=Lc(t)?[t]:yh(t),i=a.length,l=i-1;for(;++r{const a={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==Ks.all&&(t._proxyFormState[l]=!r||Ks.all),e[l]}});return a};const Mk=typeof window<"u"?Tt.useLayoutEffect:Tt.useEffect;var gs=e=>typeof e=="string",Tk=(e,t,n,r,a)=>gs(e)?(r&&t.watch.add(e),xe(n,e,a)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),xe(n,i))):(r&&(t.watchAll=!0),n),Gu=e=>as(e)||!zv(e);function qn(e,t,n=new WeakSet){if(Gu(e)||Gu(t))return Object.is(e,t);if(Pr(e)&&Pr(t))return Object.is(e.getTime(),t.getTime());const r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;if(n.has(e)||n.has(t))return!0;n.add(e),n.add(t);for(const i of r){const l=e[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(Pr(l)&&Pr(o)||jt(l)&&jt(o)||Array.isArray(l)&&Array.isArray(o)?!qn(l,o,n):!Object.is(l,o))return!1}}return!0}const Fk=Tt.createContext(null);Fk.displayName="HookFormContext";var Ik=(e,t,n,r,a)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:a||!0}}:{},Oi=e=>Array.isArray(e)?e:[e],wx=()=>{let e=[];return{get observers(){return e},next:a=>{for(const i of e)i.next&&i.next(a)},subscribe:a=>(e.push(a),{unsubscribe:()=>{e=e.filter(i=>i!==a)}}),unsubscribe:()=>{e=[]}}};function $v(e,t){const n={};for(const r in e)if(e.hasOwnProperty(r)){const a=e[r],i=t[r];if(a&&jt(a)&&i){const l=$v(a,i);jt(l)&&(n[r]=l)}else e[r]&&(n[r]=i)}return n}var Wt=e=>jt(e)&&!Object.keys(e).length,vh=e=>e.type==="file",sc=e=>{if(!xh)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},_v=e=>e.type==="select-multiple",jh=e=>e.type==="radio",Rk=e=>jh(e)||Il(e),yd=e=>sc(e)&&e.isConnected;function Lk(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in e)if(_s(e[t]))return!0;return!1};function Kv(e){return Array.isArray(e)||jt(e)&&!zk(e)}function Zu(e,t={}){for(const n in e){const r=e[n];Kv(r)?(t[n]=Array.isArray(r)?[]:{},Zu(r,t[n])):rt(r)||(t[n]=!0)}return t}function ia(e,t,n){n||(n=Zu(t));for(const r in e){const a=e[r];if(Kv(a))rt(t)||Gu(n[r])?n[r]=Zu(a,Array.isArray(a)?[]:{}):ia(a,as(t)?{}:t[r],n[r]);else{const i=t[r];n[r]=!qn(a,i)}}return n}const Sx={value:!1,isValid:!1},kx={value:!0,isValid:!0};var Bv=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!rt(e[0].attributes.value)?rt(e[0].value)||e[0].value===""?kx:{value:e[0].value,isValid:!0}:kx:Sx}return Sx},Uv=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>rt(e)?e:t?e===""?NaN:e&&+e:n&&gs(e)?new Date(e):r?r(e):e;const Cx={isValid:!1,value:null};var qv=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,Cx):Cx;function Ex(e){const t=e.ref;return vh(t)?t.files:jh(t)?qv(e.refs).value:_v(t)?[...t.selectedOptions].map(({value:n})=>n):Il(t)?Bv(e.refs).value:Uv(rt(t.value)?e.ref.value:t.value,e)}var $k=(e,t,n,r)=>{const a={};for(const i of e){const l=xe(t,i);l&&Ye(a,i,l._f)}return{criteriaMode:n,names:[...e],fields:a,shouldUseNativeValidation:r}},nc=e=>e instanceof RegExp,ji=e=>rt(e)?e:nc(e)?e.source:jt(e)?nc(e.value)?e.value.source:e.value:e,Dx=e=>({isOnSubmit:!e||e===Ks.onSubmit,isOnBlur:e===Ks.onBlur,isOnChange:e===Ks.onChange,isOnAll:e===Ks.all,isOnTouch:e===Ks.onTouched});const Ax="AsyncFunction";var _k=e=>!!e&&!!e.validate&&!!(_s(e.validate)&&e.validate.constructor.name===Ax||jt(e.validate)&&Object.values(e.validate).find(t=>t.constructor.name===Ax)),Kk=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate),Px=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const zi=(e,t,n,r)=>{for(const a of n||Object.keys(e)){const i=xe(e,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!r)return!0;if(l.ref&&t(l.ref,l.name)&&!r)return!0;if(zi(o,t))break}else if(jt(o)&&zi(o,t))break}}};function Mx(e,t,n){const r=xe(e,n);if(r||Lc(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=xe(t,i),o=xe(e,i);if(l&&!Array.isArray(l)&&n!==i)return{name:n};if(o&&o.type)return{name:i,error:o};if(o&&o.root&&o.root.type)return{name:`${i}.root`,error:o.root};a.pop()}return{name:n}}var Bk=(e,t,n,r)=>{n(e);const{name:a,...i}=e;return Wt(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||Ks.all))},Uk=(e,t,n)=>!e||!t||e===t||Oi(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),qk=(e,t,n,r,a)=>a.isOnAll?!1:!n&&a.isOnTouch?!(t||e):(n?r.isOnBlur:a.isOnBlur)?!e:(n?r.isOnChange:a.isOnChange)?e:!0,Vk=(e,t)=>!gh(xe(e,t)).length&&yt(e,t),Qk=(e,t,n)=>{const r=Oi(xe(e,n));return Ye(r,"root",t[n]),Ye(e,n,r),e};function Tx(e,t,n="validate"){if(gs(e)||Array.isArray(e)&&e.every(gs)||Js(e)&&!e)return{type:n,message:gs(e)?e:"",ref:t}}var ra=e=>jt(e)&&!nc(e)?e:{value:e,message:""},Fx=async(e,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:x,pattern:m,validate:f,name:p,valueAsNumber:b,mount:g}=e._f,y=xe(n,p);if(!g||t.has(p))return{};const v=o?o[0]:l,N=R=>{a&&v.reportValidity&&(v.setCustomValidity(Js(R)?"":R||""),v.reportValidity())},E={},P=jh(l),I=Il(l),w=P||I,S=(b||vh(l))&&rt(l.value)&&rt(y)||sc(l)&&l.value===""||y===""||Array.isArray(y)&&!y.length,A=Ik.bind(null,p,r,E),O=(R,q,D,z=fn.maxLength,k=fn.minLength)=>{const K=R?q:D;E[p]={type:R?z:k,message:K,ref:l,...A(R?z:k,K)}};if(i?!Array.isArray(y)||!y.length:c&&(!w&&(S||as(y))||Js(y)&&!y||I&&!Bv(o).isValid||P&&!qv(o).isValid)){const{value:R,message:q}=gs(c)?{value:!!c,message:c}:ra(c);if(R&&(E[p]={type:fn.required,message:q,ref:v,...A(fn.required,q)},!r))return N(q),E}if(!S&&(!as(h)||!as(x))){let R,q;const D=ra(x),z=ra(h);if(!as(y)&&!isNaN(y)){const k=l.valueAsNumber||y&&+y;as(D.value)||(R=k>D.value),as(z.value)||(q=knew Date(new Date().toDateString()+" "+Q),B=l.type=="time",_=l.type=="week";gs(D.value)&&y&&(R=B?K(y)>K(D.value):_?y>D.value:k>new Date(D.value)),gs(z.value)&&y&&(q=B?K(y)+R.value,z=!as(q.value)&&y.length<+q.value;if((D||z)&&(O(D,R.message,q.message),!r))return N(E[p].message),E}if(m&&!S&&gs(y)){const{value:R,message:q}=ra(m);if(nc(R)&&!y.match(R)&&(E[p]={type:fn.pattern,message:q,ref:l,...A(fn.pattern,q)},!r))return N(q),E}if(f){if(_s(f)){const R=await f(y,n),q=Tx(R,v);if(q&&(E[p]={...q,...A(fn.validate,q.message)},!r))return N(q.message),E}else if(jt(f)){let R={};for(const q in f){if(!Wt(R)&&!r)break;const D=Tx(await f[q](y,n),v,q);D&&(R={...D,...A(q,D.message)},N(D.message),r&&(E[p]=R))}if(!Wt(R)&&(E[p]={ref:v,...R},!r))return E}}return N(!0),E};const Hk={mode:Ks.onSubmit,reValidateMode:Ks.onChange,shouldFocusError:!0};function Wk(e={}){let t={...Hk,...e},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:_s(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=jt(t.defaultValues)||jt(t.values)?bt(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:bt(a),l={action:!1,mount:!1,watch:!1,keepIsValid:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},h={...u};let x={...h};const m={array:wx(),state:wx()},f=t.criteriaMode===Ks.all,p=L=>U=>{clearTimeout(d),d=setTimeout(L,U)},b=async L=>{if(!l.keepIsValid&&!t.disabled&&(h.isValid||x.isValid||L)){let U;t.resolver?(U=Wt((await w()).errors),g()):U=await A(r,!0),U!==n.isValid&&m.state.next({isValid:U})}},g=(L,U)=>{!t.disabled&&(h.isValidating||h.validatingFields||x.isValidating||x.validatingFields)&&((L||Array.from(o.mount)).forEach(W=>{W&&(U?Ye(n.validatingFields,W,U):yt(n.validatingFields,W))}),m.state.next({validatingFields:n.validatingFields,isValidating:!Wt(n.validatingFields)}))},y=(L,U=[],W,ce,ne=!0,ee=!0)=>{if(ce&&W&&!t.disabled){if(l.action=!0,ee&&Array.isArray(xe(r,L))){const ye=W(xe(r,L),ce.argA,ce.argB);ne&&Ye(r,L,ye)}if(ee&&Array.isArray(xe(n.errors,L))){const ye=W(xe(n.errors,L),ce.argA,ce.argB);ne&&Ye(n.errors,L,ye),Vk(n.errors,L)}if((h.touchedFields||x.touchedFields)&&ee&&Array.isArray(xe(n.touchedFields,L))){const ye=W(xe(n.touchedFields,L),ce.argA,ce.argB);ne&&Ye(n.touchedFields,L,ye)}(h.dirtyFields||x.dirtyFields)&&(n.dirtyFields=ia(a,i)),m.state.next({name:L,isDirty:R(L,U),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Ye(i,L,U)},v=(L,U)=>{Ye(n.errors,L,U),m.state.next({errors:n.errors})},N=L=>{n.errors=L,m.state.next({errors:n.errors,isValid:!1})},E=(L,U,W,ce)=>{const ne=xe(r,L);if(ne){const ee=xe(i,L,rt(W)?xe(a,L):W);rt(ee)||ce&&ce.defaultChecked||U?Ye(i,L,U?ee:Ex(ne._f)):z(L,ee),l.mount&&!l.action&&b()}},P=(L,U,W,ce,ne)=>{let ee=!1,ye=!1;const Le={name:L};if(!t.disabled){if(!W||ce){(h.isDirty||x.isDirty)&&(ye=n.isDirty,n.isDirty=Le.isDirty=R(),ee=ye!==Le.isDirty);const Me=qn(xe(a,L),U);ye=!!xe(n.dirtyFields,L),Me?yt(n.dirtyFields,L):Ye(n.dirtyFields,L,!0),Le.dirtyFields=n.dirtyFields,ee=ee||(h.dirtyFields||x.dirtyFields)&&ye!==!Me}if(W){const Me=xe(n.touchedFields,L);Me||(Ye(n.touchedFields,L,W),Le.touchedFields=n.touchedFields,ee=ee||(h.touchedFields||x.touchedFields)&&Me!==W)}ee&&ne&&m.state.next(Le)}return ee?Le:{}},I=(L,U,W,ce)=>{const ne=xe(n.errors,L),ee=(h.isValid||x.isValid)&&Js(U)&&n.isValid!==U;if(t.delayError&&W?(c=p(()=>v(L,W)),c(t.delayError)):(clearTimeout(d),c=null,W?Ye(n.errors,L,W):yt(n.errors,L)),(W?!qn(ne,W):ne)||!Wt(ce)||ee){const ye={...ce,...ee&&Js(U)?{isValid:U}:{},errors:n.errors,name:L};n={...n,...ye},m.state.next(ye)}},w=async L=>(g(L,!0),await t.resolver(i,t.context,$k(L||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),S=async L=>{const{errors:U}=await w(L);if(g(L),L)for(const W of L){const ce=xe(U,W);ce?Ye(n.errors,W,ce):yt(n.errors,W)}else n.errors=U;return U},A=async(L,U,W={valid:!0})=>{for(const ce in L){const ne=L[ce];if(ne){const{_f:ee,...ye}=ne;if(ee){const Le=o.array.has(ee.name),Me=ne._f&&_k(ne._f);Me&&h.validatingFields&&g([ee.name],!0);const kt=await Fx(ne,o.disabled,i,f,t.shouldUseNativeValidation&&!U,Le);if(Me&&h.validatingFields&&g([ee.name]),kt[ee.name]&&(W.valid=!1,U||e.shouldUseNativeValidation))break;!U&&(xe(kt,ee.name)?Le?Qk(n.errors,kt,ee.name):Ye(n.errors,ee.name,kt[ee.name]):yt(n.errors,ee.name))}!Wt(ye)&&await A(ye,U,W)}}return W.valid},O=()=>{for(const L of o.unMount){const U=xe(r,L);U&&(U._f.refs?U._f.refs.every(W=>!yd(W)):!yd(U._f.ref))&&es(L)}o.unMount=new Set},R=(L,U)=>!t.disabled&&(L&&U&&Ye(i,L,U),!qn(le(),a)),q=(L,U,W)=>Tk(L,o,{...l.mount?i:rt(U)?a:gs(L)?{[L]:U}:U},W,U),D=L=>gh(xe(l.mount?i:a,L,t.shouldUnregister?xe(a,L,[]):[])),z=(L,U,W={})=>{const ce=xe(r,L);let ne=U;if(ce){const ee=ce._f;ee&&(!ee.disabled&&Ye(i,L,Uv(U,ee)),ne=sc(ee.ref)&&as(U)?"":U,_v(ee.ref)?[...ee.ref.options].forEach(ye=>ye.selected=ne.includes(ye.value)):ee.refs?Il(ee.ref)?ee.refs.forEach(ye=>{(!ye.defaultChecked||!ye.disabled)&&(Array.isArray(ne)?ye.checked=!!ne.find(Le=>Le===ye.value):ye.checked=ne===ye.value||!!ne)}):ee.refs.forEach(ye=>ye.checked=ye.value===ne):vh(ee.ref)?ee.ref.value="":(ee.ref.value=ne,ee.ref.type||m.state.next({name:L,values:bt(i)})))}(W.shouldDirty||W.shouldTouch)&&P(L,ne,W.shouldTouch,W.shouldDirty,!0),W.shouldValidate&&Q(L)},k=(L,U,W)=>{for(const ce in U){if(!U.hasOwnProperty(ce))return;const ne=U[ce],ee=L+"."+ce,ye=xe(r,ee);(o.array.has(L)||jt(ne)||ye&&!ye._f)&&!Pr(ne)?k(ee,ne,W):z(ee,ne,W)}},K=(L,U,W={})=>{const ce=xe(r,L),ne=o.array.has(L),ee=bt(U);Ye(i,L,ee),ne?(m.array.next({name:L,values:bt(i)}),(h.isDirty||h.dirtyFields||x.isDirty||x.dirtyFields)&&W.shouldDirty&&m.state.next({name:L,dirtyFields:ia(a,i),isDirty:R(L,ee)})):ce&&!ce._f&&!as(ee)?k(L,ee,W):z(L,ee,W),Px(L,o)?m.state.next({...n,name:L,values:bt(i)}):m.state.next({name:l.mount?L:void 0,values:bt(i)})},B=async L=>{l.mount=!0;const U=L.target;let W=U.name,ce=!0;const ne=xe(r,W),ee=Me=>{ce=Number.isNaN(Me)||Pr(Me)&&isNaN(Me.getTime())||qn(Me,xe(i,W,Me))},ye=Dx(t.mode),Le=Dx(t.reValidateMode);if(ne){let Me,kt;const mn=U.type?Ex(ne._f):kk(L),Hs=L.type===Nx.BLUR||L.type===Nx.FOCUS_OUT,Ln=!Kk(ne._f)&&!t.resolver&&!xe(n.errors,W)&&!ne._f.deps||qk(Hs,xe(n.touchedFields,W),n.isSubmitted,Le,ye),li=Px(W,o,Hs);Ye(i,W,mn),Hs?(!U||!U.readOnly)&&(ne._f.onBlur&&ne._f.onBlur(L),c&&c(0)):ne._f.onChange&&ne._f.onChange(L);const sa=P(W,mn,Hs),Oc=!Wt(sa)||li;if(!Hs&&m.state.next({name:W,type:L.type,values:bt(i)}),Ln)return(h.isValid||x.isValid)&&(t.mode==="onBlur"?Hs&&b():Hs||b()),Oc&&m.state.next({name:W,...li?{}:sa});if(!Hs&&li&&m.state.next({...n}),t.resolver){const{errors:oi}=await w([W]);if(g([W]),ee(mn),ce){const Rl=Mx(n.errors,r,W),ci=Mx(oi,r,Rl.name||W);Me=ci.error,W=ci.name,kt=Wt(oi)}}else g([W],!0),Me=(await Fx(ne,o.disabled,i,f,t.shouldUseNativeValidation))[W],g([W]),ee(mn),ce&&(Me?kt=!1:(h.isValid||x.isValid)&&(kt=await A(r,!0)));ce&&(ne._f.deps&&(!Array.isArray(ne._f.deps)||ne._f.deps.length>0)&&Q(ne._f.deps),I(W,kt,Me,sa))}},_=(L,U)=>{if(xe(n.errors,U)&&L.focus)return L.focus(),1},Q=async(L,U={})=>{let W,ce;const ne=Oi(L);if(t.resolver){const ee=await S(rt(L)?L:ne);W=Wt(ee),ce=L?!ne.some(ye=>xe(ee,ye)):W}else L?(ce=(await Promise.all(ne.map(async ee=>{const ye=xe(r,ee);return await A(ye&&ye._f?{[ee]:ye}:ye)}))).every(Boolean),!(!ce&&!n.isValid)&&b()):ce=W=await A(r);return m.state.next({...!gs(L)||(h.isValid||x.isValid)&&W!==n.isValid?{}:{name:L},...t.resolver||!L?{isValid:W}:{},errors:n.errors}),U.shouldFocus&&!ce&&zi(r,_,L?ne:o.mount),ce},le=(L,U)=>{let W={...l.mount?i:a};return U&&(W=$v(U.dirtyFields?n.dirtyFields:n.touchedFields,W)),rt(L)?W:gs(L)?xe(W,L):L.map(ce=>xe(W,ce))},de=(L,U)=>({invalid:!!xe((U||n).errors,L),isDirty:!!xe((U||n).dirtyFields,L),error:xe((U||n).errors,L),isValidating:!!xe(n.validatingFields,L),isTouched:!!xe((U||n).touchedFields,L)}),Ke=L=>{L&&Oi(L).forEach(U=>yt(n.errors,U)),m.state.next({errors:L?n.errors:{}})},Ve=(L,U,W)=>{const ce=(xe(r,L,{_f:{}})._f||{}).ref,ne=xe(n.errors,L)||{},{ref:ee,message:ye,type:Le,...Me}=ne;Ye(n.errors,L,{...Me,...U,ref:ce}),m.state.next({name:L,errors:n.errors,isValid:!1}),W&&W.shouldFocus&&ce&&ce.focus&&ce.focus()},st=(L,U)=>_s(L)?m.state.subscribe({next:W=>"values"in W&&L(q(void 0,U),W)}):q(L,U,!0),C=L=>m.state.subscribe({next:U=>{Uk(L.name,U.name,L.exact)&&Bk(U,L.formState||h,ts,L.reRenderRoot)&&L.callback({values:{...i},...n,...U,defaultValues:a})}}).unsubscribe,nt=L=>(l.mount=!0,x={...x,...L.formState},C({...L,formState:{...u,...L.formState}})),es=(L,U={})=>{for(const W of L?Oi(L):o.mount)o.mount.delete(W),o.array.delete(W),U.keepValue||(yt(r,W),yt(i,W)),!U.keepError&&yt(n.errors,W),!U.keepDirty&&yt(n.dirtyFields,W),!U.keepTouched&&yt(n.touchedFields,W),!U.keepIsValidating&&yt(n.validatingFields,W),!t.shouldUnregister&&!U.keepDefaultValue&&yt(a,W);m.state.next({values:bt(i)}),m.state.next({...n,...U.keepDirty?{isDirty:R()}:{}}),!U.keepIsValid&&b()},Vt=({disabled:L,name:U})=>{if(Js(L)&&l.mount||L||o.disabled.has(U)){const ne=o.disabled.has(U)!==!!L;L?o.disabled.add(U):o.disabled.delete(U),ne&&l.mount&&!l.action&&b()}},ae=(L,U={})=>{let W=xe(r,L);const ce=Js(U.disabled)||Js(t.disabled);return Ye(r,L,{...W||{},_f:{...W&&W._f?W._f:{ref:{name:L}},name:L,mount:!0,...U}}),o.mount.add(L),W?Vt({disabled:Js(U.disabled)?U.disabled:t.disabled,name:L}):E(L,!0,U.value),{...ce?{disabled:U.disabled||t.disabled}:{},...t.progressive?{required:!!U.required,min:ji(U.min),max:ji(U.max),minLength:ji(U.minLength),maxLength:ji(U.maxLength),pattern:ji(U.pattern)}:{},name:L,onChange:B,onBlur:B,ref:ne=>{if(ne){ae(L,U),W=xe(r,L);const ee=rt(ne.value)&&ne.querySelectorAll&&ne.querySelectorAll("input,select,textarea")[0]||ne,ye=Rk(ee),Le=W._f.refs||[];if(ye?Le.find(Me=>Me===ee):ee===W._f.ref)return;Ye(r,L,{_f:{...W._f,...ye?{refs:[...Le.filter(yd),ee,...Array.isArray(xe(a,L))?[{}]:[]],ref:{type:ee.type,name:L}}:{ref:ee}}}),E(L,!1,void 0,ee)}else W=xe(r,L,{}),W._f&&(W._f.mount=!1),(t.shouldUnregister||U.shouldUnregister)&&!(Ek(o.array,L)&&l.action)&&o.unMount.add(L)}}},Ge=()=>t.shouldFocusError&&zi(r,_,o.mount),xt=L=>{Js(L)&&(m.state.next({disabled:L}),zi(r,(U,W)=>{const ce=xe(r,W);ce&&(U.disabled=ce._f.disabled||L,Array.isArray(ce._f.refs)&&ce._f.refs.forEach(ne=>{ne.disabled=ce._f.disabled||L}))},0,!1))},Z=(L,U)=>async W=>{let ce;W&&(W.preventDefault&&W.preventDefault(),W.persist&&W.persist());let ne=bt(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:ee,values:ye}=await w();g(),n.errors=ee,ne=bt(ye)}else await A(r);if(o.disabled.size)for(const ee of o.disabled)yt(ne,ee);if(yt(n.errors,"root"),Wt(n.errors)){m.state.next({errors:{}});try{await L(ne,W)}catch(ee){ce=ee}}else U&&await U({...n.errors},W),Ge(),setTimeout(Ge);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Wt(n.errors)&&!ce,submitCount:n.submitCount+1,errors:n.errors}),ce)throw ce},Fe=(L,U={})=>{xe(r,L)&&(rt(U.defaultValue)?K(L,bt(xe(a,L))):(K(L,U.defaultValue),Ye(a,L,bt(U.defaultValue))),U.keepTouched||yt(n.touchedFields,L),U.keepDirty||(yt(n.dirtyFields,L),n.isDirty=U.defaultValue?R(L,bt(xe(a,L))):R()),U.keepError||(yt(n.errors,L),h.isValid&&b()),m.state.next({...n}))},Xe=(L,U={})=>{const W=L?bt(L):a,ce=bt(W),ne=Wt(L),ee=ne?a:ce;if(U.keepDefaultValues||(a=W),!U.keepValues){if(U.keepDirtyValues){const ye=new Set([...o.mount,...Object.keys(ia(a,i))]);for(const Le of Array.from(ye)){const Me=xe(n.dirtyFields,Le),kt=xe(i,Le),mn=xe(ee,Le);Me&&!rt(kt)?Ye(ee,Le,kt):!Me&&!rt(mn)&&K(Le,mn)}}else{if(xh&&rt(L))for(const ye of o.mount){const Le=xe(r,ye);if(Le&&Le._f){const Me=Array.isArray(Le._f.refs)?Le._f.refs[0]:Le._f.ref;if(sc(Me)){const kt=Me.closest("form");if(kt){kt.reset();break}}}}if(U.keepFieldsRef)for(const ye of o.mount)K(ye,xe(ee,ye));else r={}}i=t.shouldUnregister?U.keepDefaultValues?bt(a):{}:bt(ee),m.array.next({values:{...ee}}),m.state.next({values:{...ee}})}o={mount:U.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!U.keepIsValid||!!U.keepDirtyValues||!t.shouldUnregister&&!Wt(ee),l.watch=!!t.shouldUnregister,l.keepIsValid=!!U.keepIsValid,l.action=!1,U.keepErrors||(n.errors={}),m.state.next({submitCount:U.keepSubmitCount?n.submitCount:0,isDirty:ne?!1:U.keepDirty?n.isDirty:!!(U.keepDefaultValues&&!qn(L,a)),isSubmitted:U.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:ne?{}:U.keepDirtyValues?U.keepDefaultValues&&i?ia(a,i):n.dirtyFields:U.keepDefaultValues&&L?ia(a,L):U.keepDirty?n.dirtyFields:{},touchedFields:U.keepTouched?n.touchedFields:{},errors:U.keepErrors?n.errors:{},isSubmitSuccessful:U.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},J=(L,U)=>Xe(_s(L)?L(i):L,{...t.resetOptions,...U}),ue=(L,U={})=>{const W=xe(r,L),ce=W&&W._f;if(ce){const ne=ce.refs?ce.refs[0]:ce.ref;ne.focus&&setTimeout(()=>{ne.focus(),U.shouldSelect&&_s(ne.select)&&ne.select()})}},ts=L=>{n={...n,...L}},gt={control:{register:ae,unregister:es,getFieldState:de,handleSubmit:Z,setError:Ve,_subscribe:C,_runSchema:w,_updateIsValidating:g,_focusError:Ge,_getWatch:q,_getDirty:R,_setValid:b,_setFieldArray:y,_setDisabledField:Vt,_setErrors:N,_getFieldArray:D,_reset:Xe,_resetDefaultValues:()=>_s(t.defaultValues)&&t.defaultValues().then(L=>{J(L,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:O,_disableForm:xt,_subjects:m,_proxyFormState:h,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(L){l=L},get _defaultValues(){return a},get _names(){return o},set _names(L){o=L},get _formState(){return n},get _options(){return t},set _options(L){t={...t,...L}}},subscribe:nt,trigger:Q,register:ae,handleSubmit:Z,watch:st,setValue:K,getValues:le,reset:J,resetField:Fe,clearErrors:Ke,unregister:es,setError:Ve,setFocus:ue,getFieldState:de};return{...gt,formControl:gt}}function Vv(e={}){const t=Tt.useRef(void 0),n=Tt.useRef(void 0),[r,a]=Tt.useState({isDirty:!1,isValidating:!1,isLoading:_s(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1,isReady:!1,defaultValues:_s(e.defaultValues)?void 0:e.defaultValues});if(!t.current)if(e.formControl)t.current={...e.formControl,formState:r},e.defaultValues&&!_s(e.defaultValues)&&e.formControl.reset(e.defaultValues,e.resetOptions);else{const{formControl:l,...o}=Wk(e);t.current={...o,formState:r}}const i=t.current.control;return i._options=e,Mk(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>a({...i._formState}),reRenderRoot:!0});return a(o=>({...o,isReady:!0})),i._formState.isReady=!0,l},[i]),Tt.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Tt.useEffect(()=>{e.mode&&(i._options.mode=e.mode),e.reValidateMode&&(i._options.reValidateMode=e.reValidateMode)},[i,e.mode,e.reValidateMode]),Tt.useEffect(()=>{e.errors&&(i._setErrors(e.errors),i._focusError())},[i,e.errors]),Tt.useEffect(()=>{e.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,e.shouldUnregister]),Tt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Tt.useEffect(()=>{var l;e.values&&!qn(e.values,n.current)?(i._reset(e.values,{keepFieldsRef:!0,...i._options.resetOptions}),!((l=i._options.resetOptions)===null||l===void 0)&&l.keepIsValid||i._setValid(),n.current=e.values,a(o=>({...o}))):i._resetDefaultValues()},[i,e.values]),Tt.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=Tt.useMemo(()=>Pk(r,i),[i,r]),t.current}function Ix(){var g,y;const{id:e}=Nc(),t=Yt(),n=ge(),r=!!e,{register:a,handleSubmit:i,reset:l,watch:o,setValue:c,formState:{errors:d}}=Vv(),u=o("type"),{data:h}=fe({queryKey:["customer",e],queryFn:()=>At.getById(parseInt(e)),enabled:r});j.useEffect(()=>{if(h!=null&&h.data){const v={...h.data};v.birthDate&&(v.birthDate=v.birthDate.split("T")[0]),v.foundingDate&&(v.foundingDate=v.foundingDate.split("T")[0]),l(v)}},[h,l]);const x=G({mutationFn:At.create,onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),t("/customers")}}),m=G({mutationFn:v=>At.update(parseInt(e),v),onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),n.invalidateQueries({queryKey:["customer",e]}),t(`/customers/${e}`)}}),f=v=>{const N={type:v.type,salutation:v.salutation||void 0,firstName:v.firstName,lastName:v.lastName,companyName:v.companyName||void 0,email:v.email||void 0,phone:v.phone||void 0,mobile:v.mobile||void 0,taxNumber:v.taxNumber||void 0,commercialRegisterNumber:v.commercialRegisterNumber||void 0,notes:v.notes||void 0,birthPlace:v.birthPlace||void 0};v.birthDate&&typeof v.birthDate=="string"&&v.birthDate.trim()!==""?N.birthDate=new Date(v.birthDate).toISOString():N.birthDate=null,v.foundingDate&&typeof v.foundingDate=="string"&&v.foundingDate.trim()!==""?N.foundingDate=new Date(v.foundingDate).toISOString():N.foundingDate=null,r?m.mutate(N):x.mutate(N)},p=x.isPending||m.isPending,b=x.error||m.error;return s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold mb-6",children:r?"Kunde bearbeiten":"Neuer Kunde"}),b&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:b instanceof Error?b.message:"Ein Fehler ist aufgetreten"}),s.jsxs("form",{onSubmit:i(f),children:[s.jsx(X,{className:"mb-6",title:"Stammdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Ie,{label:"Kundentyp",...a("type"),options:[{value:"PRIVATE",label:"Privatkunde"},{value:"BUSINESS",label:"Geschäftskunde"}]}),s.jsx(Ie,{label:"Anrede",...a("salutation"),options:[{value:"Herr",label:"Herr"},{value:"Frau",label:"Frau"},{value:"Divers",label:"Divers"}]}),s.jsx(H,{label:"Vorname",...a("firstName",{required:"Vorname erforderlich"}),error:(g=d.firstName)==null?void 0:g.message}),s.jsx(H,{label:"Nachname",...a("lastName",{required:"Nachname erforderlich"}),error:(y=d.lastName)==null?void 0:y.message}),u==="BUSINESS"&&s.jsxs(s.Fragment,{children:[s.jsx(H,{label:"Firmenname",...a("companyName"),className:"md:col-span-2"}),s.jsx(H,{label:"Gründungsdatum",type:"date",...a("foundingDate"),value:o("foundingDate")||"",onClear:()=>c("foundingDate","")})]}),u!=="BUSINESS"&&s.jsxs(s.Fragment,{children:[s.jsx(H,{label:"Geburtsdatum",type:"date",...a("birthDate"),value:o("birthDate")||"",onClear:()=>c("birthDate","")}),s.jsx(H,{label:"Geburtsort",...a("birthPlace")})]})]})}),s.jsx(X,{className:"mb-6",title:"Kontaktdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(H,{label:"E-Mail",type:"email",...a("email")}),s.jsx(H,{label:"Telefon",...a("phone")}),s.jsx(H,{label:"Mobil",...a("mobile")})]})}),u==="BUSINESS"&&s.jsxs(X,{className:"mb-6",title:"Geschäftsdaten",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(H,{label:"Steuernummer",...a("taxNumber")}),s.jsx(H,{label:"Handelsregisternummer",...a("commercialRegisterNumber"),placeholder:"z.B. HRB 12345"})]}),r&&s.jsx("p",{className:"mt-4 text-sm text-gray-500",children:"Dokumente (Gewerbeanmeldung, Handelsregisterauszug) können nach dem Speichern in der Kundendetailansicht hochgeladen werden."})]}),s.jsx(X,{className:"mb-6",title:"Notizen",children:s.jsx("textarea",{...a("notes"),rows:4,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"Interne Notizen..."})}),s.jsxs("div",{className:"flex justify-end gap-4",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:()=>t(-1),children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})]})}const vd={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},jd={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},Rx={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},Gk=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function Zk({isOpen:e,onClose:t}){return e?s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:t}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600",children:s.jsx(qt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:Gk.map(({status:n,label:r,description:a,color:i})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${i}`,children:r}),s.jsx("span",{className:"text-sm text-gray-600",children:a})]},n))})]})]}):null}function Jk(){const[e,t]=Sc(),n=Yt(),[r,a]=j.useState(e.get("search")||""),[i,l]=j.useState(e.get("type")||""),[o,c]=j.useState(e.get("status")||""),[d,u]=j.useState(parseInt(e.get("page")||"1",10)),[h,x]=j.useState(new Set),[m,f]=j.useState(!1),{hasPermission:p,isCustomer:b,isCustomerPortal:g,user:y}=We(),v=ge();j.useEffect(()=>{const D=new URLSearchParams;r&&D.set("search",r),i&&D.set("type",i),o&&D.set("status",o),d>1&&D.set("page",d.toString()),t(D,{replace:!0})},[r,i,o,d,t]);const N=G({mutationFn:Oe.delete,onSuccess:()=>{v.invalidateQueries({queryKey:["contracts"]})}}),{data:E,isLoading:P}=fe({queryKey:["contracts",r,i,o,d,b?y==null?void 0:y.customerId:null],queryFn:()=>Oe.getAll({search:r||void 0,type:i||void 0,status:o||void 0,page:d,limit:20,customerId:b?y==null?void 0:y.customerId:void 0})}),I=j.useMemo(()=>{if(!g||!(E!=null&&E.data))return[];const D=new Set;return y!=null&&y.customerId&&D.add(y.customerId),E.data.forEach(z=>D.add(z.customerId)),[...D]},[E==null?void 0:E.data,g,y==null?void 0:y.customerId]),w=s1({queries:I.map(D=>({queryKey:["contract-tree",D],queryFn:()=>Oe.getTreeForCustomer(D),enabled:g}))}),S=j.useMemo(()=>{const D=new Map;return I.forEach((z,k)=>{var B;const K=w[k];(B=K==null?void 0:K.data)!=null&&B.data&&D.set(z,K.data.data)}),D},[I,w]),A=j.useMemo(()=>{if(!g||!(E!=null&&E.data))return null;const D={};for(const z of E.data){const k=z.customerId;if(!D[k]){const K=z.customer?z.customer.companyName||`${z.customer.firstName} ${z.customer.lastName}`:`Kunde ${k}`;D[k]={customerId:k,customerName:K,isOwn:k===(y==null?void 0:y.customerId),contracts:[],tree:S.get(k)||[]}}D[k].contracts.push(z)}return Object.values(D).sort((z,k)=>z.isOwn&&!k.isOwn?-1:!z.isOwn&&k.isOwn?1:z.customerName.localeCompare(k.customerName))},[E==null?void 0:E.data,g,y==null?void 0:y.customerId,S]),O=D=>{x(z=>{const k=new Set(z);return k.has(D)?k.delete(D):k.add(D),k})},R=(D,z)=>D.map(k=>s.jsx("div",{children:q(k,z)},k.contract.id)),q=(D,z=0)=>{var le,de,Ke,Ve,st,C,nt;const{contract:k,predecessors:K,hasHistory:B}=D,_=h.has(k.id),Q=z>0;return s.jsxs("div",{children:[s.jsxs("div",{className:` - border rounded-lg p-4 transition-colors - ${Q?"ml-6 border-l-4 border-l-gray-300 bg-gray-50":"hover:bg-gray-50"} - `,children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[!Q&&B?s.jsx("button",{onClick:()=>O(k.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:_?"Einklappen":"Vorgänger anzeigen",children:_?s.jsx(dn,{className:"w-4 h-4 text-gray-500"}):s.jsx(Ft,{className:"w-4 h-4 text-gray-500"})}):Q?null:s.jsx("div",{className:"w-6"}),s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[k.contractNumber,s.jsx(oe,{value:k.contractNumber})]}),s.jsx(ve,{children:vd[k.type]||k.type}),s.jsx(ve,{variant:Rx[k.status]||"default",children:jd[k.status]||k.status}),Q&&s.jsx("span",{className:"text-xs text-gray-500 ml-2",children:"(Vorgänger)"})]}),s.jsx("div",{className:"flex gap-2",children:s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${k.id}`,{state:{from:"contracts"}}),title:"Ansehen",children:s.jsx(Ae,{className:"w-4 h-4"})})})]}),(k.providerName||((le=k.provider)==null?void 0:le.name))&&s.jsxs("p",{className:`flex items-center gap-1 ${Q?"ml-6":""}`,children:[k.providerName||((de=k.provider)==null?void 0:de.name),(k.tariffName||((Ke=k.tariff)==null?void 0:Ke.name))&&` - ${k.tariffName||((Ve=k.tariff)==null?void 0:Ve.name)}`,s.jsx(oe,{value:(k.providerName||((st=k.provider)==null?void 0:st.name)||"")+(k.tariffName||(C=k.tariff)!=null&&C.name?` - ${k.tariffName||((nt=k.tariff)==null?void 0:nt.name)}`:"")})]}),k.startDate&&s.jsxs("p",{className:`text-sm text-gray-500 ${Q?"ml-6":""}`,children:["Beginn: ",new Date(k.startDate).toLocaleDateString("de-DE"),k.endDate&&` | Ende: ${new Date(k.endDate).toLocaleDateString("de-DE")}`]})]}),(z===0&&_||z>0)&&K.length>0&&s.jsx("div",{className:"mt-2",children:R(K,z+1)})]},k.id)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Verträge"}),p("contracts:create")&&!b&&s.jsx(ke,{to:"/contracts/new",children:s.jsxs(T,{children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neuer Vertrag"]})})]}),s.jsx(X,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-4 flex-wrap",children:[s.jsx("div",{className:"flex-1 min-w-[200px]",children:s.jsx(H,{placeholder:"Suchen...",value:r,onChange:D=>a(D.target.value)})}),s.jsx(Ie,{value:i,onChange:D=>l(D.target.value),options:Object.entries(vd).map(([D,z])=>({value:D,label:z})),className:"w-48"}),s.jsx(Ie,{value:o,onChange:D=>c(D.target.value),options:Object.entries(jd).map(([D,z])=>({value:D,label:z})),className:"w-48"}),s.jsx(T,{variant:"secondary",children:s.jsx(Tl,{className:"w-4 h-4"})})]})}),P?s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."})}):E!=null&&E.data&&E.data.length>0?s.jsx(s.Fragment,{children:g&&A?s.jsx("div",{className:"space-y-6",children:A.map(D=>s.jsxs(X,{children:[s.jsx("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:D.isOwn?s.jsxs(s.Fragment,{children:[s.jsx(ii,{className:"w-5 h-5 text-blue-600"}),s.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"Meine Verträge"}),s.jsx(ve,{variant:"default",children:D.contracts.length})]}):s.jsxs(s.Fragment,{children:[s.jsx(Ca,{className:"w-5 h-5 text-purple-600"}),s.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:["Verträge von ",D.customerName]}),s.jsx(ve,{variant:"default",children:D.contracts.length})]})}),D.tree.length>0?s.jsx("div",{className:"space-y-4",children:D.tree.map(z=>q(z,0))}):s.jsx("p",{className:"text-gray-500",children:"Keine Verträge vorhanden."})]},D.isOwn?"own":D.customerName))}):s.jsxs(X,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Vertragsnr."}),!b&&s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kunde"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Typ"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Anbieter / Tarif"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:s.jsxs("span",{className:"flex items-center gap-1",children:["Status",s.jsx("button",{onClick:()=>f(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Ml,{className:"w-4 h-4"})})]})}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beginn"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:E.data.map(D=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono text-sm",children:D.contractNumber}),!b&&s.jsx("td",{className:"py-3 px-4",children:D.customer&&s.jsx(ke,{to:`/customers/${D.customer.id}`,className:"text-blue-600 hover:underline",children:D.customer.companyName||`${D.customer.firstName} ${D.customer.lastName}`})}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ve,{children:vd[D.type]})}),s.jsxs("td",{className:"py-3 px-4",children:[D.providerName||"-",D.tariffName&&s.jsxs("span",{className:"text-gray-500",children:[" / ",D.tariffName]})]}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ve,{variant:Rx[D.status],children:jd[D.status]})}),s.jsx("td",{className:"py-3 px-4",children:D.startDate?new Date(D.startDate).toLocaleDateString("de-DE"):"-"}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${D.id}`,{state:{from:"contracts"}}),children:s.jsx(Ae,{className:"w-4 h-4"})}),p("contracts:update")&&!b&&s.jsx(ke,{to:`/contracts/${D.id}/edit`,children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(He,{className:"w-4 h-4"})})}),p("contracts:delete")&&!b&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&N.mutate(D.id)},children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})})]},D.id))})]})}),E.pagination&&E.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",E.pagination.page," von ",E.pagination.totalPages," (",E.pagination.total," Einträge)"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>u(D=>Math.max(1,D-1)),disabled:d===1,children:"Zurück"}),s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>u(D=>D+1),disabled:d>=E.pagination.totalPages,children:"Weiter"})]})]})]})}):s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Verträge gefunden."})}),s.jsx(Zk,{isOpen:m,onClose:()=>f(!1)})]})}const Xk={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},Yk={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},eC={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"};function tC({contractId:e,isOpen:t,onClose:n}){var o,c,d,u,h,x,m,f,p,b,g;const{data:r,isLoading:a,error:i}=fe({queryKey:["contract",e],queryFn:()=>Oe.getById(e),enabled:t}),l=r==null?void 0:r.data;return s.jsxs(qe,{isOpen:t,onClose:n,title:"Vertragsdetails",size:"xl",children:[a&&s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}),i&&s.jsx("div",{className:"text-center py-8 text-red-600",children:"Fehler beim Laden des Vertrags"}),l&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3 pb-4 border-b",children:[s.jsxs("span",{className:"text-xl font-bold font-mono flex items-center gap-2",children:[l.contractNumber,s.jsx(oe,{value:l.contractNumber})]}),s.jsx(ve,{children:Xk[l.type]||l.type}),s.jsx(ve,{variant:eC[l.status]||"default",children:Yk[l.status]||l.status})]}),(l.providerName||((o=l.provider)==null?void 0:o.name)||l.tariffName||((c=l.tariff)==null?void 0:c.name))&&s.jsx(X,{title:"Anbieter & Tarif",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(l.providerName||((d=l.provider)==null?void 0:d.name))&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[l.providerName||((u=l.provider)==null?void 0:u.name),s.jsx(oe,{value:l.providerName||((h=l.provider)==null?void 0:h.name)||""})]})]}),(l.tariffName||((x=l.tariff)==null?void 0:x.name))&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Tarif"}),s.jsxs("dd",{className:"flex items-center gap-1",children:[l.tariffName||((m=l.tariff)==null?void 0:m.name),s.jsx(oe,{value:l.tariffName||((f=l.tariff)==null?void 0:f.name)||""})]})]}),l.customerNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer beim Anbieter"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.customerNumberAtProvider,s.jsx(oe,{value:l.customerNumberAtProvider})]})]}),l.contractNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer beim Anbieter"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.contractNumberAtProvider,s.jsx(oe,{value:l.contractNumberAtProvider})]})]})]})}),(l.type==="ELECTRICITY"||l.type==="GAS")&&((p=l.energyDetails)==null?void 0:p.meter)&&s.jsx(X,{title:"Zähler",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Zählernummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.energyDetails.meter.meterNumber,s.jsx(oe,{value:l.energyDetails.meter.meterNumber})]})]}),l.energyDetails.maloId&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"MaLo-ID"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.energyDetails.maloId,s.jsx(oe,{value:l.energyDetails.maloId})]})]})]})}),s.jsx(X,{title:"Laufzeit",children:s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[l.startDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsbeginn"}),s.jsx("dd",{children:new Date(l.startDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),l.endDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsende"}),s.jsx("dd",{children:new Date(l.endDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),l.contractDuration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Laufzeit"}),s.jsx("dd",{children:l.contractDuration.description})]}),l.cancellationPeriod&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsfrist"}),s.jsx("dd",{children:l.cancellationPeriod.description})]})]})}),(l.portalUsername||((b=l.provider)==null?void 0:b.portalUrl))&&s.jsx(X,{title:"Portal-Zugangsdaten",children:s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[((g=l.provider)==null?void 0:g.portalUrl)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Portal-URL"}),s.jsx("dd",{children:s.jsx("a",{href:l.provider.portalUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:l.provider.portalUrl})})]}),l.portalUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Benutzername"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.portalUsername,s.jsx(oe,{value:l.portalUsername})]})]})]})}),l.address&&s.jsxs(X,{title:"Lieferadresse",children:[s.jsxs("p",{children:[l.address.street," ",l.address.houseNumber]}),s.jsxs("p",{children:[l.address.postalCode," ",l.address.city]})]}),l.notes&&s.jsx(X,{title:"Notizen",children:s.jsx("p",{className:"whitespace-pre-wrap text-gray-700",children:l.notes})})]})]})}function sC({contractId:e,canEdit:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(null),c=ge(),{data:d,isLoading:u}=fe({queryKey:["contract-history",e],queryFn:()=>tc.getByContract(e)}),h=G({mutationFn:f=>tc.delete(e,f),onSuccess:()=>{c.invalidateQueries({queryKey:["contract-history",e]})}}),x=(d==null?void 0:d.data)||[],m=[...x].sort((f,p)=>new Date(p.createdAt).getTime()-new Date(f.createdAt).getTime());return s.jsxs("div",{className:"bg-white rounded-lg border p-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(zS,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Vertragshistorie"}),s.jsx(ve,{variant:"default",children:x.length})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[t&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>i(!0),children:s.jsx(_e,{className:"w-4 h-4"})}),x.length>0&&s.jsx("button",{onClick:()=>r(!n),className:"text-gray-500 hover:text-gray-700",children:n?s.jsx(Tc,{className:"w-4 h-4"}):s.jsx(dn,{className:"w-4 h-4"})})]})]}),u&&s.jsx("p",{className:"text-sm text-gray-500",children:"Laden..."}),!n&&!u&&m.length>0&&s.jsxs("div",{className:"text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:new Date(m[0].createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})})," - ",m[0].title]}),n&&!u&&m.length>0&&s.jsx("div",{className:"space-y-2",children:m.map(f=>s.jsxs("div",{className:"flex items-start justify-between p-3 bg-gray-50 rounded-lg group",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-sm font-medium text-gray-800",children:f.title}),f.isAutomatic?s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 text-xs rounded bg-blue-100 text-blue-700",title:"Automatisch erstellt",children:[s.jsx(AS,{className:"w-3 h-3"}),"Auto"]}):s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 text-xs rounded bg-gray-100 text-gray-600",title:"Manuell erstellt",children:[s.jsx(ii,{className:"w-3 h-3"}),"Manuell"]})]}),f.description&&s.jsx("p",{className:"text-sm text-gray-600 whitespace-pre-wrap mb-1",children:f.description}),s.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-400",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(on,{className:"w-3 h-3"}),new Date(f.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})]}),s.jsxs("span",{children:["von ",f.createdBy]})]})]}),t&&!f.isAutomatic&&s.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 ml-3",children:[s.jsx("button",{onClick:()=>o(f),className:"text-gray-500 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>{confirm("Eintrag wirklich löschen?")&&h.mutate(f.id)},className:"text-gray-500 hover:text-red-600",title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4"})})]})]},f.id))}),n&&!u&&m.length===0&&s.jsx("p",{className:"text-sm text-gray-500 italic",children:"Keine Historie vorhanden."}),(a||l)&&s.jsx(nC,{isOpen:!0,onClose:()=>{i(!1),o(null)},contractId:e,entry:l})]})}function nC({isOpen:e,onClose:t,contractId:n,entry:r}){const a=ge(),i=!!r,[l,o]=j.useState({title:(r==null?void 0:r.title)||"",description:(r==null?void 0:r.description)||""}),[c,d]=j.useState(null),u=G({mutationFn:()=>tc.create(n,{title:l.title,description:l.description||void 0}),onSuccess:()=>{a.invalidateQueries({queryKey:["contract-history",n]}),t()},onError:f=>{d(f.message)}}),h=G({mutationFn:()=>tc.update(n,r.id,{title:l.title,description:l.description||void 0}),onSuccess:()=>{a.invalidateQueries({queryKey:["contract-history",n]}),t()},onError:f=>{d(f.message)}}),x=f=>{if(f.preventDefault(),d(null),!l.title.trim()){d("Titel ist erforderlich");return}i?h.mutate():u.mutate()},m=u.isPending||h.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:i?"Eintrag bearbeiten":"Historie-Eintrag hinzufügen",children:s.jsxs("form",{onSubmit:x,className:"space-y-4",children:[c&&s.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm",children:c}),s.jsx(H,{label:"Titel *",value:l.title,onChange:f=>o({...l,title:f.target.value}),placeholder:"z.B. kWh auf 18000 erhöht",required:!0}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung (optional)"}),s.jsx("textarea",{value:l.description,onChange:f=>o({...l,description:f.target.value}),placeholder:"Weitere Details...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})]}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:m,children:m?"Wird gespeichert...":i?"Speichern":"Hinzufügen"})]})]})})}const Lx={INTERIM:"Zwischenrechnung",FINAL:"Schlussrechnung",NOT_AVAILABLE:"Nicht verfügbar"};function rC({ecdId:e,invoices:t,contractId:n,canEdit:r}){const[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=ge(),h=G({mutationFn:p=>aa.deleteInvoice(e,p),onSuccess:()=>{u.invalidateQueries({queryKey:["contract",n.toString()]})}}),x=[...t].sort((p,b)=>new Date(b.invoiceDate).getTime()-new Date(p.invoiceDate).getTime()),m=t.some(p=>p.invoiceType==="FINAL"),f=t.some(p=>p.invoiceType==="NOT_AVAILABLE");return s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Be,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Rechnungen"}),s.jsx(ve,{variant:"default",children:t.length}),m?s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-green-100 text-green-800",children:[s.jsx(xr,{className:"w-3 h-3"}),"Schlussrechnung"]}):f?s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Nicht verfügbar"]}):t.length>0?s.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-orange-100 text-orange-800",children:[s.jsx(hs,{className:"w-3 h-3"}),"Schlussrechnung fehlt"]}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>o(!0),children:s.jsx(_e,{className:"w-4 h-4"})}),t.length>0&&s.jsx("button",{onClick:()=>i(!a),className:"text-gray-500 hover:text-gray-700",children:a?s.jsx(Tc,{className:"w-4 h-4"}):s.jsx(dn,{className:"w-4 h-4"})})]})]}),!a&&x.length>0&&s.jsxs("div",{className:"text-sm text-gray-600",children:["Letzte: ",new Date(x[0].invoiceDate).toLocaleDateString("de-DE")," - ",Lx[x[0].invoiceType]]}),a&&x.length>0&&s.jsx("div",{className:"space-y-2",children:x.map(p=>s.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg group",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium",children:new Date(p.invoiceDate).toLocaleDateString("de-DE")}),s.jsx("div",{className:"text-xs text-gray-500",children:Lx[p.invoiceType]})]}),p.documentPath&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("a",{href:`/api${p.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm",title:"Anzeigen",children:s.jsx(Ae,{className:"w-4 h-4"})}),s.jsx("a",{href:`/api${p.documentPath}`,download:!0,className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm",title:"Download",children:s.jsx(Ps,{className:"w-4 h-4"})})]}),p.notes&&s.jsx("span",{className:"text-xs text-gray-400 italic",children:p.notes})]}),r&&s.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100",children:[s.jsx("button",{onClick:()=>d(p),className:"text-gray-500 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>{confirm("Rechnung wirklich löschen?")&&h.mutate(p.id)},className:"text-gray-500 hover:text-red-600",title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4"})})]})]},p.id))}),a&&x.length===0&&s.jsx("p",{className:"text-sm text-gray-500 italic",children:"Keine Rechnungen vorhanden."}),(l||c)&&s.jsx(aC,{isOpen:!0,onClose:()=>{o(!1),d(null)},ecdId:e,contractId:n,invoice:c})]})}function aC({isOpen:e,onClose:t,ecdId:n,contractId:r,invoice:a}){const i=ge(),l=!!a,o=j.useRef(null),[c,d]=j.useState({invoiceDate:a!=null&&a.invoiceDate?new Date(a.invoiceDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],invoiceType:(a==null?void 0:a.invoiceType)||"INTERIM",notes:(a==null?void 0:a.notes)||""}),[u,h]=j.useState(null),[x,m]=j.useState(null),f=G({mutationFn:async N=>{var P;const E=await aa.addInvoice(n,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return(P=E.data)!=null&&P.id&&await aa.uploadDocument(E.data.id,N),E},onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:N=>{m(N.message)}}),p=G({mutationFn:async()=>await aa.addInvoice(n,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0}),onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:N=>{m(N.message)}}),b=G({mutationFn:async N=>{const E=await aa.updateInvoice(n,a.id,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return N&&await aa.uploadDocument(a.id,N),E},onSuccess:()=>{i.invalidateQueries({queryKey:["contract",r.toString()]}),t()},onError:N=>{m(N.message)}}),g=N=>{if(N.preventDefault(),m(null),l){if(c.invoiceType!=="NOT_AVAILABLE"&&!(a!=null&&a.documentPath)&&!u){m("Bitte laden Sie ein Dokument hoch");return}b.mutate(u)}else if(c.invoiceType==="NOT_AVAILABLE")p.mutate();else if(u)f.mutate(u);else{m("Bitte laden Sie ein Dokument hoch");return}},y=N=>{var P;const E=(P=N.target.files)==null?void 0:P[0];if(E){if(E.type!=="application/pdf"){m("Nur PDF-Dateien sind erlaubt");return}if(E.size>10*1024*1024){m("Datei ist zu groß (max. 10 MB)");return}h(E),m(null)}},v=f.isPending||p.isPending||b.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:l?"Rechnung bearbeiten":"Rechnung hinzufügen",children:s.jsxs("form",{onSubmit:g,className:"space-y-4",children:[x&&s.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm",children:x}),s.jsx(H,{label:"Rechnungsdatum",type:"date",value:c.invoiceDate,onChange:N=>d({...c,invoiceDate:N.target.value}),required:!0}),s.jsx(Ie,{label:"Rechnungstyp",value:c.invoiceType,onChange:N=>d({...c,invoiceType:N.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"},{value:"NOT_AVAILABLE",label:"Nicht verfügbar"}]}),c.invoiceType!=="NOT_AVAILABLE"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Dokument (PDF) *"}),(a==null?void 0:a.documentPath)&&!u&&s.jsxs("div",{className:"mb-2 text-sm text-green-600 flex items-center gap-1",children:[s.jsx(xr,{className:"w-4 h-4"}),"Dokument vorhanden"]}),u&&s.jsxs("div",{className:"mb-2 text-sm text-blue-600 flex items-center gap-1",children:[s.jsx(Be,{className:"w-4 h-4"}),u.name]}),s.jsx("input",{type:"file",ref:o,accept:".pdf",onChange:y,className:"hidden"}),s.jsx(T,{type:"button",variant:"secondary",onClick:()=>{var N;return(N=o.current)==null?void 0:N.click()},children:a!=null&&a.documentPath||u?"Ersetzen":"PDF hochladen"})]}),c.invoiceType==="NOT_AVAILABLE"&&s.jsx("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-800 text-sm",children:'Bei diesem Typ wird kein Dokument benötigt. Die Rechnung wird als "nicht mehr zu bekommen" markiert.'}),s.jsx(H,{label:"Notizen (optional)",value:c.notes,onChange:N=>d({...c,notes:N.target.value}),placeholder:"Optionale Anmerkungen..."}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:v,children:v?"Wird gespeichert...":l?"Speichern":"Hinzufügen"})]})]})})}const iC=10.5;function Ox(e,t){const n=new Date(e),r=new Date(t);n.setHours(0,0,0,0),r.setHours(0,0,0,0);const a=r.getTime()-n.getTime();return Math.ceil(a/(1e3*60*60*24))}function lC(e,t,n){const r=new Date(t),a=new Date(n);return r.setHours(0,0,0,0),a.setHours(0,0,0,0),e.filter(i=>{const l=new Date(i.readingDate);return l.setHours(0,0,0,0),l>=r&&l<=a})}function oC(e,t,n,r){const a=lC(e,t,n);if(a.length===0)return{type:"none",consumptionKwh:0};if(a.length===1)return{type:"insufficient",consumptionKwh:0,message:"Berechnung auf Grund fehlender Stände nicht möglich"};const i=[...a].sort((f,p)=>new Date(f.readingDate).getTime()-new Date(p.readingDate).getTime()),l=i[0],o=i[i.length-1],c=new Date(o.readingDate),d=new Date(n);if(c.setHours(0,0,0,0),d.setHours(0,0,0,0),c>=d){const f=o.value-l.value;return zx("exact",f,r,l,o)}const u=Ox(l.readingDate,o.readingDate);if(u<1)return{type:"insufficient",consumptionKwh:0,message:"Zeitraum zwischen Zählerständen zu kurz für Berechnung"};const h=Ox(t,n),m=(o.value-l.value)/u*h;return zx("projected",m,r,l,o,n)}function zx(e,t,n,r,a,i){return n==="GAS"?{type:e,consumptionM3:t,consumptionKwh:t*iC,startReading:r,endReading:a,projectedEndDate:i}:{type:e,consumptionKwh:t,startReading:r,endReading:a,projectedEndDate:i}}function cC(e,t,n,r){if(t==null&&n==null)return null;const a=(t??0)*12,i=e*(n??0),l=a+i,o=l-(r??0),c=o/12;return{annualBaseCost:a,annualConsumptionCost:i,annualTotalCost:l,monthlyPayment:c,bonus:r??void 0,effectiveAnnualCost:o}}const dC={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},uC={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},mC={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},hC=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function fC({isOpen:e,onClose:t}){return e?s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:t}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600",children:s.jsx(qt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:hC.map(({status:n,label:r,description:a,color:i})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${i}`,children:r}),s.jsx("span",{className:"text-sm text-gray-600",children:a})]},n))})]})]}):null}function pC(e){const t=e.match(/^(\d+)([TMWJ])$/);if(!t)return!1;const n=parseInt(t[1]),r=t[2];let a=0;return r==="T"?a=n:r==="W"?a=n*7:r==="M"?a=n*30:r==="J"&&(a=n*365),a<=30}function xC({simCard:e}){const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1),o=async()=>{if(t)n(!1),a(null);else{l(!0);try{const c=await Oe.getSimCardCredentials(e.id);c.data&&(a(c.data),n(!0))}catch{alert("PIN/PUK konnte nicht geladen werden")}finally{l(!1)}}};return s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.isMain&&s.jsx(ve,{variant:"success",children:"Hauptkarte"}),e.isMultisim&&s.jsx(ve,{variant:"warning",children:"Multisim"})]}),s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[e.phoneNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Rufnummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[e.phoneNumber,s.jsx(oe,{value:e.phoneNumber})]})]}),e.simCardNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIM-Nr."}),s.jsxs("dd",{className:"font-mono text-xs flex items-center gap-1",children:[e.simCardNumber,s.jsx(oe,{value:e.simCardNumber})]})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"PIN"}),s.jsx("dd",{className:"font-mono flex items-center gap-1",children:t&&(r!=null&&r.pin)?s.jsxs(s.Fragment,{children:[r.pin,s.jsx(oe,{value:r.pin})]}):"••••"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"PUK"}),s.jsx("dd",{className:"font-mono flex items-center gap-1",children:t&&(r!=null&&r.puk)?s.jsxs(s.Fragment,{children:[r.puk,s.jsx(oe,{value:r.puk})]}):"••••••••"})]})]}),s.jsx("div",{className:"mt-2",children:s.jsx(T,{variant:"ghost",size:"sm",onClick:o,disabled:i,children:i?"Laden...":t?s.jsxs(s.Fragment,{children:[s.jsx(It,{className:"w-4 h-4 mr-1"})," PIN/PUK verbergen"]}):s.jsxs(s.Fragment,{children:[s.jsx(Ae,{className:"w-4 h-4 mr-1"})," PIN/PUK anzeigen"]})})})]})}function gC({meterId:e,meterType:t,readings:n,contractId:r,canEdit:a}){const[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),h=ge(),x=G({mutationFn:p=>ln.deleteReading(e,p),onSuccess:()=>{h.invalidateQueries({queryKey:["contract",r.toString()]})}}),m=[...n].sort((p,b)=>new Date(b.readingDate).getTime()-new Date(p.readingDate).getTime()),f=t==="ELECTRICITY"?"kWh":"m³";return s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ev,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Zählerstände"}),s.jsx(ve,{variant:"default",children:n.length})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[a&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>c(!0),title:"Zählerstand erfassen",children:s.jsx(_e,{className:"w-4 h-4"})}),n.length>0&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>l(!i),children:i?s.jsx(Tc,{className:"w-4 h-4"}):s.jsx(dn,{className:"w-4 h-4"})})]})]}),i&&n.length>0&&s.jsx("div",{className:"space-y-2 bg-gray-50 rounded-lg p-3",children:m.map(p=>s.jsxs("div",{className:"flex justify-between items-center text-sm group py-1 border-b border-gray-200 last:border-0",children:[s.jsxs("span",{className:"text-gray-500 flex items-center gap-1",children:[new Date(p.readingDate).toLocaleDateString("de-DE"),s.jsx(oe,{value:new Date(p.readingDate).toLocaleDateString("de-DE")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"font-mono flex items-center gap-1",children:[p.value.toLocaleString("de-DE")," ",p.unit,s.jsx(oe,{value:p.value.toString(),title:"Nur Wert kopieren"})]}),a&&s.jsxs("div",{className:"opacity-0 group-hover:opacity-100 flex gap-1",children:[s.jsx("button",{onClick:()=>u(p),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:s.jsx(He,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&x.mutate(p.id)},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:s.jsx(Ne,{className:"w-3 h-3"})})]})]})]},p.id))}),!i&&n.length>0&&s.jsxs("p",{className:"text-sm text-gray-500",children:["Letzter Stand: ",m[0].value.toLocaleString("de-DE")," ",m[0].unit," (",new Date(m[0].readingDate).toLocaleDateString("de-DE"),")"]}),n.length===0&&s.jsx("p",{className:"text-sm text-gray-500",children:"Keine Zählerstände vorhanden."}),(o||d)&&s.jsx(yC,{isOpen:!0,onClose:()=>{c(!1),u(null)},meterId:e,contractId:r,reading:d,defaultUnit:f})]})}function yC({isOpen:e,onClose:t,meterId:n,contractId:r,reading:a,defaultUnit:i}){var f;const l=ge(),o=!!a,[c,d]=j.useState({readingDate:a!=null&&a.readingDate?new Date(a.readingDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],value:((f=a==null?void 0:a.value)==null?void 0:f.toString())||"",notes:(a==null?void 0:a.notes)||""}),u=G({mutationFn:p=>ln.addReading(n,p),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",r.toString()]}),t()}}),h=G({mutationFn:p=>ln.updateReading(n,a.id,p),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",r.toString()]}),t()}}),x=p=>{p.preventDefault();const b={readingDate:new Date(c.readingDate),value:parseFloat(c.value),unit:i,notes:c.notes||void 0};o?h.mutate(b):u.mutate(b)},m=u.isPending||h.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:o?"Zählerstand bearbeiten":"Zählerstand erfassen",children:s.jsxs("form",{onSubmit:x,className:"space-y-4",children:[s.jsx(H,{label:"Ablesedatum",type:"date",value:c.readingDate,onChange:p=>d({...c,readingDate:p.target.value}),required:!0}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsx("div",{className:"col-span-2",children:s.jsx(H,{label:"Zählerstand",type:"number",step:"0.01",value:c.value,onChange:p=>d({...c,value:p.target.value}),required:!0})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Einheit"}),s.jsx("div",{className:"h-10 flex items-center px-3 bg-gray-100 border border-gray-300 rounded-md text-gray-700",children:i})]})]}),s.jsx(H,{label:"Notizen (optional)",value:c.notes,onChange:p=>d({...c,notes:p.target.value})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:m||!c.value,children:m?"Speichern...":o?"Speichern":"Erfassen"})]})]})})}function vC({contractType:e,readings:t,startDate:n,endDate:r,basePrice:a,unitPrice:i,bonus:l}){const o=oC(t,n,r,e),c=o.consumptionKwh>0?cC(o.consumptionKwh,a,i,l):null;if(o.type==="none")return null;const d=(h,x=2)=>h.toLocaleString("de-DE",{minimumFractionDigits:x,maximumFractionDigits:x}),u=h=>new Date(h).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"});return s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(TS,{className:"w-4 h-4 text-gray-500"}),s.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Verbrauch & Kosten"}),o.type==="exact"&&s.jsx(ve,{variant:"success",children:"Exakt"}),o.type==="projected"&&s.jsx(ve,{variant:"warning",children:"Hochrechnung"})]}),o.type==="insufficient"?s.jsx("p",{className:"text-sm text-gray-500 italic",children:o.message}):s.jsxs("div",{className:"bg-gray-50 rounded-lg p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("h5",{className:"text-sm font-medium text-gray-600 mb-2",children:["Berechneter Verbrauch",o.type==="projected"&&" (hochgerechnet)"]}),s.jsx("div",{className:"text-lg font-semibold text-gray-900",children:e==="GAS"?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"font-mono",children:[d(o.consumptionM3||0)," m³"]}),s.jsxs("span",{className:"text-gray-500 text-sm ml-2",children:["= ",d(o.consumptionKwh)," kWh"]})]}):s.jsxs("span",{className:"font-mono",children:[d(o.consumptionKwh)," kWh"]})}),o.startReading&&o.endReading&&s.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:["Basierend auf Zählerständen vom ",u(o.startReading.readingDate)," bis ",u(o.endReading.readingDate)]})]}),c&&s.jsxs("div",{className:"border-t border-gray-200 pt-4",children:[s.jsx("h5",{className:"text-sm font-medium text-gray-600 mb-3",children:"Kostenvorschau"}),s.jsxs("div",{className:"space-y-2 text-sm",children:[a!=null&&a>0&&s.jsxs("div",{className:"flex justify-between",children:[s.jsxs("span",{className:"text-gray-600",children:["Grundpreis: ",d(a)," €/Mon × 12"]}),s.jsxs("span",{className:"font-mono",children:[d(c.annualBaseCost)," €"]})]}),i!=null&&i>0&&s.jsxs("div",{className:"flex justify-between",children:[s.jsxs("span",{className:"text-gray-600",children:["Arbeitspreis: ",d(o.consumptionKwh)," kWh × ",d(i,4)," €"]}),s.jsxs("span",{className:"font-mono",children:[d(c.annualConsumptionCost)," €"]})]}),s.jsx("div",{className:"border-t border-gray-300 pt-2",children:s.jsxs("div",{className:"flex justify-between font-medium",children:[s.jsx("span",{className:"text-gray-700",children:"Jahreskosten"}),s.jsxs("span",{className:"font-mono",children:[d(c.annualTotalCost)," €"]})]})}),c.bonus!=null&&c.bonus>0&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex justify-between text-green-600",children:[s.jsx("span",{children:"Bonus"}),s.jsxs("span",{className:"font-mono",children:["- ",d(c.bonus)," €"]})]}),s.jsx("div",{className:"border-t border-gray-300 pt-2",children:s.jsxs("div",{className:"flex justify-between font-semibold",children:[s.jsx("span",{className:"text-gray-800",children:"Effektive Jahreskosten"}),s.jsxs("span",{className:"font-mono",children:[d(c.effectiveAnnualCost)," €"]})]})})]}),s.jsx("div",{className:"border-t border-gray-300 pt-2 mt-2",children:s.jsxs("div",{className:"flex justify-between text-blue-700 font-semibold",children:[s.jsx("span",{children:"Monatlicher Abschlag"}),s.jsxs("span",{className:"font-mono",children:[d(c.monthlyPayment)," €"]})]})})]})]})]})]})}function $x({task:e,contractId:t,canEdit:n,isCustomerPortal:r,isCompleted:a,onEdit:i}){const[l,o]=j.useState(""),[c,d]=j.useState(!1),[u,h]=j.useState(null),[x,m]=j.useState(""),f=ge(),p=G({mutationFn:K=>et.complete(K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),b=G({mutationFn:K=>et.reopen(K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),g=G({mutationFn:K=>et.delete(K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),y=G({mutationFn:K=>et.createSubtask(e.id,K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]}),o(""),d(!1)},onError:K=>{console.error("Fehler beim Erstellen der Unteraufgabe:",K),alert("Fehler beim Erstellen der Unteraufgabe. Bitte versuchen Sie es erneut.")}}),v=G({mutationFn:K=>et.createReply(e.id,K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]}),o(""),d(!1)},onError:K=>{console.error("Fehler beim Erstellen der Antwort:",K),alert("Fehler beim Erstellen der Antwort. Bitte versuchen Sie es erneut.")}}),N=G({mutationFn:({id:K,title:B})=>et.updateSubtask(K,B),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]}),h(null),m("")}}),E=G({mutationFn:K=>et.completeSubtask(K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),P=G({mutationFn:K=>et.reopenSubtask(K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),I=G({mutationFn:K=>et.deleteSubtask(K),onSuccess:async()=>{await f.refetchQueries({queryKey:["contract-tasks",t]})}}),w=K=>{K.preventDefault(),l.trim()&&(r?v.mutate(l.trim()):y.mutate(l.trim()))},S=K=>{K.preventDefault(),x.trim()&&u&&N.mutate({id:u,title:x.trim()})},A=(K,B)=>{h(K),m(B)},O=()=>{h(null),m("")},R=e.subtasks||[],q=R.filter(K=>K.status==="OPEN"),D=R.filter(K=>K.status==="COMPLETED"),z=r?{singular:"Antwort",placeholder:"Antwort...",deleteConfirm:"Antwort löschen?"}:{singular:"Unteraufgabe",placeholder:"Unteraufgabe...",deleteConfirm:"Unteraufgabe löschen?"},k=(K,B)=>u===K.id?s.jsx("div",{className:"py-1",children:s.jsxs("form",{onSubmit:S,className:"flex items-center gap-2",children:[s.jsx(No,{className:"w-4 h-4 text-gray-300 flex-shrink-0"}),s.jsx("input",{type:"text",value:x,onChange:Q=>m(Q.target.value),className:"flex-1 text-sm px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500",autoFocus:!0}),s.jsx(T,{type:"submit",size:"sm",disabled:!x.trim()||N.isPending,children:"✓"}),s.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:O,children:"×"})]})},K.id):s.jsx("div",{className:`py-1 group/subtask ${B?"opacity-60":""}`,children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("button",{onClick:()=>B?P.mutate(K.id):E.mutate(K.id),disabled:E.isPending||P.isPending||r,className:`flex-shrink-0 mt-0.5 ${r?"cursor-default":B?"hover:text-yellow-600":"hover:text-green-600"}`,children:B?s.jsx(As,{className:"w-4 h-4 text-green-500"}):s.jsx(No,{className:"w-4 h-4 text-gray-400"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("span",{className:`text-sm ${B?"line-through text-gray-500":""}`,children:K.title}),n&&!r&&!B&&s.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover/subtask:opacity-100",children:[s.jsx("button",{onClick:()=>A(K.id,K.title),className:"text-gray-400 hover:text-blue-600 p-0.5",title:"Bearbeiten",children:s.jsx(He,{className:"w-3 h-3"})}),s.jsx("button",{onClick:()=>{confirm(z.deleteConfirm)&&I.mutate(K.id)},className:"text-gray-400 hover:text-red-600 p-0.5",title:"Löschen",children:s.jsx(Ne,{className:"w-3 h-3"})})]}),n&&!r&&B&&s.jsx("button",{onClick:()=>{confirm(z.deleteConfirm)&&I.mutate(K.id)},className:"text-gray-400 hover:text-red-600 p-0.5 opacity-0 group-hover/subtask:opacity-100",title:"Löschen",children:s.jsx(Ne,{className:"w-3 h-3"})})]}),s.jsxs("p",{className:"text-xs text-gray-400",children:[K.createdBy&&`${K.createdBy} • `,B?`Erledigt am ${K.completedAt?new Date(K.completedAt).toLocaleDateString("de-DE"):new Date(K.updatedAt).toLocaleDateString("de-DE")}`:new Date(K.createdAt).toLocaleDateString("de-DE")]})]})]})},K.id);return s.jsx("div",{className:`p-3 bg-gray-50 rounded-lg group ${a?"bg-gray-50/50 opacity-70":""}`,children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("button",{onClick:()=>a?b.mutate(e.id):p.mutate(e.id),disabled:p.isPending||b.isPending||r,className:`mt-0.5 flex-shrink-0 ${r?"cursor-default":a?"hover:text-yellow-600":"hover:text-green-600"}`,title:r?void 0:a?"Wieder öffnen":"Als erledigt markieren",children:a?s.jsx(As,{className:"w-5 h-5 text-green-500"}):s.jsx(No,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-medium ${a?"line-through text-gray-500":""}`,children:e.title}),e.visibleInPortal&&s.jsx(ve,{variant:"default",className:"text-xs",children:"Portal"}),R.length>0&&s.jsxs("span",{className:"text-xs text-gray-400",children:["(",D.length,"/",R.length,")"]})]}),e.description&&s.jsx("p",{className:`text-sm mt-1 whitespace-pre-wrap ${a?"text-gray-500":"text-gray-600"}`,children:e.description}),s.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:[e.createdBy&&`${e.createdBy} • `,a?`Erledigt am ${e.completedAt?new Date(e.completedAt).toLocaleDateString("de-DE"):"-"}`:new Date(e.createdAt).toLocaleDateString("de-DE")]}),R.length>0&&s.jsxs("div",{className:"mt-3 ml-2 space-y-0 border-l-2 border-gray-200 pl-3",children:[q.map(K=>k(K,!1)),D.map(K=>k(K,!0))]}),!a&&(n&&!r||r)&&s.jsx("div",{className:"mt-2 ml-2",children:c?s.jsxs("form",{onSubmit:w,className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:l,onChange:K=>o(K.target.value),placeholder:z.placeholder,className:"flex-1 text-sm px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500",autoFocus:!0}),s.jsx(T,{type:"submit",size:"sm",disabled:!l.trim()||y.isPending||v.isPending,children:s.jsx(_e,{className:"w-3 h-3"})}),s.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:()=>{d(!1),o("")},children:"×"})]}):s.jsxs("button",{onClick:()=>d(!0),className:"text-xs text-gray-400 hover:text-blue-600 flex items-center gap-1",children:[s.jsx(_e,{className:"w-3 h-3"}),z.singular]})})]}),n&&!r&&s.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100",children:[!a&&s.jsx("button",{onClick:i,className:"text-gray-400 hover:text-blue-600 p-1",title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>{confirm("Aufgabe wirklich löschen?")&&g.mutate(e.id)},className:"text-gray-400 hover:text-red-600 p-1",title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4"})})]})]})})}function jC({contractId:e,canEdit:t,isCustomerPortal:n}){var v;const[r,a]=j.useState(!1),[i,l]=j.useState(null),{data:o,isLoading:c}=fe({queryKey:["contract-tasks",e],queryFn:()=>et.getByContract(e),staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:d,isLoading:u}=fe({queryKey:["app-settings-public"],queryFn:()=>Xr.getPublic(),enabled:n,staleTime:0}),h=!u&&((v=d==null?void 0:d.data)==null?void 0:v.customerSupportTicketsEnabled)==="true",x=(o==null?void 0:o.data)||[],m=x.filter(N=>N.status==="OPEN"),f=x.filter(N=>N.status==="COMPLETED"),p=n?{title:"Support-Anfragen",button:"Anfrage erstellen",empty:"Keine Support-Anfragen vorhanden."}:{title:"Aufgaben",button:"Aufgabe",empty:"Keine Aufgaben vorhanden."},b=n?ul:dl;if(c||n&&u)return s.jsx(X,{className:"mb-6",title:p.title,children:s.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."})});const y=t&&!n||n&&h;return s.jsxs(X,{className:"mb-6",title:p.title,children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(b,{className:"w-5 h-5 text-gray-500"}),s.jsxs("span",{className:"text-sm text-gray-600",children:[m.length," offen, ",f.length," erledigt"]})]}),y&&s.jsxs(T,{size:"sm",onClick:()=>a(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-1"}),p.button]})]}),x.length===0?s.jsx("p",{className:"text-center py-4 text-gray-500",children:p.empty}):s.jsxs("div",{className:"space-y-2",children:[m.map(N=>s.jsx($x,{task:N,contractId:e,canEdit:t,isCustomerPortal:n,isCompleted:!1,onEdit:()=>l(N)},N.id)),f.length>0&&m.length>0&&s.jsx("div",{className:"border-t my-3"}),f.map(N=>s.jsx($x,{task:N,contractId:e,canEdit:t,isCustomerPortal:n,isCompleted:!0,onEdit:()=>{}},N.id))]}),(r||i)&&s.jsx(bC,{isOpen:!0,onClose:()=>{a(!1),l(null)},contractId:e,task:i,isCustomerPortal:n})]})}function bC({isOpen:e,onClose:t,contractId:n,task:r,isCustomerPortal:a=!1}){const i=ge(),l=!!r,[o,c]=j.useState({title:(r==null?void 0:r.title)||"",description:(r==null?void 0:r.description)||"",visibleInPortal:(r==null?void 0:r.visibleInPortal)||!1});j.useEffect(()=>{e&&c({title:(r==null?void 0:r.title)||"",description:(r==null?void 0:r.description)||"",visibleInPortal:(r==null?void 0:r.visibleInPortal)||!1})},[e,r]);const d=G({mutationFn:p=>et.create(n,p),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),u=G({mutationFn:p=>et.createSupportTicket(n,p),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),h=G({mutationFn:p=>et.update(r.id,p),onSuccess:async()=>{await i.refetchQueries({queryKey:["contract-tasks",n]}),t()}}),x=p=>{p.preventDefault(),l?h.mutate({title:o.title,description:o.description||void 0,visibleInPortal:o.visibleInPortal}):a?u.mutate({title:o.title,description:o.description||void 0}):d.mutate({title:o.title,description:o.description||void 0,visibleInPortal:o.visibleInPortal})},m=d.isPending||u.isPending||h.isPending,f=a?{modalTitle:l?"Anfrage bearbeiten":"Neue Support-Anfrage",titleLabel:"Betreff",titlePlaceholder:"Kurze Beschreibung Ihrer Anfrage",descLabel:"Ihre Nachricht",descPlaceholder:"Beschreiben Sie Ihr Anliegen...",submitBtn:l?"Speichern":"Anfrage senden"}:{modalTitle:l?"Aufgabe bearbeiten":"Neue Aufgabe",titleLabel:"Titel",titlePlaceholder:"Kurze Beschreibung der Aufgabe",descLabel:"Beschreibung (optional)",descPlaceholder:"Details zur Aufgabe...",submitBtn:l?"Speichern":"Erstellen"};return s.jsx(qe,{isOpen:e,onClose:t,title:f.modalTitle,children:s.jsxs("form",{onSubmit:x,className:"space-y-4",children:[s.jsx(H,{label:f.titleLabel,value:o.title,onChange:p=>c({...o,title:p.target.value}),required:!0,placeholder:f.titlePlaceholder}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:f.descLabel}),s.jsx("textarea",{value:o.description,onChange:p=>c({...o,description:p.target.value}),className:"w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",rows:a?5:3,placeholder:f.descPlaceholder})]}),!a&&s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:o.visibleInPortal,onChange:p=>c({...o,visibleInPortal:p.target.checked}),className:"w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),s.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:m||!o.title.trim(),children:m?"Speichern...":f.submitBtn})]})]})})}function NC(){var nt,es,Vt,ae,Ge,xt;const{id:e}=Nc(),t=Yt(),r=Rn().state,a=ge(),{hasPermission:i,isCustomer:l,isCustomerPortal:o}=We(),c=parseInt(e),[d,u]=j.useState(!1),[h,x]=j.useState(null),[m,f]=j.useState(!1),[p,b]=j.useState(!1),[g,y]=j.useState(null),[v,N]=j.useState({}),[E,P]=j.useState({}),[I,w]=j.useState(!1),[S,A]=j.useState(!1),[O,R]=j.useState(!1),[q,D]=j.useState(!1),{data:z,isLoading:k}=fe({queryKey:["contract",e],queryFn:()=>Oe.getById(c)}),K=G({mutationFn:()=>Oe.delete(c),onSuccess:()=>{t("/contracts")}}),B=G({mutationFn:()=>Oe.createFollowUp(c),onSuccess:Z=>{Z.data?t(`/contracts/${Z.data.id}/edit`):alert("Folgevertrag wurde erstellt, aber keine ID zurückgegeben")},onError:Z=>{console.error("Folgevertrag Fehler:",Z),alert(`Fehler beim Erstellen des Folgevertrags: ${Z instanceof Error?Z.message:"Unbekannter Fehler"}`)}}),_=G({mutationFn:()=>Oe.snooze(c,{}),onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]}),D(!1)},onError:Z=>{console.error("Un-Snooze Fehler:",Z),alert(`Fehler beim Aufheben der Zurückstellung: ${Z instanceof Error?Z.message:"Unbekannter Fehler"}`)}}),Q=G({mutationFn:Z=>{const Xe={cancellationConfirmationDate:Z?new Date(Z).toISOString():null};return Oe.update(c,Xe)},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]})},onError:Z=>{console.error("Fehler beim Speichern des Datums:",Z),alert("Fehler beim Speichern des Datums")}}),le=G({mutationFn:Z=>{const Xe={cancellationConfirmationOptionsDate:Z?new Date(Z).toISOString():null};return Oe.update(c,Xe)},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",e]}),a.invalidateQueries({queryKey:["contract-cockpit"]})},onError:Z=>{console.error("Fehler beim Speichern des Datums:",Z),alert("Fehler beim Speichern des Datums")}}),de=async()=>{var Z;if(d)u(!1),x(null);else try{const Fe=await Oe.getPassword(c);(Z=Fe.data)!=null&&Z.password&&(x(Fe.data.password),u(!0))}catch{alert("Passwort konnte nicht entschlüsselt werden")}},Ke=async()=>{var Z;if(p)b(!1),y(null);else try{const Fe=await Oe.getInternetCredentials(c);(Z=Fe.data)!=null&&Z.password&&(y(Fe.data.password),b(!0))}catch{alert("Internet-Passwort konnte nicht entschlüsselt werden")}},Ve=async Z=>{var Fe;if(v[Z])N(Xe=>({...Xe,[Z]:!1})),P(Xe=>({...Xe,[Z]:null}));else try{const J=(Fe=(await Oe.getSipCredentials(Z)).data)==null?void 0:Fe.password;J&&(P(ue=>({...ue,[Z]:J})),N(ue=>({...ue,[Z]:!0})))}catch{alert("SIP-Passwort konnte nicht entschlüsselt werden")}},st=async()=>{var Xe,J,ue;const Z=z==null?void 0:z.data,Fe=((Xe=Z==null?void 0:Z.stressfreiEmail)==null?void 0:Xe.email)||(Z==null?void 0:Z.portalUsername);if(!((J=Z==null?void 0:Z.provider)!=null&&J.portalUrl)||!Fe){alert("Portal-URL oder Benutzername fehlt");return}f(!0);try{const ts=await Oe.getPassword(c);if(!((ue=ts.data)!=null&&ue.password)){alert("Passwort konnte nicht entschlüsselt werden");return}const un=Z.provider,gt=un.portalUrl,L=un.usernameFieldName||"username",U=un.passwordFieldName||"password",W=new URL(gt);W.searchParams.set(L,Fe),W.searchParams.set(U,ts.data.password),window.open(W.toString(),"_blank")}catch{alert("Fehler beim Auto-Login")}finally{f(!1)}};if(k)return s.jsx("div",{className:"text-center py-8",children:"Laden..."});if(!(z!=null&&z.data))return s.jsx("div",{className:"text-center py-8 text-red-600",children:"Vertrag nicht gefunden"});const C=z.data;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{if((r==null?void 0:r.from)==="customer"&&(r!=null&&r.customerId))t(`/customers/${r.customerId}?tab=contracts`);else if((r==null?void 0:r.from)==="cockpit"){const Z=r.filter?`?filter=${r.filter}`:"";t(`/contracts/cockpit${Z}`)}else(r==null?void 0:r.from)==="contracts"?t("/contracts"):C.customer?t(`/customers/${C.customer.id}?tab=contracts`):t("/contracts")},children:s.jsx(Vs,{className:"w-4 h-4"})}),s.jsx("h1",{className:"text-2xl font-bold",children:C.contractNumber}),s.jsx(ve,{children:dC[C.type]}),s.jsx(ve,{variant:mC[C.status],children:uC[C.status]}),s.jsx("button",{onClick:()=>R(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Ml,{className:"w-4 h-4"})}),C.nextReviewDate&&new Date(C.nextReviewDate)>new Date&&s.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-amber-100 text-amber-800 rounded-full text-xs",children:[s.jsx(wv,{className:"w-3 h-3"}),s.jsxs("span",{children:["Zurückgestellt bis ",new Date(C.nextReviewDate).toLocaleDateString("de-DE")]}),i("contracts:update")&&s.jsx("button",{onClick:()=>D(!0),className:"ml-1 p-0.5 hover:bg-amber-200 rounded",title:"Zurückstellung aufheben",children:s.jsx(qt,{className:"w-3 h-3"})})]})]}),C.customer&&s.jsxs("p",{className:"text-gray-500 ml-10",children:["Kunde:"," ",s.jsx(ke,{to:`/customers/${C.customer.id}`,className:"text-blue-600 hover:underline",children:C.customer.companyName||`${C.customer.firstName} ${C.customer.lastName}`})]})]}),!l&&s.jsxs("div",{className:"flex gap-2",children:[C.previousContract&&s.jsx(ke,{to:`/contracts/${C.previousContract.id}`,children:s.jsxs(T,{variant:"secondary",children:[s.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Vorgängervertrag"]})}),i("contracts:create")&&!C.followUpContract&&s.jsxs(T,{variant:"secondary",onClick:()=>A(!0),disabled:B.isPending,children:[s.jsx(oh,{className:"w-4 h-4 mr-2"}),B.isPending?"Erstelle...":"Folgevertrag anlegen"]}),C.followUpContract&&s.jsx(ke,{to:`/contracts/${C.followUpContract.id}`,children:s.jsxs(T,{variant:"secondary",children:[s.jsx(Nv,{className:"w-4 h-4 mr-2"}),"Folgevertrag anzeigen"]})}),i("contracts:update")&&s.jsx(ke,{to:`/contracts/${e}/edit`,children:s.jsxs(T,{variant:"secondary",children:[s.jsx(He,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),i("contracts:delete")&&s.jsxs(T,{variant:"danger",onClick:()=>{confirm("Vertrag wirklich löschen?")&&K.mutate()},children:[s.jsx(Ne,{className:"w-4 h-4 mr-2"}),"Löschen"]})]})]}),C.previousContract&&s.jsx(X,{className:"mb-6 border-l-4 border-l-blue-500",title:"Vorgängervertrag",children:s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),s.jsx("dd",{children:s.jsx("button",{onClick:()=>w(!0),className:"text-blue-600 hover:underline",children:C.previousContract.contractNumber})})]}),C.previousContract.providerName&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsx("dd",{children:C.previousContract.providerName})]}),C.previousContract.customerNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),s.jsx("dd",{className:"font-mono",children:C.previousContract.customerNumberAtProvider})]}),C.previousContract.contractNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),s.jsx("dd",{className:"font-mono",children:C.previousContract.contractNumberAtProvider})]}),C.previousContract.portalUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Zugangsdaten"}),s.jsx("dd",{children:C.previousContract.portalUsername})]})]})}),!C.previousContract&&(C.previousProvider||C.previousCustomerNumber||C.previousContractNumber)&&s.jsx(X,{className:"mb-6 border-l-4 border-l-gray-400",title:"Altanbieter",children:s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.previousProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsx("dd",{children:C.previousProvider.name})]}),C.previousCustomerNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.previousCustomerNumber,s.jsx(oe,{value:C.previousCustomerNumber})]})]}),C.previousContractNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.previousContractNumber,s.jsx(oe,{value:C.previousContractNumber})]})]})]})}),C.cancellationConfirmationDate&&s.jsxs("div",{className:"mb-6 p-4 bg-red-50 border-2 border-red-400 rounded-lg flex items-start gap-3",children:[s.jsx("span",{className:"text-red-600 text-xl font-bold",children:"!"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold text-red-800",children:"Kündigungsbestätigung vorhanden"}),s.jsxs("p",{className:"text-sm text-red-700 mt-1",children:["Dieser Vertrag hat eine Kündigungsbestätigung vom"," ",s.jsx("strong",{children:new Date(C.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),".",C.cancellationConfirmationOptionsDate&&s.jsxs(s.Fragment,{children:[" Optionen-Bestätigung: ",s.jsx("strong",{children:new Date(C.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),"."]})]})]})]}),C.type==="MOBILE"&&((nt=C.mobileDetails)==null?void 0:nt.requiresMultisim)&&s.jsxs("div",{className:"mb-6 p-4 bg-amber-50 border border-amber-300 rounded-lg flex items-start gap-3",children:[s.jsx("span",{className:"text-amber-600 text-xl font-bold",children:"!"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold text-amber-800",children:"Multisim erforderlich"}),s.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"Dieser Kunde benötigt eine Multisim-Karte. Multisim ist bei Klarmobil, Congstar und Otelo nicht buchbar. Bitte einen Anbieter wie Freenet oder vergleichbar wählen."})]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6",children:[s.jsx(X,{title:"Anbieter & Tarif",children:s.jsxs("dl",{className:"space-y-3",children:[(C.provider||C.providerName)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),s.jsx("dd",{className:"font-medium",children:((es=C.provider)==null?void 0:es.name)||C.providerName})]}),(C.tariff||C.tariffName)&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Tarif"}),s.jsx("dd",{children:((Vt=C.tariff)==null?void 0:Vt.name)||C.tariffName})]}),C.customerNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.customerNumberAtProvider,s.jsx(oe,{value:C.customerNumberAtProvider})]})]}),C.contractNumberAtProvider&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.contractNumberAtProvider,s.jsx(oe,{value:C.contractNumberAtProvider})]})]}),C.salesPlatform&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertriebsplattform"}),s.jsx("dd",{children:C.salesPlatform.name})]}),C.commission!==null&&C.commission!==void 0&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Provision"}),s.jsx("dd",{children:C.commission.toLocaleString("de-DE",{style:"currency",currency:"EUR"})})]}),C.priceFirst12Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis erste 12 Monate"}),s.jsx("dd",{children:C.priceFirst12Months})]}),C.priceFrom13Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis ab 13. Monat"}),s.jsx("dd",{children:C.priceFrom13Months})]}),C.priceAfter24Months&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Preis nach 24 Monaten"}),s.jsx("dd",{children:C.priceAfter24Months})]})]})}),s.jsxs(X,{title:"Laufzeit und Kündigung",className:C.cancellationConfirmationDate?"border-2 border-red-400":"",children:[C.contractDuration&&pC(C.contractDuration.code)&&s.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[s.jsx("strong",{children:"Hinweis:"})," Dieser Vertrag gilt als unbefristet mit der jeweiligen Kündigungsfrist."]}),s.jsxs("dl",{className:"space-y-3",children:[C.startDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsbeginn"}),s.jsx("dd",{children:new Date(C.startDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.endDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsende"}),s.jsx("dd",{children:new Date(C.endDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.contractDuration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragslaufzeit"}),s.jsx("dd",{children:C.contractDuration.description})]}),C.cancellationPeriod&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsfrist"}),s.jsx("dd",{children:C.cancellationPeriod.description})]}),C.cancellationConfirmationDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsdatum"}),s.jsx("dd",{children:new Date(C.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.cancellationConfirmationOptionsDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsoptionendatum"}),s.jsx("dd",{children:new Date(C.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),C.wasSpecialCancellation&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Sonderkündigung"}),s.jsx("dd",{children:s.jsx(ve,{variant:"warning",children:"Ja"})})]})]}),i("contracts:update")&&s.jsxs("div",{className:"mt-6 pt-6 border-t",children:[s.jsx("h4",{className:"font-medium mb-4",children:"Kündigungsdokumente"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsschreiben"}),C.cancellationLetterPath?s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationLetterPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationLetterPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationLetter(c,Z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationLetterPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ut.deleteCancellationLetter(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]}):s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationLetter(c,Z),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsbestätigung"}),C.cancellationConfirmationPath?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationConfirmationPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationConfirmationPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationConfirmation(c,Z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationConfirmationPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ut.deleteCancellationConfirmation(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Bestätigung erhalten am"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"date",value:C.cancellationConfirmationDate?C.cancellationConfirmationDate.split("T")[0]:"",onChange:Z=>{const Fe=Z.target.value||null;Q.mutate(Fe)},className:"block w-full max-w-[180px] px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"}),C.cancellationConfirmationDate&&s.jsx("button",{onClick:()=>Q.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:s.jsx(Ne,{className:"w-4 h-4"})})]})]})]}):s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationConfirmation(c,Z),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsschreiben Optionen"}),C.cancellationLetterOptionsPath?s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationLetterOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationLetterOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationLetterOptions(c,Z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationLetterOptionsPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ut.deleteCancellationLetterOptions(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]}):s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationLetterOptions(c,Z),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsbestätigung Optionen"}),C.cancellationConfirmationOptionsPath?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("a",{href:`/api${C.cancellationConfirmationOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ae,{className:"w-4 h-4"}),"Anzeigen"]}),s.jsxs("a",{href:`/api${C.cancellationConfirmationOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ps,{className:"w-4 h-4"}),"Download"]}),s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationConfirmationOptions(c,Z),a.invalidateQueries({queryKey:["contract",e]})},existingFile:C.cancellationConfirmationOptionsPath,accept:".pdf",label:"Ersetzen"}),s.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await ut.deleteCancellationConfirmationOptions(c),a.invalidateQueries({queryKey:["contract",e]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[s.jsx(Ne,{className:"w-4 h-4"}),"Löschen"]})]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Bestätigung erhalten am"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"date",value:C.cancellationConfirmationOptionsDate?C.cancellationConfirmationOptionsDate.split("T")[0]:"",onChange:Z=>{const Fe=Z.target.value||null;le.mutate(Fe)},className:"block w-full max-w-[180px] px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"}),C.cancellationConfirmationOptionsDate&&s.jsx("button",{onClick:()=>le.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:s.jsx(Ne,{className:"w-4 h-4"})})]})]})]}):s.jsx(Dt,{onUpload:async Z=>{await ut.uploadCancellationConfirmationOptions(c,Z),a.invalidateQueries({queryKey:["contract",e]})},accept:".pdf",label:"PDF hochladen"})]})]})]})]})]}),(C.portalUsername||C.stressfreiEmail||C.portalPasswordEncrypted)&&s.jsxs(X,{className:"mb-6",title:"Zugangsdaten",children:[s.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[(C.portalUsername||C.stressfreiEmail)&&s.jsxs("div",{children:[s.jsxs("dt",{className:"text-sm text-gray-500",children:["Benutzername",C.stressfreiEmail&&s.jsx("span",{className:"ml-2 text-xs text-blue-600",children:"(Stressfrei-Wechseln)"})]}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[((ae=C.stressfreiEmail)==null?void 0:ae.email)||C.portalUsername,s.jsx(oe,{value:((Ge=C.stressfreiEmail)==null?void 0:Ge.email)||C.portalUsername||""})]})]}),C.portalPasswordEncrypted&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Passwort"}),s.jsxs("dd",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:d&&h?h:"••••••••"}),d&&h&&s.jsx(oe,{value:h}),s.jsx(T,{variant:"ghost",size:"sm",onClick:de,children:d?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]}),((xt=C.provider)==null?void 0:xt.portalUrl)&&(C.portalUsername||C.stressfreiEmail)&&C.portalPasswordEncrypted&&s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsxs(T,{onClick:st,disabled:m,className:"w-full sm:w-auto",children:[s.jsx(dh,{className:"w-4 h-4 mr-2"}),m?"Wird geöffnet...":"Zum Kundenportal (Auto-Login)"]}),s.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"Öffnet das Portal mit vorausgefüllten Zugangsdaten"})]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6",children:[C.address&&s.jsx(X,{title:"Lieferadresse",children:s.jsxs(Wu,{values:[`${C.address.street} ${C.address.houseNumber}`,`${C.address.postalCode} ${C.address.city}`,C.address.country],children:[s.jsxs("p",{children:[C.address.street," ",C.address.houseNumber]}),s.jsxs("p",{children:[C.address.postalCode," ",C.address.city]}),s.jsx("p",{className:"text-gray-500",children:C.address.country})]})}),(C.billingAddress||C.address)&&s.jsx(X,{title:"Rechnungsadresse",children:(()=>{const Z=C.billingAddress||C.address;return Z?s.jsxs(Wu,{values:[`${Z.street} ${Z.houseNumber}`,`${Z.postalCode} ${Z.city}`,Z.country],children:[s.jsxs("p",{children:[Z.street," ",Z.houseNumber]}),s.jsxs("p",{children:[Z.postalCode," ",Z.city]}),s.jsx("p",{className:"text-gray-500",children:Z.country}),!C.billingAddress&&C.address&&s.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"(wie Lieferadresse)"})]}):null})()}),C.bankCard&&s.jsxs(X,{title:"Bankkarte",children:[s.jsx("p",{className:"font-medium",children:C.bankCard.accountHolder}),s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[C.bankCard.iban,s.jsx(oe,{value:C.bankCard.iban})]}),C.bankCard.bankName&&s.jsx("p",{className:"text-gray-500",children:C.bankCard.bankName})]}),C.identityDocument&&s.jsxs(X,{title:"Ausweis",children:[s.jsxs("p",{className:"font-mono flex items-center gap-1",children:[C.identityDocument.documentNumber,s.jsx(oe,{value:C.identityDocument.documentNumber})]}),s.jsx("p",{className:"text-gray-500",children:C.identityDocument.type})]})]}),C.energyDetails&&s.jsxs(X,{className:"mb-6",title:C.type==="ELECTRICITY"?"Strom-Details":"Gas-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.energyDetails.meter&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Zählernummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.energyDetails.meter.meterNumber,s.jsx(oe,{value:C.energyDetails.meter.meterNumber})]})]}),C.energyDetails.maloId&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"MaLo-ID"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.energyDetails.maloId,s.jsx(oe,{value:C.energyDetails.maloId})]})]}),C.energyDetails.annualConsumption&&s.jsxs("div",{children:[s.jsxs("dt",{className:"text-sm text-gray-500",children:["Jahresverbrauch ",C.type==="ELECTRICITY"?"":"(m³)"]}),s.jsxs("dd",{children:[C.energyDetails.annualConsumption.toLocaleString("de-DE")," ",C.type==="ELECTRICITY"?"kWh":"m³"]})]}),C.type==="GAS"&&C.energyDetails.annualConsumptionKwh&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Jahresverbrauch (kWh)"}),s.jsxs("dd",{children:[C.energyDetails.annualConsumptionKwh.toLocaleString("de-DE")," kWh"]})]}),C.energyDetails.basePrice!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Grundpreis"}),s.jsxs("dd",{children:[C.energyDetails.basePrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/Monat"]})]}),C.energyDetails.unitPrice!=null&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Arbeitspreis"}),s.jsxs("dd",{children:[C.energyDetails.unitPrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/kWh"]})]}),C.energyDetails.bonus&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Bonus"}),s.jsxs("dd",{children:[C.energyDetails.bonus.toLocaleString("de-DE")," €"]})]}),C.energyDetails.previousProviderName&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversorger"}),s.jsx("dd",{children:C.energyDetails.previousProviderName})]}),C.energyDetails.previousCustomerNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorherige Kundennr."}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.energyDetails.previousCustomerNumber,s.jsx(oe,{value:C.energyDetails.previousCustomerNumber})]})]})]}),C.energyDetails.meter&&s.jsx(gC,{meterId:C.energyDetails.meter.id,meterType:C.energyDetails.meter.type,readings:C.energyDetails.meter.readings||[],contractId:c,canEdit:i("contracts:update")&&!l}),C.energyDetails.meter&&C.startDate&&C.endDate&&s.jsx(vC,{contractType:C.type,readings:C.energyDetails.meter.readings||[],startDate:C.startDate,endDate:C.endDate,basePrice:C.energyDetails.basePrice,unitPrice:C.energyDetails.unitPrice,bonus:C.energyDetails.bonus}),s.jsx(rC,{ecdId:C.energyDetails.id,invoices:C.energyDetails.invoices||[],contractId:c,canEdit:i("contracts:update")&&!l})]}),C.internetDetails&&s.jsxs(X,{className:"mb-6",title:C.type==="DSL"?"DSL-Details":C.type==="CABLE"?"Kabelinternet-Details":"Glasfaser-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.internetDetails.downloadSpeed&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Download"}),s.jsxs("dd",{children:[C.internetDetails.downloadSpeed," Mbit/s"]})]}),C.internetDetails.uploadSpeed&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Upload"}),s.jsxs("dd",{children:[C.internetDetails.uploadSpeed," Mbit/s"]})]}),C.internetDetails.routerModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Router"}),s.jsx("dd",{children:C.internetDetails.routerModel})]}),C.internetDetails.routerSerialNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Router S/N"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.routerSerialNumber,s.jsx(oe,{value:C.internetDetails.routerSerialNumber})]})]}),C.internetDetails.installationDate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Installation"}),s.jsx("dd",{children:new Date(C.internetDetails.installationDate).toLocaleDateString("de-DE")})]}),C.internetDetails.homeId&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Home-ID"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.homeId,s.jsx(oe,{value:C.internetDetails.homeId})]})]}),C.internetDetails.activationCode&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Aktivierungscode"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.activationCode,s.jsx(oe,{value:C.internetDetails.activationCode})]})]})]}),(C.internetDetails.internetUsername||C.internetDetails.internetPasswordEncrypted)&&s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Internet-Zugangsdaten"}),s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.internetDetails.internetUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Benutzername"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.internetDetails.internetUsername,s.jsx(oe,{value:C.internetDetails.internetUsername})]})]}),C.internetDetails.internetPasswordEncrypted&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Passwort"}),s.jsxs("dd",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:p&&g?g:"••••••••"}),p&&g&&s.jsx(oe,{value:g}),s.jsx(T,{variant:"ghost",size:"sm",onClick:Ke,children:p?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})]}),C.internetDetails.phoneNumbers&&C.internetDetails.phoneNumbers.length>0&&s.jsxs("div",{className:"mt-4 pt-4 border-t",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Rufnummern & SIP-Zugangsdaten"}),s.jsx("div",{className:"space-y-3",children:C.internetDetails.phoneNumbers.map(Z=>s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsxs("span",{className:"font-mono font-medium flex items-center gap-1",children:[Z.phoneNumber,s.jsx(oe,{value:Z.phoneNumber})]}),Z.isMain&&s.jsx(ve,{variant:"success",children:"Hauptnummer"})]}),(Z.sipUsername||Z.sipPasswordEncrypted||Z.sipServer)&&s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[Z.sipUsername&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIP-Benutzer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[Z.sipUsername,s.jsx(oe,{value:Z.sipUsername})]})]}),Z.sipPasswordEncrypted&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIP-Passwort"}),s.jsxs("dd",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:v[Z.id]&&E[Z.id]?E[Z.id]:"••••••••"}),v[Z.id]&&E[Z.id]&&s.jsx(oe,{value:E[Z.id]}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>Ve(Z.id),children:v[Z.id]?s.jsx(It,{className:"w-3 h-3"}):s.jsx(Ae,{className:"w-3 h-3"})})]})]}),Z.sipServer&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"SIP-Server"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[Z.sipServer,s.jsx(oe,{value:Z.sipServer})]})]})]})]},Z.id))})]})]}),C.mobileDetails&&s.jsxs(X,{className:"mb-6",title:"Mobilfunk-Details",children:[s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.mobileDetails.dataVolume&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Datenvolumen"}),s.jsxs("dd",{children:[C.mobileDetails.dataVolume," GB"]})]}),C.mobileDetails.includedMinutes&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-Minuten"}),s.jsx("dd",{children:C.mobileDetails.includedMinutes})]}),C.mobileDetails.includedSMS&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-SMS"}),s.jsx("dd",{children:C.mobileDetails.includedSMS})]}),C.mobileDetails.deviceModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Gerät"}),s.jsx("dd",{children:C.mobileDetails.deviceModel})]}),C.mobileDetails.deviceImei&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"IMEI"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.mobileDetails.deviceImei,s.jsx(oe,{value:C.mobileDetails.deviceImei})]})]}),C.mobileDetails.requiresMultisim&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Multisim"}),s.jsx("dd",{children:s.jsx(ve,{variant:"warning",children:"Erforderlich"})})]})]}),C.mobileDetails.simCards&&C.mobileDetails.simCards.length>0&&s.jsxs("div",{className:"mt-6 pt-6 border-t",children:[s.jsx("h4",{className:"font-medium mb-4",children:"SIM-Karten"}),s.jsx("div",{className:"space-y-3",children:C.mobileDetails.simCards.map(Z=>s.jsx(xC,{simCard:Z},Z.id))})]}),(!C.mobileDetails.simCards||C.mobileDetails.simCards.length===0)&&(C.mobileDetails.phoneNumber||C.mobileDetails.simCardNumber)&&s.jsxs("div",{className:"mt-6 pt-6 border-t",children:[s.jsx("h4",{className:"font-medium mb-4",children:"SIM-Karte (Legacy)"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[C.mobileDetails.phoneNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Rufnummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.mobileDetails.phoneNumber,s.jsx(oe,{value:C.mobileDetails.phoneNumber})]})]}),C.mobileDetails.simCardNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SIM-Kartennummer"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.mobileDetails.simCardNumber,s.jsx(oe,{value:C.mobileDetails.simCardNumber})]})]})]})]})]}),C.tvDetails&&s.jsx(X,{className:"mb-6",title:"TV-Details",children:s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[C.tvDetails.receiverModel&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Receiver"}),s.jsx("dd",{children:C.tvDetails.receiverModel})]}),C.tvDetails.smartcardNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Smartcard"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.tvDetails.smartcardNumber,s.jsx(oe,{value:C.tvDetails.smartcardNumber})]})]}),C.tvDetails.package&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Paket"}),s.jsx("dd",{children:C.tvDetails.package})]})]})}),C.carInsuranceDetails&&s.jsx(X,{className:"mb-6",title:"KFZ-Versicherung Details",children:s.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[C.carInsuranceDetails.licensePlate&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Kennzeichen"}),s.jsxs("dd",{className:"font-mono font-bold flex items-center gap-1",children:[C.carInsuranceDetails.licensePlate,s.jsx(oe,{value:C.carInsuranceDetails.licensePlate})]})]}),C.carInsuranceDetails.vehicleType&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Fahrzeug"}),s.jsx("dd",{children:C.carInsuranceDetails.vehicleType})]}),C.carInsuranceDetails.hsn&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"HSN/TSN"}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.carInsuranceDetails.hsn,"/",C.carInsuranceDetails.tsn,s.jsx(oe,{value:`${C.carInsuranceDetails.hsn}/${C.carInsuranceDetails.tsn}`})]})]}),C.carInsuranceDetails.vin&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"FIN"}),s.jsxs("dd",{className:"font-mono text-sm flex items-center gap-1",children:[C.carInsuranceDetails.vin,s.jsx(oe,{value:C.carInsuranceDetails.vin})]})]}),C.carInsuranceDetails.firstRegistration&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Erstzulassung"}),s.jsx("dd",{children:new Date(C.carInsuranceDetails.firstRegistration).toLocaleDateString("de-DE")})]}),C.carInsuranceDetails.noClaimsClass&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SF-Klasse"}),s.jsx("dd",{children:C.carInsuranceDetails.noClaimsClass})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Versicherungsart"}),s.jsx("dd",{children:s.jsx(ve,{variant:C.carInsuranceDetails.insuranceType==="FULL"?"success":C.carInsuranceDetails.insuranceType==="PARTIAL"?"warning":"default",children:C.carInsuranceDetails.insuranceType==="FULL"?"Vollkasko":C.carInsuranceDetails.insuranceType==="PARTIAL"?"Teilkasko":"Haftpflicht"})})]}),C.carInsuranceDetails.deductiblePartial&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SB Teilkasko"}),s.jsxs("dd",{children:[C.carInsuranceDetails.deductiblePartial," €"]})]}),C.carInsuranceDetails.deductibleFull&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"SB Vollkasko"}),s.jsxs("dd",{children:[C.carInsuranceDetails.deductibleFull," €"]})]}),C.carInsuranceDetails.policyNumber&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Versicherungsschein-Nr."}),s.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[C.carInsuranceDetails.policyNumber,s.jsx(oe,{value:C.carInsuranceDetails.policyNumber})]})]}),C.carInsuranceDetails.previousInsurer&&s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversicherer"}),s.jsx("dd",{children:C.carInsuranceDetails.previousInsurer})]})]})}),s.jsx(jC,{contractId:c,canEdit:i("contracts:update"),isCustomerPortal:o}),!o&&i("contracts:read")&&C.customerId&&s.jsx(uk,{contractId:c,customerId:C.customerId}),C.notes&&s.jsx(X,{title:"Notizen",children:s.jsx("p",{className:"whitespace-pre-wrap",children:C.notes})}),!o&&i("contracts:read")&&s.jsx(sC,{contractId:c,canEdit:i("contracts:update")}),I&&C.previousContract&&s.jsx(tC,{contractId:C.previousContract.id,isOpen:!0,onClose:()=>w(!1)}),s.jsx(qe,{isOpen:S,onClose:()=>A(!1),title:"Folgevertrag anlegen",size:"sm",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("p",{className:"text-gray-700",children:"Möchten Sie wirklich einen Folgevertrag für diesen Vertrag anlegen?"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Die Daten des aktuellen Vertrags werden als Vorlage übernommen."}),s.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[s.jsx(T,{variant:"secondary",onClick:()=>A(!1),children:"Nein"}),s.jsx(T,{onClick:()=>{A(!1),B.mutate()},children:"Ja, anlegen"})]})]})}),s.jsx(fC,{isOpen:O,onClose:()=>R(!1)}),s.jsx(qe,{isOpen:q,onClose:()=>D(!1),title:"Zurückstellung aufheben?",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("p",{className:"text-gray-700",children:"Möchten Sie die Zurückstellung für diesen Vertrag wirklich aufheben?"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Der Vertrag wird danach wieder im Cockpit angezeigt, wenn Fristen anstehen oder abgelaufen sind."}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:()=>D(!1),children:"Abbrechen"}),s.jsx(T,{variant:"danger",onClick:()=>_.mutate(),disabled:_.isPending,children:_.isPending?"Wird aufgehoben...":"Ja, aufheben"})]})]})})]})}const wC=[{value:"DRAFT",label:"Entwurf"},{value:"PENDING",label:"Ausstehend"},{value:"ACTIVE",label:"Aktiv"},{value:"CANCELLED",label:"Gekündigt"},{value:"EXPIRED",label:"Abgelaufen"},{value:"DEACTIVATED",label:"Deaktiviert"}],SC=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function kC({isOpen:e,onClose:t}){return e?s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:t}),s.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),s.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600",children:s.jsx(qt,{className:"w-4 h-4"})})]}),s.jsx("div",{className:"space-y-2",children:SC.map(({status:n,label:r,description:a,color:i})=>s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`font-medium text-sm min-w-[90px] ${i}`,children:r}),s.jsx("span",{className:"text-sm text-gray-600",children:a})]},n))})]})]}):null}function _x(){var oi,Rl,ci,bh,Nh,wh,Sh,kh,Ch;const{id:e}=Nc(),[t]=Sc(),n=Yt(),r=ge(),a=!!e,i=t.get("customerId"),{register:l,handleSubmit:o,reset:c,watch:d,setValue:u,formState:{errors:h}}=Vv({defaultValues:{customerId:i||"",type:"ELECTRICITY",status:"DRAFT",previousContractId:""}}),x=d("type"),m=d("customerId"),f=d("previousContractId"),{data:p}=fe({queryKey:["contract",e],queryFn:()=>Oe.getById(parseInt(e)),enabled:a}),{data:b}=fe({queryKey:["customers-all"],queryFn:()=>At.getAll({limit:1e3})}),{data:g}=fe({queryKey:["customer",m],queryFn:()=>At.getById(parseInt(m)),enabled:!!m}),{data:y}=fe({queryKey:["customer-contracts-for-predecessor",m],queryFn:()=>Oe.getAll({customerId:parseInt(m),limit:1e3}),enabled:!!m}),{data:v}=fe({queryKey:["platforms"],queryFn:()=>il.getAll()}),{data:N}=fe({queryKey:["cancellation-periods"],queryFn:()=>ll.getAll()}),{data:E}=fe({queryKey:["contract-durations"],queryFn:()=>ol.getAll()}),{data:P}=fe({queryKey:["providers"],queryFn:()=>Xa.getAll()}),{data:I}=fe({queryKey:["contract-categories"],queryFn:()=>cl.getAll()}),w=d("providerId"),[S,A]=j.useState(null),[O,R]=j.useState([]),[q,D]=j.useState([]),[z,k]=j.useState(!1),[K,B]=j.useState("manual"),[_,Q]=j.useState(""),[le,de]=j.useState(!1),[Ke,Ve]=j.useState(!1),[st,C]=j.useState({}),[nt,es]=j.useState({}),[Vt,ae]=j.useState({}),[Ge,xt]=j.useState(!1);j.useEffect(()=>{a||k(!0)},[a]),j.useEffect(()=>{!a&&i&&(b!=null&&b.data)&&b.data.some(ie=>ie.id.toString()===i)&&u("customerId",i)},[a,i,b,u]),j.useEffect(()=>{z&&S&&w!==S&&u("tariffId",""),A(w)},[w,S,u,z]),j.useEffect(()=>{if(!a&&(I!=null&&I.data)&&I.data.length>0){const F=d("type"),ie=I.data.filter(pe=>pe.isActive),we=ie.some(pe=>pe.code===F);if(!F||!we){const pe=ie.sort((je,ct)=>je.sortOrder-ct.sortOrder)[0];pe&&u("type",pe.code)}}},[I,a,u,d]),j.useEffect(()=>{a&&(p!=null&&p.data)&&!m&&u("customerId",p.data.customerId.toString())},[a,p,m,u]),j.useEffect(()=>{var F,ie,we,pe,je,ct,Ce,di,Eh,Dh,Ah,Ph,Mh,Th,Fh,Ih,Rh,Lh,Oh,zh,$h,_h,Kh,Bh,Uh,qh,Vh,Qh,Hh,Wh,Gh,Zh,Jh,Xh,Yh,ef,tf,sf,nf,rf,af,lf,of,cf,df,uf,mf,hf,ff,pf,xf,gf;if(p!=null&&p.data&&(v!=null&&v.data)&&(I!=null&&I.data)&&(P!=null&&P.data)&&(g!=null&&g.data)){const re=p.data;c({customerId:re.customerId.toString(),type:re.type,status:re.status,addressId:((F=re.addressId)==null?void 0:F.toString())||"",billingAddressId:((ie=re.billingAddressId)==null?void 0:ie.toString())||"",bankCardId:((we=re.bankCardId)==null?void 0:we.toString())||"",identityDocumentId:((pe=re.identityDocumentId)==null?void 0:pe.toString())||"",salesPlatformId:((je=re.salesPlatformId)==null?void 0:je.toString())||"",providerId:((ct=re.providerId)==null?void 0:ct.toString())||"",tariffId:((Ce=re.tariffId)==null?void 0:Ce.toString())||"",providerName:re.providerName||"",tariffName:re.tariffName||"",customerNumberAtProvider:re.customerNumberAtProvider||"",contractNumberAtProvider:re.contractNumberAtProvider||"",priceFirst12Months:re.priceFirst12Months||"",priceFrom13Months:re.priceFrom13Months||"",priceAfter24Months:re.priceAfter24Months||"",startDate:re.startDate?re.startDate.split("T")[0]:"",endDate:re.endDate?re.endDate.split("T")[0]:"",cancellationPeriodId:((di=re.cancellationPeriodId)==null?void 0:di.toString())||"",contractDurationId:((Eh=re.contractDurationId)==null?void 0:Eh.toString())||"",commission:re.commission||"",portalUsername:re.portalUsername||"",notes:re.notes||"",meterId:((Ah=(Dh=re.energyDetails)==null?void 0:Dh.meterId)==null?void 0:Ah.toString())||"",maloId:((Ph=re.energyDetails)==null?void 0:Ph.maloId)||"",annualConsumption:((Mh=re.energyDetails)==null?void 0:Mh.annualConsumption)||"",annualConsumptionKwh:((Th=re.energyDetails)==null?void 0:Th.annualConsumptionKwh)||"",basePrice:((Fh=re.energyDetails)==null?void 0:Fh.basePrice)||"",unitPrice:((Ih=re.energyDetails)==null?void 0:Ih.unitPrice)||"",bonus:((Rh=re.energyDetails)==null?void 0:Rh.bonus)||"",downloadSpeed:((Lh=re.internetDetails)==null?void 0:Lh.downloadSpeed)||"",uploadSpeed:((Oh=re.internetDetails)==null?void 0:Oh.uploadSpeed)||"",routerModel:((zh=re.internetDetails)==null?void 0:zh.routerModel)||"",routerSerialNumber:(($h=re.internetDetails)==null?void 0:$h.routerSerialNumber)||"",installationDate:(_h=re.internetDetails)!=null&&_h.installationDate?re.internetDetails.installationDate.split("T")[0]:"",internetUsername:((Kh=re.internetDetails)==null?void 0:Kh.internetUsername)||"",homeId:((Bh=re.internetDetails)==null?void 0:Bh.homeId)||"",activationCode:((Uh=re.internetDetails)==null?void 0:Uh.activationCode)||"",requiresMultisim:((qh=re.mobileDetails)==null?void 0:qh.requiresMultisim)||!1,dataVolume:((Vh=re.mobileDetails)==null?void 0:Vh.dataVolume)||"",includedMinutes:((Qh=re.mobileDetails)==null?void 0:Qh.includedMinutes)||"",includedSMS:((Hh=re.mobileDetails)==null?void 0:Hh.includedSMS)||"",deviceModel:((Wh=re.mobileDetails)==null?void 0:Wh.deviceModel)||"",deviceImei:((Gh=re.mobileDetails)==null?void 0:Gh.deviceImei)||"",phoneNumber:((Zh=re.mobileDetails)==null?void 0:Zh.phoneNumber)||"",simCardNumber:((Jh=re.mobileDetails)==null?void 0:Jh.simCardNumber)||"",receiverModel:((Xh=re.tvDetails)==null?void 0:Xh.receiverModel)||"",smartcardNumber:((Yh=re.tvDetails)==null?void 0:Yh.smartcardNumber)||"",tvPackage:((ef=re.tvDetails)==null?void 0:ef.package)||"",licensePlate:((tf=re.carInsuranceDetails)==null?void 0:tf.licensePlate)||"",hsn:((sf=re.carInsuranceDetails)==null?void 0:sf.hsn)||"",tsn:((nf=re.carInsuranceDetails)==null?void 0:nf.tsn)||"",vin:((rf=re.carInsuranceDetails)==null?void 0:rf.vin)||"",vehicleType:((af=re.carInsuranceDetails)==null?void 0:af.vehicleType)||"",firstRegistration:(lf=re.carInsuranceDetails)!=null&&lf.firstRegistration?re.carInsuranceDetails.firstRegistration.split("T")[0]:"",noClaimsClass:((of=re.carInsuranceDetails)==null?void 0:of.noClaimsClass)||"",insuranceType:((cf=re.carInsuranceDetails)==null?void 0:cf.insuranceType)||"LIABILITY",deductiblePartial:((df=re.carInsuranceDetails)==null?void 0:df.deductiblePartial)||"",deductibleFull:((uf=re.carInsuranceDetails)==null?void 0:uf.deductibleFull)||"",policyNumber:((mf=re.carInsuranceDetails)==null?void 0:mf.policyNumber)||"",previousInsurer:((hf=re.carInsuranceDetails)==null?void 0:hf.previousInsurer)||"",cancellationConfirmationDate:re.cancellationConfirmationDate?re.cancellationConfirmationDate.split("T")[0]:"",cancellationConfirmationOptionsDate:re.cancellationConfirmationOptionsDate?re.cancellationConfirmationOptionsDate.split("T")[0]:"",wasSpecialCancellation:re.wasSpecialCancellation||!1,previousContractId:((ff=re.previousContractId)==null?void 0:ff.toString())||"",previousProviderId:((pf=re.previousProviderId)==null?void 0:pf.toString())||"",previousCustomerNumber:re.previousCustomerNumber||"",previousContractNumber:re.previousContractNumber||""}),(xf=re.mobileDetails)!=null&&xf.simCards&&re.mobileDetails.simCards.length>0?R(re.mobileDetails.simCards.map(ss=>({id:ss.id,phoneNumber:ss.phoneNumber||"",simCardNumber:ss.simCardNumber||"",pin:"",puk:"",hasExistingPin:!!ss.pin,hasExistingPuk:!!ss.puk,isMultisim:ss.isMultisim,isMain:ss.isMain}))):R([]),(gf=re.internetDetails)!=null&&gf.phoneNumbers&&re.internetDetails.phoneNumbers.length>0?D(re.internetDetails.phoneNumbers.map(ss=>({id:ss.id,phoneNumber:ss.phoneNumber||"",sipUsername:ss.sipUsername||"",sipPassword:"",hasExistingSipPassword:!!ss.sipPasswordEncrypted,sipServer:ss.sipServer||"",isMain:ss.isMain}))):D([]),re.stressfreiEmailId?(B("stressfrei"),Q(re.stressfreiEmailId.toString())):(B("manual"),Q("")),k(!0)}},[p,c,v,I,P,g]);const Z=d("startDate"),Fe=d("contractDurationId");j.useEffect(()=>{if(Z&&Fe&&(E!=null&&E.data)){const F=E.data.find(ie=>ie.id===parseInt(Fe));if(F){const ie=new Date(Z),pe=F.code.match(/^(\d+)([MTJ])$/);if(pe){const je=parseInt(pe[1]),ct=pe[2];let Ce=new Date(ie);ct==="T"?Ce.setDate(Ce.getDate()+je):ct==="M"?Ce.setMonth(Ce.getMonth()+je):ct==="J"&&Ce.setFullYear(Ce.getFullYear()+je),u("endDate",Ce.toISOString().split("T")[0])}}}},[Z,Fe,E,u]);const Xe=G({mutationFn:Oe.create,onSuccess:(F,ie)=>{r.invalidateQueries({queryKey:["contracts"]}),ie.customerId&&r.invalidateQueries({queryKey:["customer",ie.customerId.toString()]}),r.invalidateQueries({queryKey:["customers"]}),n(i?`/customers/${i}?tab=contracts`:"/contracts")}}),J=G({mutationFn:F=>Oe.update(parseInt(e),F),onSuccess:(F,ie)=>{r.invalidateQueries({queryKey:["contracts"]}),r.invalidateQueries({queryKey:["contract",e]}),ie.customerId&&r.invalidateQueries({queryKey:["customer",ie.customerId.toString()]}),r.invalidateQueries({queryKey:["customers"]}),n(`/contracts/${e}`)}}),ue=F=>{const ie=Ce=>{if(Ce==null||Ce==="")return;const di=parseInt(String(Ce));return isNaN(di)?void 0:di},we=kt.find(Ce=>Ce.code===F.type),pe=ie(F.customerId);if(!pe){alert("Bitte wählen Sie einen Kunden aus");return}if(!F.type||!we){alert("Bitte wählen Sie einen Vertragstyp aus");return}const je=Ce=>Ce==null||Ce===""?null:Ce,ct={customerId:pe,type:F.type,contractCategoryId:we.id,status:F.status,addressId:ie(F.addressId)??null,billingAddressId:ie(F.billingAddressId)??null,bankCardId:ie(F.bankCardId)??null,identityDocumentId:ie(F.identityDocumentId)??null,salesPlatformId:ie(F.salesPlatformId)??null,providerId:ie(F.providerId)??null,tariffId:ie(F.tariffId)??null,providerName:je(F.providerName),tariffName:je(F.tariffName),customerNumberAtProvider:je(F.customerNumberAtProvider),contractNumberAtProvider:je(F.contractNumberAtProvider),priceFirst12Months:je(F.priceFirst12Months),priceFrom13Months:je(F.priceFrom13Months),priceAfter24Months:je(F.priceAfter24Months),startDate:F.startDate?new Date(F.startDate):null,endDate:F.endDate?new Date(F.endDate):null,cancellationPeriodId:ie(F.cancellationPeriodId)??null,contractDurationId:ie(F.contractDurationId)??null,commission:F.commission?parseFloat(F.commission):null,portalUsername:K==="manual"?je(F.portalUsername):null,stressfreiEmailId:K==="stressfrei"&&_?parseInt(_):null,portalPassword:F.portalPassword||void 0,notes:je(F.notes),cancellationConfirmationDate:F.cancellationConfirmationDate?new Date(F.cancellationConfirmationDate):null,cancellationConfirmationOptionsDate:F.cancellationConfirmationOptionsDate?new Date(F.cancellationConfirmationOptionsDate):null,wasSpecialCancellation:F.wasSpecialCancellation||!1,previousContractId:ie(F.previousContractId)??null,previousProviderId:F.previousContractId?null:ie(F.previousProviderId)??null,previousCustomerNumber:F.previousContractId?null:je(F.previousCustomerNumber),previousContractNumber:F.previousContractId?null:je(F.previousContractNumber)};["ELECTRICITY","GAS"].includes(F.type)&&(ct.energyDetails={meterId:ie(F.meterId)??null,maloId:je(F.maloId),annualConsumption:F.annualConsumption?parseFloat(F.annualConsumption):null,annualConsumptionKwh:F.annualConsumptionKwh?parseFloat(F.annualConsumptionKwh):null,basePrice:F.basePrice?parseFloat(F.basePrice):null,unitPrice:F.unitPrice?parseFloat(F.unitPrice):null,bonus:F.bonus?parseFloat(F.bonus):null}),["DSL","CABLE","FIBER"].includes(F.type)&&(ct.internetDetails={downloadSpeed:ie(F.downloadSpeed)??null,uploadSpeed:ie(F.uploadSpeed)??null,routerModel:je(F.routerModel),routerSerialNumber:je(F.routerSerialNumber),installationDate:F.installationDate?new Date(F.installationDate):null,internetUsername:je(F.internetUsername),internetPassword:F.internetPassword||void 0,homeId:je(F.homeId),activationCode:je(F.activationCode),phoneNumbers:q.length>0?q.map(Ce=>({id:Ce.id,phoneNumber:Ce.phoneNumber||"",isMain:Ce.isMain??!1,sipUsername:je(Ce.sipUsername),sipPassword:Ce.sipPassword||void 0,sipServer:je(Ce.sipServer)})):void 0}),F.type==="MOBILE"&&(ct.mobileDetails={requiresMultisim:F.requiresMultisim||!1,dataVolume:F.dataVolume?parseFloat(F.dataVolume):null,includedMinutes:ie(F.includedMinutes)??null,includedSMS:ie(F.includedSMS)??null,deviceModel:je(F.deviceModel),deviceImei:je(F.deviceImei),phoneNumber:je(F.phoneNumber),simCardNumber:je(F.simCardNumber),simCards:O.length>0?O.map(Ce=>({id:Ce.id,phoneNumber:je(Ce.phoneNumber),simCardNumber:je(Ce.simCardNumber),pin:Ce.pin||void 0,puk:Ce.puk||void 0,isMultisim:Ce.isMultisim,isMain:Ce.isMain})):void 0}),F.type==="TV"&&(ct.tvDetails={receiverModel:je(F.receiverModel),smartcardNumber:je(F.smartcardNumber),package:je(F.tvPackage)}),F.type==="CAR_INSURANCE"&&(ct.carInsuranceDetails={licensePlate:je(F.licensePlate),hsn:je(F.hsn),tsn:je(F.tsn),vin:je(F.vin),vehicleType:je(F.vehicleType),firstRegistration:F.firstRegistration?new Date(F.firstRegistration):null,noClaimsClass:je(F.noClaimsClass),insuranceType:F.insuranceType,deductiblePartial:F.deductiblePartial?parseFloat(F.deductiblePartial):null,deductibleFull:F.deductibleFull?parseFloat(F.deductibleFull):null,policyNumber:je(F.policyNumber),previousInsurer:je(F.previousInsurer)}),a?J.mutate(ct):Xe.mutate(ct)},ts=Xe.isPending||J.isPending,un=Xe.error||J.error,gt=g==null?void 0:g.data,L=(gt==null?void 0:gt.addresses)||[],U=((oi=gt==null?void 0:gt.bankCards)==null?void 0:oi.filter(F=>F.isActive))||[],W=((Rl=gt==null?void 0:gt.identityDocuments)==null?void 0:Rl.filter(F=>F.isActive))||[],ce=((ci=gt==null?void 0:gt.meters)==null?void 0:ci.filter(F=>F.isActive))||[],ne=((bh=gt==null?void 0:gt.stressfreiEmails)==null?void 0:bh.filter(F=>F.isActive))||[],ee=(v==null?void 0:v.data)||[],ye=(N==null?void 0:N.data)||[],Le=(E==null?void 0:E.data)||[],Me=((Nh=P==null?void 0:P.data)==null?void 0:Nh.filter(F=>F.isActive))||[],kt=((wh=I==null?void 0:I.data)==null?void 0:wh.filter(F=>F.isActive).sort((F,ie)=>F.sortOrder-ie.sortOrder))||[],mn=kt.map(F=>({value:F.code,label:F.name})),Hs=((y==null?void 0:y.data)||[]).filter(F=>!a||F.id!==parseInt(e)).sort((F,ie)=>new Date(ie.startDate||0).getTime()-new Date(F.startDate||0).getTime()),Ln=Me.find(F=>F.id===parseInt(w||"0")),li=((Sh=Ln==null?void 0:Ln.tariffs)==null?void 0:Sh.filter(F=>F.isActive))||[],sa=F=>{const ie=F.companyName||`${F.firstName} ${F.lastName}`,we=F.birthDate?` (geb. ${new Date(F.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})`:"";return`${F.customerNumber} - ${ie}${we}`},Oc=(()=>{var we;const ie=((b==null?void 0:b.data)||[]).map(pe=>({value:pe.id.toString(),label:sa(pe)}));if(a&&((we=p==null?void 0:p.data)!=null&&we.customer)){const pe=p.data.customer;ie.some(ct=>ct.value===pe.id.toString())||ie.unshift({value:pe.id.toString(),label:sa(pe)})}return ie})();return s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold mb-6",children:a?"Vertrag bearbeiten":"Neuer Vertrag"}),un&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:un instanceof Error?un.message:"Ein Fehler ist aufgetreten"}),s.jsxs("form",{onSubmit:o(ue),children:[s.jsx(X,{className:"mb-6",title:"Vertragsdaten",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Ie,{label:"Kunde *",...l("customerId",{required:"Kunde erforderlich"}),options:Oc,error:(kh=h.customerId)==null?void 0:kh.message}),s.jsx(Ie,{label:"Vertragstyp *",...l("type",{required:"Typ erforderlich"}),options:mn}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Status"}),s.jsx("button",{type:"button",onClick:()=>xt(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:s.jsx(Ml,{className:"w-4 h-4"})})]}),s.jsx(Ie,{...l("status"),options:wC})]}),s.jsx(Ie,{label:"Vertriebsplattform",...l("salesPlatformId"),options:ee.map(F=>({value:F.id,label:F.name}))}),m&&s.jsx(Ie,{label:"Vorgänger-Vertrag",...l("previousContractId"),options:Hs.map(F=>({value:F.id,label:`${F.contractNumber} (${F.type}${F.startDate?` - ${new Date(F.startDate).toLocaleDateString("de-DE")}`:""})`})),placeholder:"Keinen Vorgänger auswählen"}),m&&!f&&s.jsxs("div",{className:"mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Altanbieter-Daten"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[s.jsx(Ie,{label:"Altanbieter",...l("previousProviderId"),options:Me.map(F=>({value:F.id,label:F.name})),placeholder:"Bitte wählen..."}),s.jsx(H,{label:"Kundennr. beim Altanbieter",...l("previousCustomerNumber")}),s.jsx(H,{label:"Vertragsnr. beim Altanbieter",...l("previousContractNumber")})]})]})]})}),m&&s.jsxs(X,{className:"mb-6",title:"Kundendaten verknüpfen",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[s.jsx(Ie,{label:"Lieferadresse",...l("addressId"),options:L.filter(F=>F.type==="DELIVERY_RESIDENCE").map(F=>({value:F.id,label:`${F.street} ${F.houseNumber}, ${F.postalCode} ${F.city}`}))}),s.jsx(Ie,{label:"Rechnungsadresse",...l("billingAddressId"),options:L.filter(F=>F.type==="BILLING").map(F=>({value:F.id,label:`${F.street} ${F.houseNumber}, ${F.postalCode} ${F.city}`})),placeholder:"Wie Lieferadresse"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Ie,{label:"Bankkarte",...l("bankCardId"),options:U.map(F=>({value:F.id,label:`${F.iban} (${F.accountHolder})`}))}),s.jsx(Ie,{label:"Ausweis",...l("identityDocumentId"),options:W.map(F=>({value:F.id,label:`${F.documentNumber} (${F.type})`}))})]})]}),s.jsx(X,{className:"mb-6",title:"Anbieter & Tarif",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Ie,{label:"Anbieter",...l("providerId"),options:Me.map(F=>({value:F.id,label:F.name}))}),s.jsx(Ie,{label:"Tarif",...l("tariffId"),options:li.map(F=>({value:F.id,label:F.name})),disabled:!w}),s.jsx(H,{label:"Kundennummer beim Anbieter",...l("customerNumberAtProvider")}),s.jsx(H,{label:"Vertragsnummer beim Anbieter",...l("contractNumberAtProvider")}),s.jsx(H,{label:"Provision (€)",type:"number",step:"0.01",...l("commission")}),s.jsx(H,{label:"Preis erste 12 Monate",...l("priceFirst12Months"),placeholder:"z.B. 29,99 €/Monat"}),s.jsx(H,{label:"Preis ab 13. Monat",...l("priceFrom13Months"),placeholder:"z.B. 39,99 €/Monat"}),s.jsx(H,{label:"Preis nach 24 Monaten",...l("priceAfter24Months"),placeholder:"z.B. 49,99 €/Monat"})]})}),s.jsxs(X,{className:"mb-6",title:"Laufzeit und Kündigung",children:[s.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[s.jsx("strong",{children:"Hinweis:"})," Ist die Laufzeit ≤ 4 Wochen, 1 Monat oder 30 Tage, gilt der Vertrag als unbefristet mit der jeweiligen Kündigungsfrist."]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(H,{label:"Vertragsbeginn",type:"date",...l("startDate"),value:d("startDate")||"",onClear:()=>u("startDate","")}),s.jsx(H,{label:"Vertragsende (berechnet)",type:"date",...l("endDate"),disabled:!0,className:"bg-gray-50"}),s.jsx(Ie,{label:"Vertragslaufzeit",...l("contractDurationId"),options:Le.map(F=>({value:F.id,label:F.description}))}),s.jsx(Ie,{label:"Kündigungsfrist",...l("cancellationPeriodId"),options:ye.map(F=>({value:F.id,label:F.description}))}),s.jsx(H,{label:"Kündigungsbestätigungsdatum",type:"date",...l("cancellationConfirmationDate"),value:d("cancellationConfirmationDate")||"",onClear:()=>u("cancellationConfirmationDate","")}),s.jsx(H,{label:"Kündigungsbestätigungsoptionendatum",type:"date",...l("cancellationConfirmationOptionsDate"),value:d("cancellationConfirmationOptionsDate")||"",onClear:()=>u("cancellationConfirmationOptionsDate","")}),s.jsx("div",{className:"col-span-2",children:s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",...l("wasSpecialCancellation"),className:"rounded border-gray-300"}),s.jsx("span",{children:"Wurde sondergekündigt?"})]})})]})]}),s.jsx(X,{className:"mb-6",title:"Zugangsdaten (verschlüsselt gespeichert)",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Portal Benutzername"}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"radio",name:"usernameType",checked:K==="manual",onChange:()=>{B("manual"),Q("")},className:"text-blue-600"}),s.jsx("span",{className:"text-sm",children:"Manuell eingeben"})]}),K==="manual"&&s.jsx(H,{...l("portalUsername"),placeholder:"Benutzername eingeben..."}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"radio",name:"usernameType",checked:K==="stressfrei",onChange:()=>{B("stressfrei"),u("portalUsername","")},className:"text-blue-600"}),s.jsx("span",{className:"text-sm",children:"Stressfrei-Wechseln Adresse"})]}),K==="stressfrei"&&s.jsx(Ie,{value:_,onChange:F=>Q(F.target.value),options:ne.map(F=>({value:F.id,label:F.email+(F.notes?` (${F.notes})`:"")})),placeholder:ne.length===0?"Keine Stressfrei-Adressen vorhanden":"Adresse auswählen..."}),K==="stressfrei"&&ne.length===0&&s.jsx("p",{className:"text-xs text-amber-600",children:"Keine Stressfrei-Wechseln Adressen für diesen Kunden vorhanden. Bitte zuerst beim Kunden anlegen."})]})]}),s.jsxs("div",{className:"mt-8",children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:a?"Neues Passwort (leer lassen = unverändert)":"Portal Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:le?"text":"password",...l("portalPassword"),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>de(!le),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:le?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})}),["ELECTRICITY","GAS"].includes(x)&&s.jsxs(X,{className:"mb-6",title:x==="ELECTRICITY"?"Strom-Details":"Gas-Details",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(Ie,{label:"Zähler",...l("meterId"),options:ce.filter(F=>F.type===x).map(F=>({value:F.id,label:`${F.meterNumber}${F.location?` (${F.location})`:""}`}))}),s.jsx(H,{label:"MaLo-ID (Marktlokations-ID)",...l("maloId")}),s.jsx(H,{label:`Jahresverbrauch (${x==="ELECTRICITY"?"kWh":"m³"})`,type:"number",...l("annualConsumption")}),x==="GAS"&&s.jsx(H,{label:"Jahresverbrauch (kWh)",type:"number",...l("annualConsumptionKwh")}),s.jsx(H,{label:"Grundpreis (€/Monat)",type:"number",step:"any",...l("basePrice")}),s.jsx(H,{label:"Arbeitspreis (€/kWh)",type:"number",step:"any",...l("unitPrice")}),s.jsx(H,{label:"Bonus (€)",type:"number",step:"0.01",...l("bonus")})]}),a&&s.jsxs("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700",children:[s.jsx("strong",{children:"Hinweis:"})," Zählerstände und Rechnungen werden in der"," ",s.jsx("span",{className:"font-medium",children:"Vertragsdetailansicht"})," verwaltet, nicht hier im Bearbeitungsformular."]})]}),["DSL","CABLE","FIBER"].includes(x)&&s.jsxs(s.Fragment,{children:[s.jsx(X,{className:"mb-6",title:x==="DSL"?"DSL-Details":x==="CABLE"?"Kabelinternet-Details":"Glasfaser-Details",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(H,{label:"Download (Mbit/s)",type:"number",...l("downloadSpeed")}),s.jsx(H,{label:"Upload (Mbit/s)",type:"number",...l("uploadSpeed")}),s.jsx(H,{label:"Router Modell",...l("routerModel")}),s.jsx(H,{label:"Router Seriennummer",...l("routerSerialNumber")}),s.jsx(H,{label:"Installationsdatum",type:"date",...l("installationDate"),value:d("installationDate")||"",onClear:()=>u("installationDate","")}),x==="FIBER"&&s.jsx(H,{label:"Home-ID",...l("homeId")}),((Ch=Ln==null?void 0:Ln.name)==null?void 0:Ch.toLowerCase().includes("vodafone"))&&["DSL","CABLE"].includes(x)&&s.jsx(H,{label:"Aktivierungscode",...l("activationCode")})]})}),s.jsx(X,{className:"mb-6",title:"Internet-Zugangsdaten (verschlüsselt)",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(H,{label:"Benutzername",...l("internetUsername")}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:a?"Neues Passwort (leer = beibehalten)":"Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:Ke?"text":"password",...l("internetPassword"),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>Ve(!Ke),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:Ke?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})}),s.jsxs(X,{className:"mb-6",title:"Rufnummern & SIP-Zugangsdaten",children:[s.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie Festnetz-Rufnummern mit SIP-Zugangsdaten erfassen."}),q.length>0&&s.jsx("div",{className:"space-y-4 mb-4",children:q.map((F,ie)=>s.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"font-medium",children:["Rufnummer ",ie+1]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:F.isMain,onChange:we=>{const pe=[...q];we.target.checked?pe.forEach((je,ct)=>je.isMain=ct===ie):pe[ie].isMain=!1,D(pe)},className:"rounded border-gray-300"}),"Hauptnummer"]})]}),s.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:()=>{D(q.filter((we,pe)=>pe!==ie))},children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[s.jsx(H,{label:"Rufnummer",value:F.phoneNumber,onChange:we=>{const pe=[...q];pe[ie].phoneNumber=we.target.value,D(pe)},placeholder:"z.B. 030 123456"}),s.jsx(H,{label:"SIP-Benutzername",value:F.sipUsername,onChange:we=>{const pe=[...q];pe[ie].sipUsername=we.target.value,D(pe)}}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:F.hasExistingSipPassword?"SIP-Passwort (bereits hinterlegt)":"SIP-Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:st[ie]?"text":"password",value:F.sipPassword,onChange:we=>{const pe=[...q];pe[ie].sipPassword=we.target.value,D(pe)},placeholder:F.hasExistingSipPassword?"Leer = beibehalten":"",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>C(we=>({...we,[ie]:!we[ie]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:st[ie]?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]}),s.jsx(H,{label:"SIP-Server",value:F.sipServer,onChange:we=>{const pe=[...q];pe[ie].sipServer=we.target.value,D(pe)},placeholder:"z.B. sip.provider.de"})]})]},ie))}),s.jsxs(T,{type:"button",variant:"secondary",onClick:()=>{D([...q,{phoneNumber:"",sipUsername:"",sipPassword:"",sipServer:"",isMain:q.length===0}])},children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Rufnummer hinzufügen"]})]})]}),x==="MOBILE"&&s.jsxs(s.Fragment,{children:[s.jsxs(X,{className:"mb-6",title:"Mobilfunk-Details",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(H,{label:"Datenvolumen (GB)",type:"number",...l("dataVolume")}),s.jsx(H,{label:"Inklusiv-Minuten",type:"number",...l("includedMinutes")}),s.jsx(H,{label:"Inklusiv-SMS",type:"number",...l("includedSMS")}),s.jsx(H,{label:"Gerät (Modell)",...l("deviceModel")}),s.jsx(H,{label:"Gerät (IMEI)",...l("deviceImei")})]}),s.jsx("div",{className:"mt-4 pt-4 border-t",children:s.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",...l("requiresMultisim"),className:"mt-1 rounded border-gray-300"}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Multisim erforderlich"}),s.jsx("p",{className:"text-sm text-amber-600 mt-1",children:"Hinweis: Multisim ist bei Klarmobil, Congstar und Otelo nicht buchbar. Muss Freenet oder vergleichbar sein."})]})]})})]}),s.jsxs(X,{className:"mb-6",title:"SIM-Karten",children:[s.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie alle SIM-Karten zum Vertrag erfassen (Hauptkarte und Multisim-Karten)."}),O.length>0&&s.jsx("div",{className:"space-y-4 mb-4",children:O.map((F,ie)=>s.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"font-medium",children:["SIM-Karte ",ie+1]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:F.isMain,onChange:we=>{const pe=[...O];we.target.checked?pe.forEach((je,ct)=>je.isMain=ct===ie):pe[ie].isMain=!1,R(pe)},className:"rounded border-gray-300"}),"Hauptkarte"]}),s.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[s.jsx("input",{type:"checkbox",checked:F.isMultisim,onChange:we=>{const pe=[...O];pe[ie].isMultisim=we.target.checked,R(pe)},className:"rounded border-gray-300"}),"Multisim"]})]}),s.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:()=>{R(O.filter((we,pe)=>pe!==ie))},children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[s.jsx(H,{label:"Rufnummer",value:F.phoneNumber,onChange:we=>{const pe=[...O];pe[ie].phoneNumber=we.target.value,R(pe)},placeholder:"z.B. 0171 1234567"}),s.jsx(H,{label:"SIM-Kartennummer",value:F.simCardNumber,onChange:we=>{const pe=[...O];pe[ie].simCardNumber=we.target.value,R(pe)},placeholder:"ICCID"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:F.hasExistingPin?"PIN (bereits hinterlegt)":"PIN"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:nt[ie]?"text":"password",value:F.pin,onChange:we=>{const pe=[...O];pe[ie].pin=we.target.value,R(pe)},placeholder:F.hasExistingPin?"Leer = beibehalten":"4-stellig",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>es(we=>({...we,[ie]:!we[ie]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:nt[ie]?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:F.hasExistingPuk?"PUK (bereits hinterlegt)":"PUK"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:Vt[ie]?"text":"password",value:F.puk,onChange:we=>{const pe=[...O];pe[ie].puk=we.target.value,R(pe)},placeholder:F.hasExistingPuk?"Leer = beibehalten":"8-stellig",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>ae(we=>({...we,[ie]:!we[ie]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:Vt[ie]?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]})]},ie))}),s.jsxs(T,{type:"button",variant:"secondary",onClick:()=>{R([...O,{phoneNumber:"",simCardNumber:"",pin:"",puk:"",isMultisim:!1,isMain:O.length===0}])},children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"SIM-Karte hinzufügen"]})]})]}),x==="TV"&&s.jsx(X,{className:"mb-6",title:"TV-Details",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(H,{label:"Receiver Modell",...l("receiverModel")}),s.jsx(H,{label:"Smartcard-Nummer",...l("smartcardNumber")}),s.jsx(H,{label:"Paket",...l("tvPackage"),placeholder:"z.B. Basis, Premium, Sport"})]})}),x==="CAR_INSURANCE"&&s.jsx(X,{className:"mb-6",title:"KFZ-Versicherung Details",children:s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[s.jsx(H,{label:"Kennzeichen",...l("licensePlate")}),s.jsx(H,{label:"HSN",...l("hsn")}),s.jsx(H,{label:"TSN",...l("tsn")}),s.jsx(H,{label:"FIN (VIN)",...l("vin")}),s.jsx(H,{label:"Fahrzeugtyp",...l("vehicleType")}),s.jsx(H,{label:"Erstzulassung",type:"date",...l("firstRegistration"),value:d("firstRegistration")||"",onClear:()=>u("firstRegistration","")}),s.jsx(H,{label:"SF-Klasse",...l("noClaimsClass")}),s.jsx(Ie,{label:"Versicherungsart",...l("insuranceType"),options:[{value:"LIABILITY",label:"Haftpflicht"},{value:"PARTIAL",label:"Teilkasko"},{value:"FULL",label:"Vollkasko"}]}),s.jsx(H,{label:"SB Teilkasko (€)",type:"number",...l("deductiblePartial")}),s.jsx(H,{label:"SB Vollkasko (€)",type:"number",...l("deductibleFull")}),s.jsx(H,{label:"Versicherungsscheinnummer",...l("policyNumber")}),s.jsx(H,{label:"Vorversicherer",...l("previousInsurer")})]})}),s.jsx(X,{className:"mb-6",title:"Notizen",children:s.jsx("textarea",{...l("notes"),rows:4,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"Interne Notizen..."})}),s.jsxs("div",{className:"flex justify-end gap-4",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:()=>n(-1),children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:ts,children:ts?"Speichern...":"Speichern"})]})]}),s.jsx(kC,{isOpen:Ge,onClose:()=>xt(!1)})]})}const CC={ELECTRICITY:ph,GAS:Cv,DSL:Ea,CABLE:Ea,FIBER:Ea,MOBILE:hh,TV:Fv,CAR_INSURANCE:kv},EC={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabel",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ"},DC={critical:"bg-red-100 border-red-300 text-red-800",warning:"bg-yellow-100 border-yellow-300 text-yellow-800",ok:"bg-green-100 border-green-300 text-green-800",none:"bg-gray-100 border-gray-300 text-gray-800"},AC={critical:"danger",warning:"warning",ok:"success",none:"default"},PC={cancellation_deadline:Sv,contract_ending:on,missing_cancellation_letter:Be,missing_cancellation_confirmation:Be,missing_portal_credentials:$S,missing_customer_number:Be,missing_provider:Be,missing_address:Be,missing_bank:Be,missing_meter:ph,missing_sim:hh,open_tasks:dl,pending_status:on,draft_status:Be,review_due:Pv,missing_invoice:mh},MC={cancellationDeadlines:"Kündigungsfristen",contractEnding:"Vertragsenden",missingCredentials:"Fehlende Zugangsdaten",missingData:"Fehlende Daten",openTasks:"Offene Aufgaben",pendingContracts:"Wartende Verträge",missingInvoices:"Fehlende Rechnungen",reviewDue:"Erneute Prüfung fällig"};function TC(){var w;const[e,t]=Sc(),[n,r]=j.useState(new Set),a=e.get("filter"),[i,l]=j.useState(a||"all");j.useEffect(()=>{i==="all"?e.delete("filter"):e.set("filter",i),t(e,{replace:!0})},[i,e,t]);const{data:o,isLoading:c,error:d}=fe({queryKey:["contract-cockpit"],queryFn:()=>Oe.getCockpit(),staleTime:0}),u=ge(),[h,x]=j.useState(null),[m,f]=j.useState(""),p=j.useRef(null);j.useEffect(()=>{const S=A=>{p.current&&!p.current.contains(A.target)&&(x(null),f(""))};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const b=G({mutationFn:({contractId:S,data:A})=>Oe.snooze(S,A),onSuccess:()=>{u.invalidateQueries({queryKey:["contract-cockpit"]}),x(null),f("")}}),g=(S,A)=>{A?b.mutate({contractId:S,data:{months:A}}):m&&b.mutate({contractId:S,data:{nextReviewDate:m}})},y=S=>{b.mutate({contractId:S,data:{}})},v=S=>{r(A=>{const O=new Set(A);return O.has(S)?O.delete(S):O.add(S),O})},N=j.useMemo(()=>{var A;if(!((A=o==null?void 0:o.data)!=null&&A.contracts))return[];const S=o.data.contracts;switch(i){case"critical":return S.filter(O=>O.highestUrgency==="critical");case"warning":return S.filter(O=>O.highestUrgency==="warning");case"ok":return S.filter(O=>O.highestUrgency==="ok");case"deadlines":return S.filter(O=>O.issues.some(R=>["cancellation_deadline","contract_ending"].includes(R.type)));case"credentials":return S.filter(O=>O.issues.some(R=>R.type.includes("credentials")));case"data":return S.filter(O=>O.issues.some(R=>R.type.startsWith("missing_")&&!R.type.includes("credentials")));case"tasks":return S.filter(O=>O.issues.some(R=>["open_tasks","pending_status","draft_status"].includes(R.type)));case"review":return S.filter(O=>O.issues.some(R=>R.type==="review_due"));case"invoices":return S.filter(O=>O.issues.some(R=>R.type.includes("invoice")));default:return S}},[(w=o==null?void 0:o.data)==null?void 0:w.contracts,i]);if(c)return s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})});if(d||!(o!=null&&o.data))return s.jsx("div",{className:"text-center py-12",children:s.jsx("p",{className:"text-red-500",children:"Fehler beim Laden des Cockpits"})});const{summary:E,thresholds:P}=o.data,I=S=>{var R,q,D,z;const A=n.has(S.id),O=CC[S.type]||Be;return s.jsxs("div",{className:`border rounded-lg mb-2 ${DC[S.highestUrgency]}`,children:[s.jsxs("div",{className:"flex items-center p-4 cursor-pointer hover:bg-opacity-50",onClick:()=>v(S.id),children:[s.jsx("div",{className:"w-6 mr-2",children:A?s.jsx(dn,{className:"w-5 h-5"}):s.jsx(Ft,{className:"w-5 h-5"})}),s.jsx(O,{className:"w-5 h-5 mr-3"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(ke,{to:`/contracts/${S.id}`,state:{from:"cockpit",filter:i!=="all"?i:void 0},className:"font-medium hover:underline",onClick:k=>k.stopPropagation(),children:S.contractNumber}),s.jsxs(ve,{variant:AC[S.highestUrgency],children:[S.issues.length," ",S.highestUrgency==="ok"?S.issues.length===1?"Hinweis":"Hinweise":S.issues.length===1?"Problem":"Probleme"]}),s.jsx("span",{className:"text-sm",children:EC[S.type]})]}),s.jsxs("div",{className:"text-sm mt-1",children:[s.jsxs(ke,{to:`/customers/${S.customer.id}`,className:"hover:underline",onClick:k=>k.stopPropagation(),children:[S.customer.customerNumber," - ",S.customer.name]}),(((R=S.provider)==null?void 0:R.name)||S.providerName)&&s.jsxs("span",{className:"ml-2",children:["| ",((q=S.provider)==null?void 0:q.name)||S.providerName,(((D=S.tariff)==null?void 0:D.name)||S.tariffName)&&` - ${((z=S.tariff)==null?void 0:z.name)||S.tariffName}`]})]})]}),s.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[s.jsxs("div",{className:"relative",ref:h===S.id?p:void 0,children:[s.jsx("button",{onClick:k=>{k.stopPropagation(),x(h===S.id?null:S.id),f("")},className:"p-2 hover:bg-white hover:bg-opacity-50 rounded",title:"Zurückstellen",children:s.jsx(wv,{className:"w-4 h-4"})}),h===S.id&&s.jsxs("div",{className:"absolute right-0 top-full mt-1 w-56 bg-white border rounded-lg shadow-lg z-50 p-3",onClick:k=>k.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-medium mb-2",children:"Zurückstellen"}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("button",{onClick:()=>g(S.id,3),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded",disabled:b.isPending,children:"+3 Monate"}),s.jsxs("button",{onClick:()=>g(S.id,6),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded bg-blue-50 border-blue-200",disabled:b.isPending,children:["+6 Monate ",s.jsx("span",{className:"text-xs text-gray-500",children:"(Empfohlen)"})]}),s.jsx("button",{onClick:()=>g(S.id,12),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded",disabled:b.isPending,children:"+12 Monate"})]}),s.jsxs("div",{className:"border-t mt-2 pt-2",children:[s.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Eigenes Datum:"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(H,{type:"date",value:m,onChange:k=>f(k.target.value),className:"flex-1 text-sm",min:new Date().toISOString().split("T")[0]}),s.jsx(T,{size:"sm",onClick:()=>g(S.id),disabled:!m||b.isPending,children:"OK"})]})]}),S.issues.some(k=>k.type==="review_due")&&s.jsx("div",{className:"border-t mt-2 pt-2",children:s.jsxs("button",{onClick:()=>y(S.id),className:"w-full text-left px-3 py-2 text-sm hover:bg-red-50 text-red-600 rounded flex items-center gap-2",disabled:b.isPending,children:[s.jsx(Pv,{className:"w-4 h-4"}),"Snooze aufheben"]})})]})]}),s.jsx(ke,{to:`/contracts/${S.id}`,state:{from:"cockpit",filter:i!=="all"?i:void 0},className:"p-2 hover:bg-white hover:bg-opacity-50 rounded",onClick:k=>k.stopPropagation(),title:"Zum Vertrag",children:s.jsx(Ae,{className:"w-4 h-4"})})]})]}),A&&s.jsx("div",{className:"border-t px-4 py-3 bg-white bg-opacity-50",children:s.jsx("div",{className:"space-y-2",children:S.issues.map((k,K)=>{const B=PC[k.type]||kn,_=k.urgency==="critical"?kn:k.urgency==="warning"?hs:k.urgency==="ok"?As:on;return s.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[s.jsx(_,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${k.urgency==="critical"?"text-red-500":k.urgency==="warning"?"text-yellow-500":k.urgency==="ok"?"text-green-500":"text-gray-500"}`}),s.jsx(B,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-gray-500"}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:k.label}),k.details&&s.jsx("span",{className:"text-gray-600 ml-2",children:k.details})]})]},K)})})})]},S.id)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(kn,{className:"w-6 h-6 text-red-500"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Vertrags-Cockpit"})]}),s.jsx(ke,{to:"/settings/deadlines",className:"text-sm text-blue-600 hover:underline",children:"Fristenschwellen anpassen"})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-6",children:[s.jsx(X,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:s.jsx(kn,{className:"w-6 h-6 text-red-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-red-600",children:E.criticalCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["Kritisch (<",P.criticalDays," Tage)"]})]})]})}),s.jsx(X,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-yellow-100 rounded-lg",children:s.jsx(hs,{className:"w-6 h-6 text-yellow-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-yellow-600",children:E.warningCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["Warnung (<",P.warningDays," Tage)"]})]})]})}),s.jsx(X,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-green-100 rounded-lg",children:s.jsx(As,{className:"w-6 h-6 text-green-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-green-600",children:E.okCount}),s.jsxs("p",{className:"text-sm text-gray-500",children:["OK (<",P.okDays," Tage)"]})]})]})}),s.jsx(X,{className:"!p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-gray-100 rounded-lg",children:s.jsx(Be,{className:"w-6 h-6 text-gray-500"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-gray-600",children:E.totalContracts}),s.jsx("p",{className:"text-sm text-gray-500",children:"Verträge mit Handlungsbedarf"})]})]})})]}),s.jsx(X,{className:"mb-6",children:s.jsx("div",{className:"flex flex-wrap gap-4",children:Object.entries(E.byCategory).map(([S,A])=>A>0&&s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsxs("span",{className:"font-medium",children:[MC[S]||S,":"]}),s.jsx(ve,{variant:"default",children:A})]},S))})}),s.jsx(X,{className:"mb-6",children:s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx("span",{className:"text-sm text-gray-600",children:"Filter:"}),s.jsx(Ie,{value:i,onChange:S=>l(S.target.value),options:[{value:"all",label:`Alle (${o.data.contracts.length})`},{value:"critical",label:`Kritisch (${E.criticalCount})`},{value:"warning",label:`Warnung (${E.warningCount})`},{value:"ok",label:`OK (${E.okCount})`},{value:"deadlines",label:`Fristen (${E.byCategory.cancellationDeadlines+E.byCategory.contractEnding})`},{value:"credentials",label:`Zugangsdaten (${E.byCategory.missingCredentials})`},{value:"data",label:`Fehlende Daten (${E.byCategory.missingData})`},{value:"tasks",label:`Aufgaben/Status (${E.byCategory.openTasks+E.byCategory.pendingContracts})`},{value:"review",label:`Erneute Prüfung (${E.byCategory.reviewDue||0})`},{value:"invoices",label:`Fehlende Rechnungen (${E.byCategory.missingInvoices||0})`}],className:"w-64"}),s.jsxs("span",{className:"text-sm text-gray-500",children:[N.length," Verträge angezeigt"]})]})}),N.length===0?s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:i==="all"?s.jsxs(s.Fragment,{children:[s.jsx(As,{className:"w-12 h-12 mx-auto mb-4 text-green-500"}),s.jsx("p",{className:"text-lg font-medium",children:"Alles in Ordnung!"}),s.jsx("p",{children:"Keine Verträge mit Handlungsbedarf gefunden."})]}):s.jsx("p",{children:"Keine Verträge für diesen Filter gefunden."})})}):s.jsx("div",{children:N.map(I)})]})}const Kx={OPEN:"Offen",COMPLETED:"Erledigt"},FC={OPEN:"warning",COMPLETED:"success"};function IC(){var B;const e=Yt(),t=ge(),{isCustomerPortal:n,user:r,hasPermission:a}=We(),[i,l]=j.useState("OPEN"),[o,c]=j.useState(new Set),[d,u]=j.useState(!1),[h,x]=j.useState({}),[m,f]=j.useState(null),p=n?"Support-Anfragen":"Aufgaben",b=n?"Anfrage":"Aufgabe",{data:g,isLoading:y}=fe({queryKey:["app-settings-public"],queryFn:()=>Xr.getPublic(),enabled:n,staleTime:0}),v=!y&&((B=g==null?void 0:g.data)==null?void 0:B.customerSupportTicketsEnabled)==="true",{data:N,isLoading:E}=fe({queryKey:["all-tasks",i],queryFn:()=>et.getAll({status:i||void 0}),staleTime:0}),P=G({mutationFn:_=>et.completeSubtask(_),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),t.invalidateQueries({queryKey:["task-stats"]})}}),I=G({mutationFn:_=>et.reopenSubtask(_),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),t.invalidateQueries({queryKey:["task-stats"]})}}),w=G({mutationFn:({taskId:_,title:Q})=>n?et.createReply(_,Q):et.createSubtask(_,Q),onSuccess:(_,{taskId:Q})=>{t.invalidateQueries({queryKey:["all-tasks"]}),x(le=>({...le,[Q]:""}))}}),S=G({mutationFn:_=>et.delete(_),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),t.invalidateQueries({queryKey:["task-stats"]})}}),A=G({mutationFn:({taskId:_,data:Q})=>et.update(_,Q),onSuccess:()=>{t.invalidateQueries({queryKey:["all-tasks"]}),f(null)}}),O=j.useMemo(()=>{var de;if(!(N!=null&&N.data))return{ownTasks:[],representedTasks:[],allTasks:[]};const _=N.data;if(!n)return{allTasks:_,ownTasks:[],representedTasks:[]};const Q=[],le=[];for(const Ke of _)((de=Ke.contract)==null?void 0:de.customerId)===(r==null?void 0:r.customerId)?Q.push(Ke):le.push(Ke);return{ownTasks:Q,representedTasks:le,allTasks:[]}},[N==null?void 0:N.data,n,r==null?void 0:r.customerId]),R=_=>{c(Q=>{const le=new Set(Q);return le.has(_)?le.delete(_):le.add(_),le})},q=_=>{P.isPending||I.isPending||(_.status==="COMPLETED"?I.mutate(_.id):P.mutate(_.id))},D=_=>{var le;const Q=(le=h[_])==null?void 0:le.trim();Q&&w.mutate({taskId:_,title:Q})},z=!n&&a("contracts:update"),k=(_,Q=!1)=>{var Ge,xt,Z,Fe,Xe,J;const le=o.has(_.id),de=_.subtasks&&_.subtasks.length>0,Ke=((Ge=_.subtasks)==null?void 0:Ge.filter(ue=>ue.status==="COMPLETED").length)||0,Ve=((xt=_.subtasks)==null?void 0:xt.length)||0,st=_.status==="COMPLETED",C=new Date(_.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),nt=!n&&a("contracts:update"),es=!n&&a("contracts:update"),Vt=_.contract?`${_.contract.contractNumber} - ${((Z=_.contract.provider)==null?void 0:Z.name)||_.contract.providerName||"Kein Anbieter"}`:`Vertrag #${_.contractId}`,ae=(Fe=_.contract)!=null&&Fe.customer?_.contract.customer.companyName||`${_.contract.customer.firstName} ${_.contract.customer.lastName}`:"";return s.jsxs("div",{className:"border rounded-lg mb-2",children:[s.jsxs("div",{className:"flex items-center p-4 hover:bg-gray-50 cursor-pointer",onClick:()=>R(_.id),children:[s.jsx("div",{className:"w-6 mr-2",children:le?s.jsx(dn,{className:"w-5 h-5 text-gray-400"}):s.jsx(Ft,{className:"w-5 h-5 text-gray-400"})}),s.jsx("div",{className:"mr-3",children:_.status==="COMPLETED"?s.jsx(As,{className:"w-5 h-5 text-green-500"}):s.jsx(on,{className:"w-5 h-5 text-yellow-500"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium",children:_.title}),s.jsx(ve,{variant:FC[_.status],children:Kx[_.status]}),de&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",Ke,"/",Ve," erledigt)"]})]}),s.jsxs("div",{className:"text-sm text-gray-500 mt-1 flex items-center gap-2",children:[s.jsx(Be,{className:"w-4 h-4"}),s.jsx(ke,{to:`/contracts/${_.contractId}`,className:"text-blue-600 hover:underline",onClick:ue=>ue.stopPropagation(),children:Vt}),Q&&ae&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-gray-400",children:"|"}),s.jsx("span",{children:ae})]})]}),_.description&&s.jsx("p",{className:"text-sm text-gray-600 mt-1 line-clamp-2",children:_.description}),s.jsxs("div",{className:"text-xs text-gray-400 mt-1",children:[_.createdBy," • ",C]})]}),s.jsxs("div",{className:"ml-4 flex gap-2",children:[nt&&s.jsx(T,{variant:"ghost",size:"sm",onClick:ue=>{ue.stopPropagation(),f(_)},title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),es&&s.jsx(T,{variant:"ghost",size:"sm",onClick:ue=>{ue.stopPropagation(),confirm("Aufgabe wirklich löschen?")&&S.mutate(_.id)},title:"Löschen",className:"text-red-500 hover:text-red-700",children:s.jsx(Ne,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:ue=>{ue.stopPropagation(),e(`/contracts/${_.contractId}`)},title:"Zum Vertrag",children:s.jsx(Ae,{className:"w-4 h-4"})})]})]}),le&&s.jsxs("div",{className:"border-t bg-gray-50 px-4 py-3",children:[de&&s.jsx("div",{className:"space-y-2 mb-4",children:(Xe=_.subtasks)==null?void 0:Xe.map(ue=>{const ts=new Date(ue.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"});return s.jsxs("div",{className:`flex items-start gap-2 text-sm ml-6 ${z?"cursor-pointer hover:bg-gray-100 rounded px-2 py-1 -mx-2":""}`,onClick:z?()=>q(ue):void 0,children:[s.jsx("span",{className:"flex-shrink-0 mt-0.5",children:ue.status==="COMPLETED"?s.jsx(As,{className:"w-4 h-4 text-green-500"}):s.jsx(No,{className:"w-4 h-4 text-gray-400"})}),s.jsxs("span",{className:ue.status==="COMPLETED"?"text-gray-500 line-through":"",children:[ue.title,s.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[ue.createdBy," • ",ts]})]})]},ue.id)})}),!st&&(z||n)&&s.jsxs("div",{className:"flex gap-2 ml-6",children:[s.jsx(H,{placeholder:n?"Antwort schreiben...":"Neue Unteraufgabe...",value:h[_.id]||"",onChange:ue=>x(ts=>({...ts,[_.id]:ue.target.value})),onKeyDown:ue=>{ue.key==="Enter"&&!ue.shiftKey&&(ue.preventDefault(),D(_.id))},className:"flex-1"}),s.jsx(T,{size:"sm",onClick:()=>D(_.id),disabled:!((J=h[_.id])!=null&&J.trim())||w.isPending,children:s.jsx(Fl,{className:"w-4 h-4"})})]}),!de&&st&&s.jsx("p",{className:"text-gray-500 text-sm text-center py-2",children:"Keine Unteraufgaben vorhanden."})]})]},_.id)},K=n?v:a("contracts:update");return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:p}),K&&s.jsxs(T,{onClick:()=>u(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neue ",b]})]}),s.jsx(X,{className:"mb-6",children:s.jsx("div",{className:"flex gap-4 flex-wrap items-center",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm text-gray-600",children:"Status:"}),s.jsx(Ie,{value:i,onChange:_=>l(_.target.value),options:[{value:"",label:"Alle"},...Object.entries(Kx).map(([_,Q])=>({value:_,label:Q}))],className:"w-40"})]})})}),E?s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."})}):s.jsx(s.Fragment,{children:n?s.jsxs("div",{className:"space-y-6",children:[s.jsxs(X,{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:[s.jsx(ii,{className:"w-5 h-5 text-blue-600"}),s.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:["Meine ",p]}),s.jsx(ve,{variant:"default",children:O.ownTasks.length})]}),O.ownTasks.length>0?s.jsx("div",{children:O.ownTasks.map(_=>k(_,!1))}):s.jsxs("p",{className:"text-gray-500 text-center py-4",children:["Keine eigenen ",p.toLowerCase()," vorhanden."]})]}),O.representedTasks.length>0&&s.jsxs(X,{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:[s.jsx(Ca,{className:"w-5 h-5 text-purple-600"}),s.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:[p," freigegebener Kunden"]}),s.jsx(ve,{variant:"default",children:O.representedTasks.length})]}),s.jsx("div",{children:O.representedTasks.map(_=>k(_,!0))})]})]}):s.jsx(X,{children:O.allTasks&&O.allTasks.length>0?s.jsx("div",{children:O.allTasks.map(_=>k(_,!0))}):s.jsxs("div",{className:"text-center py-8 text-gray-500",children:["Keine ",p.toLowerCase()," gefunden."]})})}),n?s.jsx(RC,{isOpen:d,onClose:()=>u(!1)}):s.jsx(LC,{isOpen:d,onClose:()=>u(!1)}),m&&s.jsx(OC,{task:m,onClose:()=>f(null),onSave:_=>A.mutate({taskId:m.id,data:_}),isPending:A.isPending})]})}function RC({isOpen:e,onClose:t}){const{user:n}=We(),r=Yt(),a=ge(),[i,l]=j.useState("own"),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,x]=j.useState(""),[m,f]=j.useState(!1),[p,b]=j.useState(""),{data:g}=fe({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>Oe.getAll({customerId:n==null?void 0:n.customerId}),enabled:e}),y=j.useMemo(()=>{if(!(g!=null&&g.data))return{own:[],represented:{}};const w=[],S={};for(const A of g.data)if(A.customerId===(n==null?void 0:n.customerId))w.push(A);else{if(!S[A.customerId]){const O=A.customer?A.customer.companyName||`${A.customer.firstName} ${A.customer.lastName}`:`Kunde ${A.customerId}`;S[A.customerId]={name:O,contracts:[]}}S[A.customerId].contracts.push(A)}return{own:w,represented:S}},[g==null?void 0:g.data,n==null?void 0:n.customerId]),v=Object.keys(y.represented).length>0,N=j.useMemo(()=>{var w;return i==="own"?y.own:((w=y.represented[i])==null?void 0:w.contracts)||[]},[i,y]),E=j.useMemo(()=>{if(!p)return N;const w=p.toLowerCase();return N.filter(S=>S.contractNumber.toLowerCase().includes(w)||(S.providerName||"").toLowerCase().includes(w)||(S.tariffName||"").toLowerCase().includes(w))},[N,p]),P=async()=>{if(!(!o||!d.trim())){f(!0);try{await et.createSupportTicket(o,{title:d.trim(),description:h.trim()||void 0}),a.invalidateQueries({queryKey:["all-tasks"]}),a.invalidateQueries({queryKey:["task-stats"]}),t(),u(""),x(""),c(null),l("own"),r(`/contracts/${o}`)}catch(w){console.error("Fehler beim Erstellen der Support-Anfrage:",w),alert("Fehler beim Erstellen der Support-Anfrage. Bitte versuchen Sie es erneut.")}finally{f(!1)}}},I=()=>{u(""),x(""),c(null),l("own"),b(""),t()};return s.jsx(qe,{isOpen:e,onClose:I,title:"Neue Support-Anfrage",children:s.jsxs("div",{className:"space-y-4",children:[v&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde"}),s.jsxs("select",{value:i,onChange:w=>{const S=w.target.value;l(S==="own"?"own":parseInt(S)),c(null),b("")},className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",children:[s.jsx("option",{value:"own",children:"Eigene Verträge"}),Object.entries(y.represented).map(([w,{name:S}])=>s.jsx("option",{value:w,children:S},w))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(H,{placeholder:"Vertrag suchen...",value:p,onChange:w=>b(w.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-lg",children:E.length>0?E.map(w=>s.jsxs("div",{onClick:()=>c(w.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${o===w.id?"bg-blue-50 border-blue-200":""}`,children:[s.jsx("div",{className:"font-medium",children:w.contractNumber}),s.jsxs("div",{className:"text-sm text-gray-500",children:[w.providerName||"Kein Anbieter",w.tariffName&&` - ${w.tariffName}`]})]},w.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Verträge gefunden."})})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),s.jsx(H,{value:d,onChange:w=>u(w.target.value),placeholder:"Kurze Beschreibung Ihres Anliegens"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),s.jsx("textarea",{value:h,onChange:w=>x(w.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:4,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:I,children:"Abbrechen"}),s.jsx(T,{onClick:P,disabled:!o||!d.trim()||m,children:m?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function LC({isOpen:e,onClose:t}){const n=Yt(),r=ge(),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(""),[u,h]=j.useState(""),[x,m]=j.useState(!1),[f,p]=j.useState(!1),[b,g]=j.useState(""),[y,v]=j.useState(""),{data:N}=fe({queryKey:["customers-for-task"],queryFn:()=>At.getAll({limit:100}),enabled:e}),{data:E}=fe({queryKey:["contracts-for-task",a],queryFn:()=>Oe.getAll({customerId:a}),enabled:e&&a!==null}),P=j.useMemo(()=>{if(!(N!=null&&N.data))return[];if(!b)return N.data;const O=b.toLowerCase();return N.data.filter(R=>R.customerNumber.toLowerCase().includes(O)||R.firstName.toLowerCase().includes(O)||R.lastName.toLowerCase().includes(O)||(R.companyName||"").toLowerCase().includes(O))},[N==null?void 0:N.data,b]),I=j.useMemo(()=>{if(!(E!=null&&E.data))return[];if(!y)return E.data;const O=y.toLowerCase();return E.data.filter(R=>R.contractNumber.toLowerCase().includes(O)||(R.providerName||"").toLowerCase().includes(O)||(R.tariffName||"").toLowerCase().includes(O))},[E==null?void 0:E.data,y]),w=async()=>{if(!(!l||!c.trim())){p(!0);try{await et.create(l,{title:c.trim(),description:u.trim()||void 0,visibleInPortal:x}),r.invalidateQueries({queryKey:["all-tasks"]}),r.invalidateQueries({queryKey:["task-stats"]}),t(),d(""),h(""),m(!1),o(null),i(null),n(`/contracts/${l}`)}catch(O){console.error("Fehler beim Erstellen der Aufgabe:",O),alert("Fehler beim Erstellen der Aufgabe. Bitte versuchen Sie es erneut.")}finally{p(!1)}}},S=()=>{d(""),h(""),m(!1),o(null),i(null),g(""),v(""),t()},A=O=>{const R=O.companyName||`${O.firstName} ${O.lastName}`;return`${O.customerNumber} - ${R}`};return s.jsx(qe,{isOpen:e,onClose:S,title:"Neue Aufgabe",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde *"}),s.jsx(H,{placeholder:"Kunde suchen...",value:b,onChange:O=>g(O.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:P.length>0?P.map(O=>s.jsx("div",{onClick:()=>{i(O.id),o(null),v("")},className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${a===O.id?"bg-blue-50 border-blue-200":""}`,children:s.jsx("div",{className:"font-medium",children:A(O)})},O.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Kunden gefunden."})})]}),a&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),s.jsx(H,{placeholder:"Vertrag suchen...",value:y,onChange:O=>v(O.target.value),className:"mb-2"}),s.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:I.length>0?I.map(O=>s.jsxs("div",{onClick:()=>o(O.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${l===O.id?"bg-blue-50 border-blue-200":""}`,children:[s.jsx("div",{className:"font-medium",children:O.contractNumber}),s.jsxs("div",{className:"text-sm text-gray-500",children:[O.providerName||"Kein Anbieter",O.tariffName&&` - ${O.tariffName}`]})]},O.id)):s.jsx("div",{className:"p-3 text-gray-500 text-center",children:E?"Keine Verträge gefunden.":"Laden..."})})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),s.jsx(H,{value:c,onChange:O=>d(O.target.value),placeholder:"Aufgabentitel"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),s.jsx("textarea",{value:u,onChange:O=>h(O.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),s.jsx("div",{children:s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:x,onChange:O=>m(O.target.checked),className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),s.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:S,children:"Abbrechen"}),s.jsx(T,{onClick:w,disabled:!l||!c.trim()||f,children:f?"Wird erstellt...":"Aufgabe erstellen"})]})]})})}function OC({task:e,onClose:t,onSave:n,isPending:r}){const[a,i]=j.useState(e.title),[l,o]=j.useState(e.description||""),[c,d]=j.useState(e.visibleInPortal||!1),u=()=>{a.trim()&&n({title:a.trim(),description:l.trim()||void 0,visibleInPortal:c})};return s.jsx(qe,{isOpen:!0,onClose:t,title:"Aufgabe bearbeiten",children:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),s.jsx(H,{value:a,onChange:h=>i(h.target.value),placeholder:"Aufgabentitel"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),s.jsx("textarea",{value:l,onChange:h=>o(h.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),s.jsx("div",{children:s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:c,onChange:h=>d(h.target.checked),className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),s.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(T,{variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{onClick:u,disabled:!a.trim()||r,children:r?"Wird gespeichert...":"Speichern"})]})]})})}function zC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=We(),o=ge(),{data:c,isLoading:d}=fe({queryKey:["platforms",a],queryFn:()=>il.getAll(a)}),u=G({mutationFn:il.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["platforms"]})}}),h=m=>{r(m),t(!0)},x=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Vertriebsplattformen"}),l("platforms:create")&&s.jsxs(T,{onClick:()=>t(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neue Plattform"]})]}),s.jsxs(X,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kontakt"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:c.data.map(m=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-medium",children:m.name}),s.jsx("td",{className:"py-3 px-4 text-gray-500",children:m.contactInfo||"-"}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ve,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(He,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Plattform wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})})]},m.id))})]})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Plattformen vorhanden."})]}),s.jsx($C,{isOpen:e,onClose:x,platform:n})]})}function $C({isOpen:e,onClose:t,platform:n}){const r=ge(),[a,i]=j.useState({name:"",contactInfo:"",isActive:!0});j.useState(()=>{i(n?{name:n.name,contactInfo:n.contactInfo||"",isActive:n.isActive}:{name:"",contactInfo:"",isActive:!0})}),n&&a.name!==n.name?i({name:n.name,contactInfo:n.contactInfo||"",isActive:n.isActive}):!n&&a.name;const l=G({mutationFn:il.create,onSuccess:()=>{r.invalidateQueries({queryKey:["platforms"]}),t(),i({name:"",contactInfo:"",isActive:!0})}}),o=G({mutationFn:u=>il.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["platforms"]}),t()}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:n?"Plattform bearbeiten":"Neue Plattform",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(H,{label:"Name *",value:a.name,onChange:u=>i({...a,name:u.target.value}),required:!0}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kontaktinformationen"}),s.jsx("textarea",{value:a.contactInfo,onChange:u=>i({...a,contactInfo:u.target.value}),rows:3,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"E-Mail, Telefon, Ansprechpartner..."})]}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function _C(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=We(),o=ge(),{data:c,isLoading:d}=fe({queryKey:["cancellation-periods",a],queryFn:()=>ll.getAll(a)}),u=G({mutationFn:ll.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["cancellation-periods"]})}}),h=m=>{r(m),t(!0)},x=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Kündigungsfristen"}),l("platforms:create")&&s.jsxs(T,{onClick:()=>t(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neue Frist"]})]}),s.jsxs(X,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),s.jsxs("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:[s.jsx("strong",{children:"Code-Format:"})," Zahl + Buchstabe (T=Tage, M=Monate, J=Jahre)",s.jsx("br",{}),s.jsx("strong",{children:"Beispiele:"})," 14T = 14 Tage, 3M = 3 Monate, 1J = 1 Jahr"]}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Code"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beschreibung"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:c.data.map(m=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono font-medium",children:m.code}),s.jsx("td",{className:"py-3 px-4",children:m.description}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ve,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(He,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Kündigungsfrist wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})})]},m.id))})]})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Kündigungsfristen vorhanden."})]}),s.jsx(KC,{isOpen:e,onClose:x,period:n})]})}function KC({isOpen:e,onClose:t,period:n}){const r=ge(),[a,i]=j.useState({code:"",description:"",isActive:!0});j.useEffect(()=>{e&&i(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[e,n]);const l=G({mutationFn:ll.create,onSuccess:()=>{r.invalidateQueries({queryKey:["cancellation-periods"]}),t(),i({code:"",description:"",isActive:!0})}}),o=G({mutationFn:u=>ll.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["cancellation-periods"]}),t()}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:n?"Kündigungsfrist bearbeiten":"Neue Kündigungsfrist",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(H,{label:"Code *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 14T, 3M, 1J"}),s.jsx(H,{label:"Beschreibung *",value:a.description,onChange:u=>i({...a,description:u.target.value}),required:!0,placeholder:"z.B. 14 Tage, 3 Monate, 1 Jahr"}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function BC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=We(),o=ge(),{data:c,isLoading:d}=fe({queryKey:["contract-durations",a],queryFn:()=>ol.getAll(a)}),u=G({mutationFn:ol.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["contract-durations"]})}}),h=m=>{r(m),t(!0)},x=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragslaufzeiten"}),l("platforms:create")&&s.jsxs(T,{onClick:()=>t(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neue Laufzeit"]})]}),s.jsxs(X,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),s.jsxs("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:[s.jsx("strong",{children:"Code-Format:"})," Zahl + Buchstabe (T=Tage, M=Monate, J=Jahre)",s.jsx("br",{}),s.jsx("strong",{children:"Beispiele:"})," 12M = 12 Monate, 24M = 24 Monate, 2J = 2 Jahre"]}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Code"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beschreibung"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:c.data.map(m=>s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsx("td",{className:"py-3 px-4 font-mono font-medium",children:m.code}),s.jsx("td",{className:"py-3 px-4",children:m.description}),s.jsx("td",{className:"py-3 px-4",children:s.jsx(ve,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>h(m),children:s.jsx(He,{className:"w-4 h-4"})}),l("platforms:delete")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Laufzeit wirklich löschen?")&&u.mutate(m.id)},children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})})]},m.id))})]})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Laufzeiten vorhanden."})]}),s.jsx(UC,{isOpen:e,onClose:x,duration:n})]})}function UC({isOpen:e,onClose:t,duration:n}){const r=ge(),[a,i]=j.useState({code:"",description:"",isActive:!0});j.useEffect(()=>{e&&i(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[e,n]);const l=G({mutationFn:ol.create,onSuccess:()=>{r.invalidateQueries({queryKey:["contract-durations"]}),t(),i({code:"",description:"",isActive:!0})}}),o=G({mutationFn:u=>ol.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["contract-durations"]}),t()}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:n?"Laufzeit bearbeiten":"Neue Laufzeit",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(H,{label:"Code *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 12M, 24M, 2J"}),s.jsx(H,{label:"Beschreibung *",value:a.description,onChange:u=>i({...a,description:u.target.value}),required:!0,placeholder:"z.B. 12 Monate, 24 Monate, 2 Jahre"}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function qC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),[l,o]=j.useState(new Set),{hasPermission:c}=We(),d=ge(),{data:u,isLoading:h}=fe({queryKey:["providers",a],queryFn:()=>Xa.getAll(a)}),x=G({mutationFn:Xa.delete,onSuccess:()=>{d.invalidateQueries({queryKey:["providers"]})},onError:b=>{alert(b.message)}}),m=b=>{o(g=>{const y=new Set(g);return y.has(b)?y.delete(b):y.add(b),y})},f=b=>{r(b),t(!0)},p=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Anbieter & Tarife"}),c("providers:create")&&s.jsxs(T,{onClick:()=>t(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neuer Anbieter"]})]}),s.jsxs(X,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:b=>i(b.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),h?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):u!=null&&u.data&&u.data.length>0?s.jsx("div",{className:"space-y-2",children:u.data.map(b=>s.jsx(VC,{provider:b,isExpanded:l.has(b.id),onToggle:()=>m(b.id),onEdit:()=>f(b),onDelete:()=>{confirm("Anbieter wirklich löschen?")&&x.mutate(b.id)},hasPermission:c,showInactive:a},b.id))}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Anbieter vorhanden."})]}),s.jsx(QC,{isOpen:e,onClose:p,provider:n})]})}function VC({provider:e,isExpanded:t,onToggle:n,onEdit:r,onDelete:a,hasPermission:i,showInactive:l}){var f,p;const[o,c]=j.useState(!1),[d,u]=j.useState(null),h=ge(),x=G({mutationFn:gv.delete,onSuccess:()=>{h.invalidateQueries({queryKey:["providers"]})},onError:b=>{alert(b.message)}}),m=((f=e.tariffs)==null?void 0:f.filter(b=>l||b.isActive))||[];return s.jsxs("div",{className:"border rounded-lg",children:[s.jsxs("div",{className:"flex items-center p-4 hover:bg-gray-50",children:[s.jsx("button",{onClick:n,className:"mr-3 p-1 hover:bg-gray-200 rounded",children:t?s.jsx(dn,{className:"w-5 h-5 text-gray-400"}):s.jsx(Ft,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium",children:e.name}),s.jsx(ve,{variant:e.isActive?"success":"danger",children:e.isActive?"Aktiv":"Inaktiv"}),s.jsxs("span",{className:"text-sm text-gray-500",children:["(",m.length," Tarife, ",((p=e._count)==null?void 0:p.contracts)||0," Verträge)"]})]}),e.portalUrl&&s.jsxs("a",{href:e.portalUrl,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-600 hover:underline flex items-center gap-1 mt-1",children:[s.jsx(dh,{className:"w-3 h-3"}),e.portalUrl]})]}),s.jsxs("div",{className:"flex gap-2 ml-4",children:[i("providers:update")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:r,title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),i("providers:delete")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:a,title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]}),t&&s.jsxs("div",{className:"border-t bg-gray-50 p-4",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"font-medium text-gray-700",children:"Tarife"}),i("providers:create")&&s.jsxs(T,{size:"sm",onClick:()=>c(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-1"}),"Tarif hinzufügen"]})]}),m.length>0?s.jsx("div",{className:"space-y-2",children:m.map(b=>{var g;return s.jsxs("div",{className:"flex items-center justify-between bg-white p-3 rounded border",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:b.name}),s.jsx(ve,{variant:b.isActive?"success":"danger",className:"text-xs",children:b.isActive?"Aktiv":"Inaktiv"}),((g=b._count)==null?void 0:g.contracts)!==void 0&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",b._count.contracts," Verträge)"]})]}),s.jsxs("div",{className:"flex gap-1",children:[i("providers:update")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{u(b),c(!0)},title:"Bearbeiten",children:s.jsx(He,{className:"w-3 h-3"})}),i("providers:delete")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Tarif wirklich löschen?")&&x.mutate(b.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-3 h-3 text-red-500"})})]})]},b.id)})}):s.jsx("p",{className:"text-sm text-gray-500",children:"Keine Tarife vorhanden."})]}),s.jsx(HC,{isOpen:o,onClose:()=>{c(!1),u(null)},providerId:e.id,tariff:d})]})}function QC({isOpen:e,onClose:t,provider:n}){const r=ge(),[a,i]=j.useState({name:"",portalUrl:"",usernameFieldName:"",passwordFieldName:"",isActive:!0});j.useEffect(()=>{e&&i(n?{name:n.name,portalUrl:n.portalUrl||"",usernameFieldName:n.usernameFieldName||"",passwordFieldName:n.passwordFieldName||"",isActive:n.isActive}:{name:"",portalUrl:"",usernameFieldName:"",passwordFieldName:"",isActive:!0})},[e,n]);const l=G({mutationFn:Xa.create,onSuccess:()=>{r.invalidateQueries({queryKey:["providers"]}),t()},onError:u=>{alert(u.message)}}),o=G({mutationFn:u=>Xa.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["providers"]}),t()},onError:u=>{alert(u.message)}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:n?"Anbieter bearbeiten":"Neuer Anbieter",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(H,{label:"Anbietername *",value:a.name,onChange:u=>i({...a,name:u.target.value}),required:!0,placeholder:"z.B. Vodafone, E.ON, Allianz"}),s.jsx(H,{label:"Portal-URL (Login-Seite)",value:a.portalUrl,onChange:u=>i({...a,portalUrl:u.target.value}),placeholder:"https://kundenportal.anbieter.de/login"}),s.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg space-y-3",children:[s.jsxs("p",{className:"text-sm text-gray-600",children:[s.jsx("strong",{children:"Auto-Login Felder"})," (optional)",s.jsx("br",{}),"Feldnamen für URL-Parameter beim Auto-Login:"]}),s.jsx(H,{label:"Benutzername-Feldname",value:a.usernameFieldName,onChange:u=>i({...a,usernameFieldName:u.target.value}),placeholder:"z.B. username, email, login"}),s.jsx(H,{label:"Passwort-Feldname",value:a.passwordFieldName,onChange:u=>i({...a,passwordFieldName:u.target.value}),placeholder:"z.B. password, pwd, kennwort"})]}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function HC({isOpen:e,onClose:t,providerId:n,tariff:r}){const a=ge(),[i,l]=j.useState({name:"",isActive:!0});j.useEffect(()=>{e&&l(r?{name:r.name,isActive:r.isActive}:{name:"",isActive:!0})},[e,r]);const o=G({mutationFn:h=>Xa.createTariff(n,h),onSuccess:()=>{a.invalidateQueries({queryKey:["providers"]}),t()},onError:h=>{alert(h.message)}}),c=G({mutationFn:h=>gv.update(r.id,h),onSuccess:()=>{a.invalidateQueries({queryKey:["providers"]}),t()},onError:h=>{alert(h.message)}}),d=h=>{h.preventDefault(),r?c.mutate(i):o.mutate(i)},u=o.isPending||c.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:r?"Tarif bearbeiten":"Neuer Tarif",children:s.jsxs("form",{onSubmit:d,className:"space-y-4",children:[s.jsx(H,{label:"Tarifname *",value:i.name,onChange:h=>l({...i,name:h.target.value}),required:!0,placeholder:"z.B. Comfort Plus, Basic 100"}),r&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:i.isActive,onChange:h=>l({...i,isActive:h.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:u,children:u?"Speichern...":"Speichern"})]})]})})}const Ju={Zap:s.jsx(ph,{className:"w-5 h-5"}),Flame:s.jsx(Cv,{className:"w-5 h-5"}),Wifi:s.jsx(Ea,{className:"w-5 h-5"}),Cable:s.jsx(MS,{className:"w-5 h-5"}),Network:s.jsx(VS,{className:"w-5 h-5"}),Smartphone:s.jsx(hh,{className:"w-5 h-5"}),Tv:s.jsx(Fv,{className:"w-5 h-5"}),Car:s.jsx(kv,{className:"w-5 h-5"}),FileText:s.jsx(Be,{className:"w-5 h-5"})},WC=[{value:"Zap",label:"Blitz (Strom)"},{value:"Flame",label:"Flamme (Gas)"},{value:"Wifi",label:"WLAN (DSL)"},{value:"Cable",label:"Kabel"},{value:"Network",label:"Netzwerk (Glasfaser)"},{value:"Smartphone",label:"Smartphone (Mobilfunk)"},{value:"Tv",label:"TV"},{value:"Car",label:"Auto (KFZ)"},{value:"FileText",label:"Dokument (Sonstige)"}],GC=[{value:"#FFC107",label:"Gelb"},{value:"#FF5722",label:"Orange"},{value:"#2196F3",label:"Blau"},{value:"#9C27B0",label:"Lila"},{value:"#4CAF50",label:"Grün"},{value:"#E91E63",label:"Pink"},{value:"#607D8B",label:"Grau"},{value:"#795548",label:"Braun"},{value:"#00BCD4",label:"Cyan"},{value:"#F44336",label:"Rot"}];function ZC(){const[e,t]=j.useState(!1),[n,r]=j.useState(null),[a,i]=j.useState(!1),{hasPermission:l}=We(),o=ge(),{data:c,isLoading:d}=fe({queryKey:["contract-categories",a],queryFn:()=>cl.getAll(a)}),u=G({mutationFn:cl.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["contract-categories"]})},onError:m=>{alert(m.message)}}),h=m=>{r(m),t(!0)},x=()=>{t(!1),r(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragstypen"}),l("developer:access")&&s.jsxs(T,{onClick:()=>t(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neuer Vertragstyp"]})]}),s.jsxs(X,{children:[s.jsx("div",{className:"mb-4",children:s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:m=>i(m.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),d?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?s.jsx("div",{className:"space-y-2",children:c.data.map(m=>{var f;return s.jsxs("div",{className:"flex items-center p-4 border rounded-lg hover:bg-gray-50",children:[s.jsx("div",{className:"mr-3 text-gray-400",children:s.jsx(OS,{className:"w-5 h-5"})}),s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center mr-4",style:{backgroundColor:m.color||"#E5E7EB",color:"#fff"},children:m.icon&&Ju[m.icon]?Ju[m.icon]:s.jsx(Be,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium",children:m.name}),s.jsx(ve,{variant:m.isActive?"success":"danger",children:m.isActive?"Aktiv":"Inaktiv"}),s.jsxs("span",{className:"text-sm text-gray-500",children:["(",((f=m._count)==null?void 0:f.contracts)||0," Verträge)"]})]}),s.jsxs("div",{className:"text-sm text-gray-500",children:["Code: ",s.jsx("span",{className:"font-mono",children:m.code})]})]}),s.jsxs("div",{className:"flex gap-2 ml-4",children:[l("developer:access")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>h(m),title:"Bearbeiten",children:s.jsx(He,{className:"w-4 h-4"})}),l("developer:access")&&s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertragstyp wirklich löschen?")&&u.mutate(m.id)},title:"Löschen",children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]},m.id)})}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Vertragstypen vorhanden."})]}),s.jsx(JC,{isOpen:e,onClose:x,category:n})]})}function JC({isOpen:e,onClose:t,category:n}){const r=ge(),[a,i]=j.useState({code:"",name:"",icon:"FileText",color:"#607D8B",sortOrder:0,isActive:!0});j.useEffect(()=>{e&&i(n?{code:n.code,name:n.name,icon:n.icon||"FileText",color:n.color||"#607D8B",sortOrder:n.sortOrder,isActive:n.isActive}:{code:"",name:"",icon:"FileText",color:"#607D8B",sortOrder:0,isActive:!0})},[e,n]);const l=G({mutationFn:cl.create,onSuccess:()=>{r.invalidateQueries({queryKey:["contract-categories"]}),t()},onError:u=>{alert(u.message)}}),o=G({mutationFn:u=>cl.update(n.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["contract-categories"]}),t()},onError:u=>{alert(u.message)}}),c=u=>{u.preventDefault(),n?o.mutate(a):l.mutate(a)},d=l.isPending||o.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:n?"Vertragstyp bearbeiten":"Neuer Vertragstyp",children:s.jsxs("form",{onSubmit:c,className:"space-y-4",children:[s.jsx(H,{label:"Code (technisch) *",value:a.code,onChange:u=>i({...a,code:u.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")}),required:!0,placeholder:"z.B. ELECTRICITY, MOBILE_BUSINESS",disabled:!!n}),s.jsx(H,{label:"Anzeigename *",value:a.name,onChange:u=>i({...a,name:u.target.value}),required:!0,placeholder:"z.B. Strom, Mobilfunk Business"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Icon"}),s.jsx("div",{className:"grid grid-cols-4 gap-2",children:WC.map(u=>s.jsxs("button",{type:"button",onClick:()=>i({...a,icon:u.value}),className:`p-3 border rounded-lg flex flex-col items-center gap-1 text-xs ${a.icon===u.value?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,children:[Ju[u.value],s.jsx("span",{className:"truncate w-full text-center",children:u.label.split(" ")[0]})]},u.value))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Farbe"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:GC.map(u=>s.jsx("button",{type:"button",onClick:()=>i({...a,color:u.value}),className:`w-8 h-8 rounded-full border-2 ${a.color===u.value?"border-gray-800 ring-2 ring-offset-2 ring-gray-400":"border-transparent"}`,style:{backgroundColor:u.value},title:u.label},u.value))})]}),s.jsx(H,{label:"Sortierung",type:"number",value:a.sortOrder,onChange:u=>i({...a,sortOrder:parseInt(u.target.value)||0}),placeholder:"0"}),n&&s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:a.isActive,onChange:u=>i({...a,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}const XC=[{value:"0.1",label:"10%"},{value:"0.2",label:"20%"},{value:"0.3",label:"30%"},{value:"0.4",label:"40%"},{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70% (Standard)"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"999",label:"Deaktiviert"}];function YC(){const{settings:e,updateSettings:t}=jv();return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:s.jsx(Vs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ae,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Ansicht"})]})]}),s.jsx(X,{title:"Scroll-Verhalten",children:s.jsx("div",{className:"space-y-6",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Nach-oben-Button"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Ab welcher Scroll-Position der Button unten rechts erscheinen soll"})]}),s.jsx("div",{className:"w-48",children:s.jsx(Ie,{options:XC,value:e.scrollToTopThreshold.toString(),onChange:n=>t({scrollToTopThreshold:parseFloat(n.target.value)})})})]})})})]})}function e4(){const e=ge(),{data:t,isLoading:n}=fe({queryKey:["app-settings"],queryFn:()=>Xr.getAll()}),[r,a]=j.useState(!1);j.useEffect(()=>{t!=null&&t.data&&a(t.data.customerSupportTicketsEnabled==="true")},[t]);const i=G({mutationFn:o=>Xr.update(o),onSuccess:()=>{e.invalidateQueries({queryKey:["app-settings"]}),e.invalidateQueries({queryKey:["app-settings-public"]})}}),l=o=>{a(o),i.mutate({customerSupportTicketsEnabled:o?"true":"false"})};return n?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",className:"text-gray-500 hover:text-gray-700",children:s.jsx(Vs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(uh,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Kundenportal"})]})]}),s.jsxs(X,{title:"Support-Anfragen",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(ul,{className:"w-5 h-5 text-gray-500"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Kunden können Support-Anfragen erstellen"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Wenn aktiviert, können Kunden im Portal Support-Anfragen zu ihren Verträgen erstellen. Diese erscheinen als Aufgaben in der Vertragsdetailansicht."})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:r,onChange:o=>l(o.target.checked),disabled:i.isPending,className:"sr-only peer"}),s.jsx("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),r&&s.jsx("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:s.jsxs("p",{className:"text-sm text-blue-800",children:[s.jsx("strong",{children:"Hinweis:"}),' Kunden sehen diese Anfragen als "Support-Anfragen" in ihrem Portal. Sie können die Anfrage mit einem Titel und einer Beschreibung erstellen. Ihre Mitarbeiter können dann mit Antworten (Unteraufgaben) reagieren.']})})]})]})}function t4(){const e=ge(),{data:t,isLoading:n}=fe({queryKey:["app-settings"],queryFn:()=>Xr.getAll()}),[r,a]=j.useState("14"),[i,l]=j.useState("42"),[o,c]=j.useState("90"),[d,u]=j.useState(!1);j.useEffect(()=>{t!=null&&t.data&&(a(t.data.deadlineCriticalDays||"14"),l(t.data.deadlineWarningDays||"42"),c(t.data.deadlineOkDays||"90"),u(!1))},[t]);const h=G({mutationFn:f=>Xr.update(f),onSuccess:()=>{e.invalidateQueries({queryKey:["app-settings"]}),e.invalidateQueries({queryKey:["contract-cockpit"]}),u(!1)}}),x=()=>{const f=parseInt(r),p=parseInt(i),b=parseInt(o);if(isNaN(f)||isNaN(p)||isNaN(b)){alert("Bitte gültige Zahlen eingeben");return}if(f>=p||p>=b){alert("Die Werte müssen aufsteigend sein: Kritisch < Warnung < OK");return}h.mutate({deadlineCriticalDays:r,deadlineWarningDays:i,deadlineOkDays:o})},m=(f,p)=>{f(p),u(!0)};return n?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",className:"text-gray-500 hover:text-gray-700",children:s.jsx(Vs,{className:"w-5 h-5"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(on,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Fristenschwellen"})]})]}),s.jsxs(X,{title:"Farbkodierung für Fristen",children:[s.jsx("p",{className:"text-gray-600 mb-6",children:"Definiere, ab wann Vertragsfristen als kritisch (rot), Warnung (gelb) oder OK (grün) angezeigt werden sollen. Die Werte geben die Anzahl der Tage bis zur Frist an."}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-red-50 border border-red-200 rounded-lg",children:[s.jsx(kn,{className:"w-8 h-8 text-red-500 flex-shrink-0"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block font-medium text-red-800 mb-1",children:"Kritisch (Rot)"}),s.jsx("p",{className:"text-sm text-red-600 mb-2",children:"Fristen mit weniger als X Tagen werden rot markiert"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(H,{type:"number",min:"1",value:r,onChange:f=>m(a,f.target.value),className:"w-24"}),s.jsx("span",{className:"text-red-700",children:"Tage"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg",children:[s.jsx(hs,{className:"w-8 h-8 text-yellow-500 flex-shrink-0"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block font-medium text-yellow-800 mb-1",children:"Warnung (Gelb)"}),s.jsx("p",{className:"text-sm text-yellow-600 mb-2",children:"Fristen mit weniger als X Tagen werden gelb markiert"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(H,{type:"number",min:"1",value:i,onChange:f=>m(l,f.target.value),className:"w-24"}),s.jsx("span",{className:"text-yellow-700",children:"Tage"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-4 p-4 bg-green-50 border border-green-200 rounded-lg",children:[s.jsx(As,{className:"w-8 h-8 text-green-500 flex-shrink-0"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block font-medium text-green-800 mb-1",children:"OK (Grün)"}),s.jsx("p",{className:"text-sm text-green-600 mb-2",children:"Fristen mit weniger als X Tagen werden grün markiert (darüber nicht angezeigt)"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(H,{type:"number",min:"1",value:o,onChange:f=>m(c,f.target.value),className:"w-24"}),s.jsx("span",{className:"text-green-700",children:"Tage"})]})]})]})]}),s.jsxs("div",{className:"mt-6 pt-4 border-t flex justify-between items-center",children:[s.jsx("p",{className:"text-sm text-gray-500",children:"Beispiel: Bei 14/42/90 Tagen wird eine Frist die in 10 Tagen abläuft rot, eine in 30 Tagen gelb, und eine in 60 Tagen grün markiert."}),s.jsx(T,{onClick:x,disabled:!d||h.isPending,children:h.isPending?"Speichere...":"Speichern"})]})]})]})}const s4=[{value:"PLESK",label:"Plesk"},{value:"CPANEL",label:"cPanel"},{value:"DIRECTADMIN",label:"DirectAdmin"}],Bx=[{value:"SSL",label:"SSL/TLS",description:"Verschlüsselung von Anfang an"},{value:"STARTTLS",label:"STARTTLS",description:"Startet unverschlüsselt, dann Upgrade"},{value:"NONE",label:"Keine",description:"Keine Verschlüsselung"}],bd={name:"",type:"PLESK",apiUrl:"",apiKey:"",username:"",password:"",domain:"stressfrei-wechseln.de",defaultForwardEmail:"",imapEncryption:"SSL",smtpEncryption:"SSL",allowSelfSignedCerts:!1,isActive:!0,isDefault:!1};function n4(){const e=Yt(),t=ge(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState(bd),[c,d]=j.useState(!1),[u,h]=j.useState(null),[x,m]=j.useState(!1),[f,p]=j.useState({}),[b,g]=j.useState(null),{data:y,isLoading:v}=fe({queryKey:["email-provider-configs"],queryFn:()=>yn.getConfigs()}),N=G({mutationFn:k=>yn.createConfig(k),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]}),A()}}),E=G({mutationFn:({id:k,data:K})=>yn.updateConfig(k,K),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]}),A()}}),P=G({mutationFn:k=>yn.deleteConfig(k),onSuccess:()=>{t.invalidateQueries({queryKey:["email-provider-configs"]})}}),I=(y==null?void 0:y.data)||[],w=()=>{o(bd),i(null),d(!1),h(null),r(!0)},S=k=>{o({name:k.name,type:k.type,apiUrl:k.apiUrl,apiKey:k.apiKey||"",username:k.username||"",password:"",domain:k.domain,defaultForwardEmail:k.defaultForwardEmail||"",imapEncryption:k.imapEncryption??"SSL",smtpEncryption:k.smtpEncryption??"SSL",allowSelfSignedCerts:k.allowSelfSignedCerts??!1,isActive:k.isActive,isDefault:k.isDefault}),i(k.id),d(!1),h(null),r(!0)},A=()=>{r(!1),i(null),o(bd),d(!1),h(null)},O=async k=>{var K,B,_;g(k.id),p(Q=>({...Q,[k.id]:null}));try{const Q=await yn.testConnection({id:k.id}),le={success:((K=Q.data)==null?void 0:K.success)||!1,message:(B=Q.data)==null?void 0:B.message,error:(_=Q.data)==null?void 0:_.error};p(de=>({...de,[k.id]:le}))}catch(Q){p(le=>({...le,[k.id]:{success:!1,error:Q instanceof Error?Q.message:"Unbekannter Fehler beim Testen"}}))}finally{g(null)}},R=async()=>{var k,K,B;if(!l.apiUrl||!l.domain){h({success:!1,error:"Bitte geben Sie API-URL und Domain ein."});return}m(!0),h(null);try{const _=await yn.testConnection({testData:{type:l.type,apiUrl:l.apiUrl,apiKey:l.apiKey||void 0,username:l.username||void 0,password:l.password||void 0,domain:l.domain}});h({success:((k=_.data)==null?void 0:k.success)||!1,message:(K=_.data)==null?void 0:K.message,error:(B=_.data)==null?void 0:B.error})}catch(_){h({success:!1,error:_ instanceof Error?_.message:"Unbekannter Fehler beim Verbindungstest"})}finally{m(!1)}},q=k=>{k.preventDefault();const K={name:l.name,type:l.type,apiUrl:l.apiUrl,apiKey:l.apiKey,username:l.username,domain:l.domain,defaultForwardEmail:l.defaultForwardEmail,imapEncryption:l.imapEncryption,smtpEncryption:l.smtpEncryption,allowSelfSignedCerts:l.allowSelfSignedCerts,isActive:l.isActive,isDefault:l.isDefault};l.password&&(K.password=l.password),a?E.mutate({id:a,data:K}):N.mutate(K)},D=(k,K)=>{confirm(`Möchten Sie den Provider "${K}" wirklich löschen?`)&&P.mutate(k)},z=k=>k.error?k.error:k.message?k.message:"Verbindung fehlgeschlagen";return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsxs(T,{variant:"ghost",onClick:()=>e("/settings"),children:[s.jsx(Vs,{className:"w-4 h-4 mr-2"}),"Zurück"]}),s.jsx("h1",{className:"text-2xl font-bold",children:"Email-Provisionierung"})]}),s.jsxs(X,{className:"mb-6",children:[s.jsx("p",{className:"text-gray-600 mb-4",children:'Hier konfigurieren Sie die automatische Erstellung von Stressfrei-Wechseln E-Mail-Adressen. Wenn beim Anlegen einer Stressfrei-Adresse die Option "Bei Provider anlegen" aktiviert ist, wird die E-Mail-Weiterleitung automatisch erstellt.'}),s.jsxs(T,{onClick:w,children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Provider hinzufügen"]})]}),v?s.jsx("div",{className:"text-center py-8",children:"Laden..."}):I.length===0?s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Noch keine Email-Provider konfiguriert."})}):s.jsx("div",{className:"space-y-4",children:I.map(k=>{const K=f[k.id],B=b===k.id;return s.jsx(X,{children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h3",{className:"font-semibold text-lg",children:k.name}),s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-blue-100 text-blue-800",children:k.type}),k.isDefault&&s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-green-100 text-green-800",children:"Standard"}),!k.isActive&&s.jsx("span",{className:"px-2 py-1 text-xs rounded bg-gray-100 text-gray-600",children:"Inaktiv"})]}),s.jsxs("dl",{className:"mt-3 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"API-URL"}),s.jsx("dd",{className:"font-mono text-xs truncate",children:k.apiUrl})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Domain"}),s.jsx("dd",{children:k.domain})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Benutzer"}),s.jsx("dd",{children:k.username||"-"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-gray-500",children:"Standard-Weiterleitung"}),s.jsx("dd",{className:"truncate",children:k.defaultForwardEmail||"-"})]})]}),K&&s.jsx("div",{className:`mt-3 p-3 rounded-lg text-sm ${K.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:K.success?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(xr,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{children:"Verbindung erfolgreich!"})]}):s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(px,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),s.jsx("span",{children:z(K)})]})})]}),s.jsxs("div",{className:"flex gap-2 ml-4",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>O(k),disabled:B,title:"Verbindung testen",children:B?s.jsx("span",{className:"w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin"}):s.jsx(Ea,{className:"w-4 h-4 text-blue-500"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>S(k),children:s.jsx(He,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>D(k.id,k.name),children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})]})},k.id)})}),n&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsx("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto",children:s.jsxs("div",{className:"p-6",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h2",{className:"text-xl font-semibold",children:a?"Provider bearbeiten":"Neuer Provider"}),s.jsx("button",{onClick:A,className:"text-gray-400 hover:text-gray-600",children:s.jsx(qt,{className:"w-5 h-5"})})]}),(N.error||E.error)&&s.jsx("div",{className:"mb-4 p-3 rounded-lg bg-red-50 text-red-800 text-sm",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(qt,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),s.jsx("span",{children:N.error instanceof Error?N.error.message:E.error instanceof Error?E.error.message:"Fehler beim Speichern"})]})}),s.jsxs("form",{onSubmit:q,className:"space-y-4",children:[s.jsx(H,{label:"Name *",value:l.name,onChange:k=>o({...l,name:k.target.value}),placeholder:"z.B. Plesk Hauptserver",required:!0}),s.jsx(Ie,{label:"Provider-Typ *",value:l.type,onChange:k=>o({...l,type:k.target.value}),options:s4}),s.jsx(H,{label:"API-URL *",value:l.apiUrl,onChange:k=>o({...l,apiUrl:k.target.value}),placeholder:"https://server.de:8443",required:!0}),s.jsx(H,{label:"API-Key",value:l.apiKey,onChange:k=>o({...l,apiKey:k.target.value}),placeholder:"Optional - alternativ zu Benutzername/Passwort"}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(H,{label:"Benutzername",value:l.username,onChange:k=>o({...l,username:k.target.value}),placeholder:"admin"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:a?"Neues Passwort (leer = beibehalten)":"Passwort"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:c?"text":"password",value:l.password,onChange:k=>o({...l,password:k.target.value}),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),s.jsx("button",{type:"button",onClick:()=>d(!c),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:c?s.jsx(It,{className:"w-4 h-4"}):s.jsx(Ae,{className:"w-4 h-4"})})]})]})]}),s.jsx(H,{label:"Domain *",value:l.domain,onChange:k=>o({...l,domain:k.target.value}),placeholder:"stressfrei-wechseln.de",required:!0}),s.jsx(H,{label:"Standard-Weiterleitungsadresse",value:l.defaultForwardEmail,onChange:k=>o({...l,defaultForwardEmail:k.target.value}),placeholder:"info@meinefirma.de",type:"email"}),s.jsx("p",{className:"text-xs text-gray-500 -mt-2",children:"Diese E-Mail-Adresse wird zusätzlich zur Kunden-E-Mail als Weiterleitungsziel hinzugefügt."}),s.jsxs("div",{className:"pt-4 border-t",children:[s.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"E-Mail-Verbindungseinstellungen"}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["IMAP Verschlüsselung",s.jsxs("span",{className:"text-gray-400 font-normal ml-1",children:["(Port ",l.imapEncryption==="SSL"?"993":"143",")"]})]}),s.jsx("select",{value:l.imapEncryption,onChange:k=>o({...l,imapEncryption:k.target.value}),className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm",children:Bx.map(k=>s.jsxs("option",{value:k.value,children:[k.label," - ",k.description]},k.value))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["SMTP Verschlüsselung",s.jsxs("span",{className:"text-gray-400 font-normal ml-1",children:["(Port ",l.smtpEncryption==="SSL"?"465":l.smtpEncryption==="STARTTLS"?"587":"25",")"]})]}),s.jsx("select",{value:l.smtpEncryption,onChange:k=>o({...l,smtpEncryption:k.target.value}),className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm",children:Bx.map(k=>s.jsxs("option",{value:k.value,children:[k.label," - ",k.description]},k.value))})]})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:l.allowSelfSignedCerts,onChange:k=>o({...l,allowSelfSignedCerts:k.target.checked}),className:"rounded border-gray-300"}),s.jsx("span",{className:"text-sm",children:"Selbstsignierte Zertifikate erlauben"})]}),s.jsx("p",{className:"text-xs text-gray-500",children:"Aktivieren Sie diese Option für Testumgebungen mit selbstsignierten SSL-Zertifikaten."})]})]}),s.jsxs("div",{className:"flex gap-4",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:l.isActive,onChange:k=>o({...l,isActive:k.target.checked}),className:"rounded border-gray-300"}),s.jsx("span",{className:"text-sm",children:"Aktiv"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:l.isDefault,onChange:k=>o({...l,isDefault:k.target.checked}),className:"rounded border-gray-300"}),s.jsx("span",{className:"text-sm",children:"Als Standard verwenden"})]})]}),s.jsxs("div",{className:"pt-4 border-t",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:R,disabled:x,className:"w-full",children:x?"Teste Verbindung...":s.jsxs(s.Fragment,{children:[s.jsx(Ea,{className:"w-4 h-4 mr-2"}),"Verbindung testen"]})}),u&&s.jsx("div",{className:`mt-2 p-3 rounded-lg text-sm ${u.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:u.success?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(xr,{className:"w-4 h-4 flex-shrink-0"}),s.jsx("span",{children:"Verbindung erfolgreich!"})]}):s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(px,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),s.jsx("span",{children:z(u)})]})})]}),s.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:A,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:N.isPending||E.isPending,children:N.isPending||E.isPending?"Speichern...":"Speichern"})]})]})]})})})]})}function r4(){const[e,t]=j.useState(null),[n,r]=j.useState(null),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState(null),u=j.useRef(null),h=ge(),{logout:x}=We(),{data:m,isLoading:f}=fe({queryKey:["backups"],queryFn:()=>br.list()}),p=(m==null?void 0:m.data)||[],b=G({mutationFn:()=>br.create(),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]})}}),g=G({mutationFn:S=>br.restore(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),t(null)}}),y=G({mutationFn:S=>br.delete(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),r(null)}}),v=G({mutationFn:S=>br.upload(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),d(null),u.current&&(u.current.value="")},onError:S=>{d(S.message||"Upload fehlgeschlagen")}}),N=G({mutationFn:()=>br.factoryReset(),onSuccess:()=>{i(!1),o(""),x()}}),E=S=>{var O;const A=(O=S.target.files)==null?void 0:O[0];if(A){if(!A.name.endsWith(".zip")){d("Nur ZIP-Dateien sind erlaubt");return}d(null),v.mutate(A)}},P=async S=>{const A=localStorage.getItem("token"),O=br.getDownloadUrl(S);try{const R=await fetch(O,{headers:{Authorization:`Bearer ${A}`}});if(!R.ok)throw new Error("Download fehlgeschlagen");const q=await R.blob(),D=window.URL.createObjectURL(q),z=document.createElement("a");z.href=D,z.download=`opencrm-backup-${S}.zip`,document.body.appendChild(z),z.click(),document.body.removeChild(z),window.URL.revokeObjectURL(D)}catch(R){console.error("Download error:",R)}},I=S=>new Date(S).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),w=S=>S<1024?`${S} B`:S<1024*1024?`${(S/1024).toFixed(1)} KB`:`${(S/(1024*1024)).toFixed(1)} MB`;return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-gray-900 flex items-center gap-2",children:[s.jsx(Ic,{className:"w-5 h-5"}),"Datenbank & Zurücksetzen"]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Backups erstellen, wiederherstellen oder auf Werkseinstellungen zurücksetzen."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"file",ref:u,accept:".zip",onChange:E,className:"hidden"}),s.jsx(T,{variant:"secondary",onClick:()=>{var S;return(S=u.current)==null?void 0:S.click()},disabled:v.isPending,children:v.isPending?s.jsxs(s.Fragment,{children:[s.jsx(Sr,{className:"w-4 h-4 mr-2 animate-spin"}),"Hochladen..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Hu,{className:"w-4 h-4 mr-2"}),"Backup hochladen"]})}),s.jsx(T,{onClick:()=>b.mutate(),disabled:b.isPending,children:b.isPending?s.jsxs(s.Fragment,{children:[s.jsx(Sr,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird erstellt..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Ps,{className:"w-4 h-4 mr-2"}),"Neues Backup"]})})]})]}),c&&s.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-red-700",children:c}),s.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-blue-800 mb-2",children:"Hinweise zur Datensicherung"}),s.jsxs("ul",{className:"text-sm text-blue-700 space-y-1 list-disc list-inside",children:[s.jsx("li",{children:"Backups enthalten alle Datenbankdaten und hochgeladene Dokumente"}),s.jsx("li",{children:"Erstellen Sie vor Datenbankmigrationen immer ein Backup"}),s.jsx("li",{children:"Backups können als ZIP heruntergeladen und auf einem anderen System wiederhergestellt werden"}),s.jsx("li",{children:"Bei der Wiederherstellung werden bestehende Daten mit dem Backup-Stand überschrieben"})]})]}),s.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-200",children:s.jsx("h3",{className:"text-sm font-medium text-gray-700",children:"Verfügbare Backups"})}),f?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(Sr,{className:"w-6 h-6 animate-spin text-gray-400"})}):p.length===0?s.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[s.jsx(hx,{className:"w-12 h-12 mb-2 opacity-30"}),s.jsx("p",{children:"Keine Backups vorhanden"}),s.jsx("p",{className:"text-sm mt-1",children:"Erstellen Sie Ihr erstes Backup"})]}):s.jsx("div",{className:"divide-y divide-gray-200",children:p.map(S=>s.jsx("div",{className:"p-4 hover:bg-gray-50",children:s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[s.jsx("span",{className:"font-mono text-sm bg-gray-100 px-2 py-1 rounded",children:S.name}),s.jsxs("span",{className:"text-sm text-gray-500 flex items-center gap-1",children:[s.jsx(on,{className:"w-4 h-4"}),I(S.timestamp)]})]}),s.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-600",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Be,{className:"w-4 h-4"}),S.totalRecords.toLocaleString("de-DE")," Datensätze"]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(hx,{className:"w-4 h-4"}),w(S.sizeBytes)]}),S.hasUploads&&s.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[s.jsx(LS,{className:"w-4 h-4"}),"Dokumente (",w(S.uploadSizeBytes),")"]})]}),s.jsxs("details",{className:"mt-2",children:[s.jsxs("summary",{className:"text-xs text-gray-500 cursor-pointer hover:text-gray-700",children:["Tabellen anzeigen (",S.tables.filter(A=>A.count>0).length," mit Daten)"]}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:S.tables.filter(A=>A.count>0).map(A=>s.jsxs("span",{className:"text-xs bg-gray-100 px-2 py-0.5 rounded",children:[A.table,": ",A.count]},A.table))})]})]}),s.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>P(S.name),title:"Als ZIP herunterladen",children:s.jsx(ES,{className:"w-4 h-4"})}),s.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>t(S.name),disabled:g.isPending,children:[s.jsx(Hu,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),s.jsx(T,{variant:"danger",size:"sm",onClick:()=>r(S.name),disabled:y.isPending,children:s.jsx(Ne,{className:"w-4 h-4"})})]})]})},S.name))})]}),e&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Backup wiederherstellen?"}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Möchten Sie das Backup ",s.jsx("strong",{children:e})," wirklich wiederherstellen?"]}),s.jsxs("p",{className:"text-amber-600 text-sm mb-4 bg-amber-50 p-3 rounded-lg",children:[s.jsx("strong",{children:"Achtung:"})," Bestehende Daten und Dokumente werden mit dem Backup-Stand überschrieben. Dies kann nicht rückgängig gemacht werden."]}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:()=>t(null),disabled:g.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"primary",onClick:()=>g.mutate(e),disabled:g.isPending,children:g.isPending?s.jsxs(s.Fragment,{children:[s.jsx(Sr,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird wiederhergestellt..."]}):"Ja, wiederherstellen"})]})]})}),n&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Backup löschen?"}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Möchten Sie das Backup ",s.jsx("strong",{children:n})," wirklich löschen? Dies kann nicht rückgängig gemacht werden."]}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:()=>r(null),disabled:y.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"danger",onClick:()=>y.mutate(n),disabled:y.isPending,children:y.isPending?"Wird gelöscht...":"Ja, löschen"})]})]})}),s.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-6 mt-8",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:s.jsx(hs,{className:"w-6 h-6 text-red-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-lg font-semibold text-red-800 mb-2",children:"Werkseinstellungen"}),s.jsxs("p",{className:"text-sm text-red-700 mb-4",children:["Setzt das System auf den Ausgangszustand zurück. ",s.jsx("strong",{children:"Alle Daten werden unwiderruflich gelöscht"})," - Kunden, Verträge, Benutzer, Dokumente und Einstellungen. Nur die hier gespeicherten Backups bleiben erhalten."]}),s.jsxs("ul",{className:"text-sm text-red-700 mb-4 list-disc list-inside space-y-1",children:[s.jsx("li",{children:"Alle Kunden und Verträge werden gelöscht"}),s.jsx("li",{children:"Alle Benutzer werden gelöscht"}),s.jsx("li",{children:"Alle hochgeladenen Dokumente werden gelöscht"}),s.jsx("li",{children:"Ein neuer Admin-Benutzer wird erstellt (admin@admin.com / admin)"}),s.jsxs("li",{children:[s.jsx("strong",{children:"Backups bleiben erhalten"})," und können danach wiederhergestellt werden"]})]}),s.jsxs(T,{variant:"danger",onClick:()=>i(!0),children:[s.jsx(DS,{className:"w-4 h-4 mr-2"}),"Werkseinstellungen"]})]})]})}),a&&s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-lg mx-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:s.jsx(hs,{className:"w-6 h-6 text-red-600"})}),s.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Wirklich auf Werkseinstellungen zurücksetzen?"})]}),s.jsxs("p",{className:"text-gray-600 mb-4",children:["Diese Aktion löscht ",s.jsx("strong",{children:"alle Daten unwiderruflich"}),". Es gibt kein Zurück!"]}),s.jsxs("p",{className:"text-sm text-gray-600 mb-4",children:["Geben Sie zur Bestätigung ",s.jsx("strong",{className:"font-mono bg-gray-100 px-1",children:"LÖSCHEN"})," ein:"]}),s.jsx("input",{type:"text",value:l,onChange:S=>o(S.target.value),placeholder:"LÖSCHEN",className:"w-full px-3 py-2 border border-gray-300 rounded-lg mb-4 focus:ring-2 focus:ring-red-500 focus:border-red-500"}),s.jsxs("div",{className:"flex justify-end gap-3",children:[s.jsx(T,{variant:"secondary",onClick:()=>{i(!1),o("")},disabled:N.isPending,children:"Abbrechen"}),s.jsx(T,{variant:"danger",onClick:()=>N.mutate(),disabled:l!=="LÖSCHEN"||N.isPending,children:N.isPending?s.jsxs(s.Fragment,{children:[s.jsx(Sr,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird zurückgesetzt..."]}):"Ja, alles löschen"})]})]})})]})}function a4(){var y;const[e,t]=j.useState(""),[n,r]=j.useState(1),[a,i]=j.useState(!1),[l,o]=j.useState(null),c=ge(),{refreshUser:d}=We(),{data:u,isLoading:h}=fe({queryKey:["users",e,n],queryFn:()=>Li.getAll({search:e||void 0,page:n,limit:20})}),{data:x}=fe({queryKey:["roles"],queryFn:()=>Li.getRoles()}),m=G({mutationFn:Li.delete,onSuccess:()=>{c.invalidateQueries({queryKey:["users"]})},onError:v=>{alert((v==null?void 0:v.message)||"Fehler beim Löschen des Benutzers")}}),f=v=>{var N;return(N=v.roles)==null?void 0:N.some(E=>E.name==="Admin")},p=((y=u==null?void 0:u.data)==null?void 0:y.filter(v=>v.isActive&&f(v)).length)||0,b=v=>{o(v),i(!0)},g=()=>{i(!1),o(null)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.jsx(ke,{to:"/settings",children:s.jsx(T,{variant:"ghost",size:"sm",children:s.jsx(Vs,{className:"w-4 h-4"})})}),s.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Benutzer"}),s.jsxs(T,{onClick:()=>i(!0),children:[s.jsx(_e,{className:"w-4 h-4 mr-2"}),"Neuer Benutzer"]})]}),s.jsx(X,{className:"mb-6",children:s.jsxs("div",{className:"flex gap-4",children:[s.jsx("div",{className:"flex-1",children:s.jsx(H,{placeholder:"Suchen...",value:e,onChange:v=>t(v.target.value)})}),s.jsx(T,{variant:"secondary",children:s.jsx(Tl,{className:"w-4 h-4"})})]})}),s.jsxs("div",{className:"mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[s.jsx(Ml,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-blue-800",children:[s.jsx("strong",{children:"Hinweis:"})," Bei Änderungen an Rollen oder Berechtigungen wird der betroffene Benutzer automatisch ausgeloggt und muss sich erneut anmelden."]})]}),s.jsx(X,{children:h?s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):u!=null&&u.data&&u.data.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b",children:[s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"E-Mail"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Rollen"}),s.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),s.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsx("tbody",{children:u.data.map(v=>{var N;return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[s.jsxs("td",{className:"py-3 px-4",children:[v.firstName," ",v.lastName]}),s.jsx("td",{className:"py-3 px-4",children:v.email}),s.jsx("td",{className:"py-3 px-4",children:s.jsx("div",{className:"flex gap-1 flex-wrap",children:(N=v.roles)==null?void 0:N.filter(E=>E.name!=="Developer").map(E=>s.jsx(ve,{variant:"info",children:E.name},E.id||E.name))})}),s.jsx("td",{className:"py-3 px-4",children:s.jsxs("div",{className:"flex gap-2",children:[s.jsx(ve,{variant:v.isActive?"success":"danger",children:v.isActive?"Aktiv":"Inaktiv"}),v.hasDeveloperAccess&&s.jsxs(ve,{variant:"warning",className:"flex items-center gap-1",children:[s.jsx(Fc,{className:"w-3 h-3"}),"Dev"]})]})}),s.jsx("td",{className:"py-3 px-4 text-right",children:s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>b(v),children:s.jsx(He,{className:"w-4 h-4"})}),(()=>{const E=f(v)&&v.isActive&&p<=1;return s.jsx(T,{variant:"ghost",size:"sm",disabled:E,title:E?"Letzter Administrator kann nicht gelöscht werden":void 0,onClick:()=>{confirm("Benutzer wirklich löschen?")&&m.mutate(v.id)},children:s.jsx(Ne,{className:`w-4 h-4 ${E?"text-gray-300":"text-red-500"}`})})})()]})})]},v.id)})})]})}),u.pagination&&u.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",u.pagination.page," von ",u.pagination.totalPages]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>r(v=>Math.max(1,v-1)),disabled:n===1,children:"Zurück"}),s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>r(v=>v+1),disabled:n>=u.pagination.totalPages,children:"Weiter"})]})]})]}):s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Benutzer gefunden."})}),s.jsx(i4,{isOpen:a,onClose:g,user:l,roles:(x==null?void 0:x.data)||[],onUserUpdated:d})]})}function i4({isOpen:e,onClose:t,user:n,roles:r,onUserUpdated:a}){const i=ge(),[l,o]=j.useState(null),[c,d]=j.useState({email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1});j.useEffect(()=>{var p;e&&(o(null),d(n?{email:n.email,password:"",firstName:n.firstName,lastName:n.lastName,roleIds:((p=n.roles)==null?void 0:p.filter(b=>b.name!=="Developer").map(b=>b.id))||[],isActive:n.isActive??!0,hasDeveloperAccess:n.hasDeveloperAccess??!1}:{email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1}))},[e,n]);const u=G({mutationFn:Li.create,onSuccess:()=>{i.invalidateQueries({queryKey:["users"]}),t()},onError:p=>{o((p==null?void 0:p.message)||"Fehler beim Erstellen des Benutzers")}}),h=G({mutationFn:p=>Li.update(n.id,p),onSuccess:async()=>{i.invalidateQueries({queryKey:["users"]}),await a(),t()},onError:p=>{o((p==null?void 0:p.message)||"Fehler beim Aktualisieren des Benutzers")}}),x=p=>{if(p.preventDefault(),n){const b={email:c.email,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,isActive:c.isActive,hasDeveloperAccess:c.hasDeveloperAccess};c.password&&(b.password=c.password),h.mutate(b)}else u.mutate({email:c.email,password:c.password,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,hasDeveloperAccess:c.hasDeveloperAccess})},m=p=>{d(b=>({...b,roleIds:b.roleIds.includes(p)?b.roleIds.filter(g=>g!==p):[...b.roleIds,p]}))},f=u.isPending||h.isPending;return s.jsx(qe,{isOpen:e,onClose:t,title:n?"Benutzer bearbeiten":"Neuer Benutzer",children:s.jsxs("form",{onSubmit:x,className:"space-y-4",children:[l&&s.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 flex items-start gap-2",children:[s.jsx(hs,{className:"w-5 h-5 text-red-500 flex-shrink-0 mt-0.5"}),s.jsx("p",{className:"text-red-700 text-sm",children:l})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(H,{label:"Vorname *",value:c.firstName,onChange:p=>d({...c,firstName:p.target.value}),required:!0}),s.jsx(H,{label:"Nachname *",value:c.lastName,onChange:p=>d({...c,lastName:p.target.value}),required:!0})]}),s.jsx(H,{label:"E-Mail *",type:"email",value:c.email,onChange:p=>d({...c,email:p.target.value}),required:!0}),s.jsx(H,{label:n?"Neues Passwort (leer = unverändert)":"Passwort *",type:"password",value:c.password,onChange:p=>d({...c,password:p.target.value}),required:!n}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Rollen"}),s.jsxs("div",{className:"space-y-2",children:[r.filter(p=>p.name!=="Developer").map(p=>s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.roleIds.includes(p.id),onChange:()=>m(p.id),className:"rounded"}),s.jsx("span",{children:p.name}),p.description&&s.jsxs("span",{className:"text-sm text-gray-500",children:["(",p.description,")"]})]},p.id)),s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.hasDeveloperAccess,onChange:p=>d({...c,hasDeveloperAccess:p.target.checked}),className:"rounded border-purple-300 text-purple-600 focus:ring-purple-500"}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Fc,{className:"w-4 h-4 text-purple-600"}),"Entwicklerzugriff"]}),s.jsx("span",{className:"text-sm text-gray-500",children:"(Datenbanktools)"})]})]}),n&&s.jsxs("p",{className:"mt-2 text-xs text-amber-600 flex items-center gap-1",children:[s.jsx(hs,{className:"w-3 h-3"}),"Bei Rollenänderung wird der Benutzer automatisch ausgeloggt."]})]}),n&&s.jsx("div",{className:"space-y-3 pt-3 border-t",children:s.jsxs("label",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",checked:c.isActive,onChange:p=>d({...c,isActive:p.target.checked}),className:"rounded"}),"Aktiv"]})}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(T,{type:"button",variant:"secondary",onClick:t,children:"Abbrechen"}),s.jsx(T,{type:"submit",disabled:f,children:f?"Speichern...":"Speichern"})]})]})})}function l4(){const{hasPermission:e,developerMode:t,setDeveloperMode:n}=We(),r=[{to:"/settings/users",icon:GS,title:"Benutzer",description:"Verwalten Sie Benutzerkonten, Rollen und Berechtigungen.",show:e("users:read")},{to:"/settings/platforms",icon:HS,title:"Vertriebsplattformen",description:"Verwalten Sie die Plattformen, über die Verträge abgeschlossen werden.",show:e("platforms:read")},{to:"/settings/cancellation-periods",icon:on,title:"Kündigungsfristen",description:"Konfigurieren Sie die verfügbaren Kündigungsfristen für Verträge.",show:e("platforms:read")},{to:"/settings/contract-durations",icon:Sv,title:"Vertragslaufzeiten",description:"Konfigurieren Sie die verfügbaren Laufzeiten für Verträge.",show:e("platforms:read")},{to:"/settings/providers",icon:PS,title:"Anbieter & Tarife",description:"Verwalten Sie Anbieter und deren Tarife für Verträge.",show:e("providers:read")||e("platforms:read")},{to:"/settings/contract-categories",icon:RS,title:"Vertragstypen",description:"Konfigurieren Sie die verfügbaren Vertragstypen (Strom, Gas, Mobilfunk, etc.).",show:e("platforms:read")}];return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[s.jsx(Tv,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Einstellungen"})]}),s.jsxs("div",{className:"mb-8",children:[s.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"Stammdaten"}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:r.filter(a=>a.show).map(a=>s.jsx(ke,{to:a.to,className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(a.icon,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:[a.title,s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:a.description})]})]})},a.to))})]}),e("settings:update")&&s.jsxs("div",{className:"mb-8",children:[s.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"System"}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsx(ke,{to:"/settings/portal",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(uh,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Kundenportal",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie das Kundenportal und Support-Anfragen."})]})]})}),s.jsx(ke,{to:"/settings/deadlines",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(on,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Fristenschwellen",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie die Farbkodierung für Vertragsfristen im Cockpit."})]})]})}),s.jsx(ke,{to:"/settings/email-providers",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(nn,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Email-Provisionierung",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie die automatische E-Mail-Erstellung für Stressfrei-Wechseln Adressen."})]})]})}),s.jsx(ke,{to:"/settings/database-backup",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(Ic,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Datenbank & Zurücksetzen",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Backups erstellen, wiederherstellen oder auf Werkseinstellungen zurücksetzen."})]})]})})]})]}),s.jsxs("div",{className:"mb-8",children:[s.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"Persönlich"}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:s.jsx(ke,{to:"/settings/view",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:s.jsxs("div",{className:"flex items-start gap-4",children:[s.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:s.jsx(Ae,{className:"w-6 h-6 text-blue-600"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Ansicht",s.jsx(Ft,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Passen Sie die Darstellung der Anwendung an."})]})]})})})]}),e("developer:access")&&s.jsxs(X,{title:"Entwickleroptionen",className:"mb-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Fc,{className:"w-5 h-5 text-gray-500"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Entwicklermodus"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Aktiviert erweiterte Funktionen wie direkten Datenbankzugriff"})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t,onChange:a=>n(a.target.checked),className:"sr-only peer"}),s.jsx("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),t&&s.jsx("div",{className:"mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:s.jsxs("p",{className:"text-sm text-yellow-800",children:[s.jsx("strong",{children:"Warnung:"})," Der Entwicklermodus ermöglicht direkten Zugriff auf die Datenbank. Unsachgemäße Änderungen können zu Datenverlust oder Inkonsistenzen führen."]})})]}),s.jsx(X,{title:"Über",children:s.jsxs("dl",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"Version"}),s.jsx("dd",{children:"1.0.0"})]}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-sm text-gray-500",children:"System"}),s.jsx("dd",{children:"OpenCRM"})]})]})})]})}function o4({onSelectTable:e}){const t=j.useRef(null),[n,r]=j.useState(1),[a,i]=j.useState({x:0,y:0}),[l,o]=j.useState(!1),[c,d]=j.useState({x:0,y:0}),[u,h]=j.useState({}),[x,m]=j.useState(null),{data:f,isLoading:p}=fe({queryKey:["developer-schema"],queryFn:Ci.getSchema}),b=(f==null?void 0:f.data)||[];j.useEffect(()=>{if(b.length>0&&Object.keys(u).length===0){const w=Math.ceil(Math.sqrt(b.length)),S={x:280,y:200},A={};b.forEach((O,R)=>{const q=R%w,D=Math.floor(R/w);A[O.name]={x:50+q*S.x,y:50+D*S.y}}),h(A)}},[b,u]);const g=j.useCallback(w=>{(w.target===w.currentTarget||w.target.tagName==="svg")&&(o(!0),d({x:w.clientX-a.x,y:w.clientY-a.y}))},[a]),y=j.useCallback(w=>{var S;if(l&&!x)i({x:w.clientX-c.x,y:w.clientY-c.y});else if(x){const A=(S=t.current)==null?void 0:S.getBoundingClientRect();A&&h(O=>({...O,[x]:{x:(w.clientX-A.left-a.x)/n-100,y:(w.clientY-A.top-a.y)/n-20}}))}},[l,x,c,a,n]),v=j.useCallback(()=>{o(!1),m(null)},[]),N=w=>{r(S=>Math.min(2,Math.max(.3,S+w)))},E=()=>{r(1),i({x:0,y:0})},P=j.useCallback(()=>{const w=[];return b.forEach(S=>{const A=u[S.name];A&&S.foreignKeys.forEach(O=>{const R=u[O.targetTable];if(!R)return;const q=b.find(z=>z.name===O.targetTable),D=q==null?void 0:q.relations.find(z=>z.targetTable===S.name);w.push({from:{table:S.name,x:A.x+100,y:A.y+60},to:{table:O.targetTable,x:R.x+100,y:R.y+60},type:(D==null?void 0:D.type)||"one",label:O.field})})}),w},[b,u]);if(p)return s.jsx("div",{className:"flex items-center justify-center h-full",children:"Laden..."});const I=P();return s.jsxs("div",{className:"relative h-full w-full bg-gray-50 overflow-hidden",ref:t,children:[s.jsxs("div",{className:"absolute top-4 right-4 z-10 flex gap-2 bg-white rounded-lg shadow-md p-2",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>N(.1),title:"Vergrößern",children:s.jsx(JS,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>N(-.1),title:"Verkleinern",children:s.jsx(XS,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:E,title:"Zurücksetzen",children:s.jsx(US,{className:"w-4 h-4"})}),s.jsxs("div",{className:"text-xs text-gray-500 flex items-center px-2",children:[Math.round(n*100),"%"]})]}),s.jsxs("div",{className:"absolute top-4 left-4 z-10 bg-white rounded-lg shadow-md p-2 text-xs text-gray-500",children:[s.jsx(qS,{className:"w-3 h-3 inline mr-1"}),"Tabellen ziehen zum Verschieben"]}),s.jsx("svg",{className:"w-full h-full cursor-grab",style:{cursor:l?"grabbing":"grab"},onMouseDown:g,onMouseMove:y,onMouseUp:v,onMouseLeave:v,children:s.jsxs("g",{transform:`translate(${a.x}, ${a.y}) scale(${n})`,children:[s.jsxs("defs",{children:[s.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:s.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#6b7280"})}),s.jsx("marker",{id:"many-marker",markerWidth:"12",markerHeight:"12",refX:"6",refY:"6",orient:"auto",children:s.jsx("circle",{cx:"6",cy:"6",r:"3",fill:"#6b7280"})})]}),I.map((w,S)=>{const A=w.to.x-w.from.x,O=w.to.y-w.from.y,R=w.from.x+A/2,q=w.from.y+O/2,D=w.from.x+A*.25,z=w.from.y,k=w.from.x+A*.75,K=w.to.y;return s.jsxs("g",{children:[s.jsx("path",{d:`M ${w.from.x} ${w.from.y} C ${D} ${z}, ${k} ${K}, ${w.to.x} ${w.to.y}`,fill:"none",stroke:"#9ca3af",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),s.jsx("text",{x:R,y:q-8,fontSize:"10",fill:"#6b7280",textAnchor:"middle",className:"select-none",children:w.type==="many"?"1:n":"1:1"})]},S)}),b.map(w=>{const S=u[w.name];if(!S)return null;const A=200,O=32,R=20,q=[...new Set([w.primaryKey,...w.foreignKeys.map(z=>z.field)])],D=O+Math.min(q.length,5)*R+8;return s.jsxs("g",{transform:`translate(${S.x}, ${S.y})`,style:{cursor:"move"},onMouseDown:z=>{z.stopPropagation(),m(w.name)},children:[s.jsx("rect",{x:"3",y:"3",width:A,height:D,rx:"6",fill:"rgba(0,0,0,0.1)"}),s.jsx("rect",{x:"0",y:"0",width:A,height:D,rx:"6",fill:"white",stroke:"#e5e7eb",strokeWidth:"1"}),s.jsx("rect",{x:"0",y:"0",width:A,height:O,rx:"6",fill:"#3b82f6",className:"cursor-pointer",onClick:()=>e==null?void 0:e(w.name)}),s.jsx("rect",{x:"0",y:O-6,width:A,height:"6",fill:"#3b82f6"}),s.jsx("text",{x:A/2,y:"21",fontSize:"13",fontWeight:"bold",fill:"white",textAnchor:"middle",className:"select-none pointer-events-none",children:w.name}),q.slice(0,5).map((z,k)=>{const K=z===w.primaryKey||w.primaryKey.includes(z),B=w.foreignKeys.some(_=>_.field===z);return s.jsx("g",{transform:`translate(8, ${O+4+k*R})`,children:s.jsxs("text",{x:"0",y:"14",fontSize:"11",fill:K?"#dc2626":B?"#2563eb":"#374151",fontFamily:"monospace",className:"select-none",children:[K&&"🔑 ",B&&!K&&"🔗 ",z]})},z)}),q.length>5&&s.jsxs("text",{x:A/2,y:D-4,fontSize:"10",fill:"#9ca3af",textAnchor:"middle",className:"select-none",children:["+",q.length-5," mehr..."]})]},w.name)})]})}),s.jsxs("div",{className:"absolute bottom-4 left-4 bg-white rounded-lg shadow-md p-3 text-xs",children:[s.jsx("div",{className:"font-medium mb-2",children:"Legende"}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-red-600",children:"🔑"}),s.jsx("span",{children:"Primary Key"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-blue-600",children:"🔗"}),s.jsx("span",{children:"Foreign Key"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-6 h-0.5 bg-gray-400"}),s.jsx("span",{children:"Beziehung"})]})]})]})]})}function c4(){var I;const[e,t]=j.useState(null),[n,r]=j.useState(1),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=ge(),{data:d,isLoading:u,error:h}=fe({queryKey:["developer-schema"],queryFn:Ci.getSchema});console.log("Schema data:",d),console.log("Schema error:",h);const{data:x,isLoading:m}=fe({queryKey:["developer-table",e,n],queryFn:()=>Ci.getTableData(e,n),enabled:!!e}),f=G({mutationFn:({tableName:w,id:S,data:A})=>Ci.updateRow(w,S,A),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",e]}),i(null)},onError:w=>{var S,A;alert(((A=(S=w.response)==null?void 0:S.data)==null?void 0:A.error)||"Fehler beim Speichern")}}),p=G({mutationFn:({tableName:w,id:S})=>Ci.deleteRow(w,S),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",e]})},onError:w=>{var S,A;alert(((A=(S=w.response)==null?void 0:S.data)==null?void 0:A.error)||"Fehler beim Löschen")}}),b=(d==null?void 0:d.data)||[],g=b.find(w=>w.name===e),y=(w,S)=>S.primaryKey.includes(",")?S.primaryKey.split(",").map(A=>w[A]).join("-"):String(w[S.primaryKey]),v=w=>w==null?"-":typeof w=="boolean"?w?"Ja":"Nein":typeof w=="object"?w instanceof Date||typeof w=="string"&&w.match(/^\d{4}-\d{2}-\d{2}/)?new Date(w).toLocaleString("de-DE"):JSON.stringify(w):String(w),N=()=>{!a||!e||f.mutate({tableName:e,id:a.id,data:a.data})},E=w=>{e&&confirm("Datensatz wirklich löschen?")&&p.mutate({tableName:e,id:w})};if(u)return s.jsx("div",{className:"text-center py-8",children:"Laden..."});const P=w=>{t(w),r(1),o(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ic,{className:"w-6 h-6"}),s.jsx("h1",{className:"text-2xl font-bold",children:"Datenbankstruktur"})]}),s.jsxs(T,{onClick:()=>o(!0),children:[s.jsx(mx,{className:"w-4 h-4 mr-2"}),"ER-Diagramm"]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6",children:[s.jsx(X,{title:"Tabellen",className:"lg:col-span-1",children:s.jsx("div",{className:"space-y-1 max-h-[600px] overflow-y-auto",children:b.map(w=>s.jsxs("button",{onClick:()=>{t(w.name),r(1)},className:`w-full text-left px-3 py-2 rounded-lg flex items-center gap-2 transition-colors ${e===w.name?"bg-blue-100 text-blue-700":"hover:bg-gray-100"}`,children:[s.jsx(WS,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-mono",children:w.name})]},w.name))})}),s.jsx("div",{className:"lg:col-span-3 space-y-6",children:e&&g?s.jsxs(s.Fragment,{children:[s.jsxs(X,{title:`${e} - Beziehungen`,children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Fremdschlüssel (referenziert)"}),g.foreignKeys.length>0?s.jsx("div",{className:"space-y-1",children:g.foreignKeys.map(w=>s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:"font-mono text-gray-600",children:w.field}),s.jsx(Nv,{className:"w-4 h-4 text-gray-400"}),s.jsx(ve,{variant:"info",className:"cursor-pointer",onClick:()=>{t(w.targetTable),r(1)},children:w.targetTable})]},w.field))}):s.jsx("p",{className:"text-sm text-gray-400",children:"Keine"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Relationen (wird referenziert von)"}),g.relations.length>0?s.jsx("div",{className:"space-y-1",children:g.relations.map(w=>s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:"font-mono text-gray-600",children:w.field}),s.jsx(ve,{variant:w.type==="many"?"warning":"default",children:w.type==="many"?"1:n":"1:1"}),s.jsx(ve,{variant:"info",className:"cursor-pointer",onClick:()=>{t(w.targetTable),r(1)},children:w.targetTable})]},w.field))}):s.jsx("p",{className:"text-sm text-gray-400",children:"Keine"})]})]}),s.jsx("div",{className:"mt-4 pt-4 border-t",children:s.jsxs("div",{className:"flex gap-4 text-sm",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-gray-500",children:"Primary Key:"})," ",s.jsx("span",{className:"font-mono",children:g.primaryKey})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-gray-500",children:"Readonly:"})," ",s.jsx("span",{className:"font-mono text-red-600",children:g.readonlyFields.join(", ")||"-"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-gray-500",children:"Required:"})," ",s.jsx("span",{className:"font-mono text-green-600",children:g.requiredFields.join(", ")||"-"})]})]})})]}),s.jsx(X,{title:`${e} - Daten`,children:m?s.jsx("div",{className:"text-center py-4",children:"Laden..."}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"border-b bg-gray-50",children:[(x==null?void 0:x.data)&&x.data.length>0&&Object.keys(x.data[0]).map(w=>s.jsxs("th",{className:"text-left py-2 px-3 font-medium text-gray-600 whitespace-nowrap",children:[w,g.readonlyFields.includes(w)&&s.jsx("span",{className:"ml-1 text-red-400 text-xs",children:"*"}),g.requiredFields.includes(w)&&s.jsx("span",{className:"ml-1 text-green-400 text-xs",children:"!"})]},w)),s.jsx("th",{className:"text-right py-2 px-3 font-medium text-gray-600",children:"Aktionen"})]})}),s.jsxs("tbody",{children:[(I=x==null?void 0:x.data)==null?void 0:I.map(w=>{const S=y(w,g);return s.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[Object.entries(w).map(([A,O])=>s.jsx("td",{className:"py-2 px-3 font-mono text-xs max-w-[200px] truncate",children:v(O)},A)),s.jsx("td",{className:"py-2 px-3 text-right whitespace-nowrap",children:s.jsxs("div",{className:"flex justify-end gap-1",children:[s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>i({id:S,data:{...w}}),children:s.jsx(He,{className:"w-4 h-4"})}),s.jsx(T,{variant:"ghost",size:"sm",onClick:()=>E(S),children:s.jsx(Ne,{className:"w-4 h-4 text-red-500"})})]})})]},S)}),(!(x!=null&&x.data)||x.data.length===0)&&s.jsx("tr",{children:s.jsx("td",{colSpan:100,className:"py-4 text-center text-gray-500",children:"Keine Daten vorhanden"})})]})]})}),(x==null?void 0:x.pagination)&&x.pagination.totalPages>1&&s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",x.pagination.page," von ",x.pagination.totalPages," (",x.pagination.total," Einträge)"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>r(w=>Math.max(1,w-1)),disabled:n===1,children:s.jsx(FS,{className:"w-4 h-4"})}),s.jsx(T,{variant:"secondary",size:"sm",onClick:()=>r(w=>w+1),disabled:n>=x.pagination.totalPages,children:s.jsx(Ft,{className:"w-4 h-4"})})]})]})]})})]}):s.jsx(X,{children:s.jsx("div",{className:"text-center py-8 text-gray-500",children:"Wähle eine Tabelle aus der Liste aus"})})})]}),s.jsx(qe,{isOpen:!!a,onClose:()=>i(null),title:`${e} bearbeiten`,children:a&&g&&s.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-y-auto",children:[Object.entries(a.data).map(([w,S])=>{const A=g.readonlyFields.includes(w),O=g.requiredFields.includes(w);return s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[w,A&&s.jsx("span",{className:"ml-1 text-red-400",children:"(readonly)"}),O&&s.jsx("span",{className:"ml-1 text-green-600",children:"*"})]}),A?s.jsx("div",{className:"px-3 py-2 bg-gray-100 rounded-lg font-mono text-sm",children:v(S)}):typeof S=="boolean"?s.jsxs("select",{value:String(a.data[w]),onChange:R=>i({...a,data:{...a.data,[w]:R.target.value==="true"}}),className:"w-full px-3 py-2 border rounded-lg",children:[s.jsx("option",{value:"true",children:"Ja"}),s.jsx("option",{value:"false",children:"Nein"})]}):s.jsx("input",{type:typeof S=="number"?"number":"text",value:a.data[w]??"",onChange:R=>i({...a,data:{...a.data,[w]:typeof S=="number"?R.target.value?Number(R.target.value):null:R.target.value||null}}),className:"w-full px-3 py-2 border rounded-lg font-mono text-sm",disabled:A})]},w)}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[s.jsxs(T,{variant:"secondary",onClick:()=>i(null),children:[s.jsx(qt,{className:"w-4 h-4 mr-2"}),"Abbrechen"]}),s.jsxs(T,{onClick:N,disabled:f.isPending,children:[s.jsx(Mv,{className:"w-4 h-4 mr-2"}),f.isPending?"Speichern...":"Speichern"]})]})]})}),l&&s.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[s.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>o(!1)}),s.jsxs("div",{className:"relative bg-white rounded-xl shadow-2xl w-[90vw] h-[85vh] flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(mx,{className:"w-5 h-5 text-blue-600"}),s.jsx("h2",{className:"text-lg font-semibold",children:"ER-Diagramm - Datenbankbeziehungen"})]}),s.jsx("button",{onClick:()=>o(!1),className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:s.jsx(qt,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(o4,{onSelectTable:P})})]})]})]})}function d4({children:e}){const{isAuthenticated:t,isLoading:n}=We();return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):t?s.jsx(s.Fragment,{children:e}):s.jsx(va,{to:"/login",replace:!0})}function u4({children:e}){const{hasPermission:t,developerMode:n}=We();return!t("developer:access")||!n?s.jsx(va,{to:"/",replace:!0}):s.jsx(s.Fragment,{children:e})}function m4(){const{isAuthenticated:e,isLoading:t}=We();return t?s.jsx("div",{className:"min-h-screen flex items-center justify-center",children:s.jsx("div",{className:"text-gray-500",children:"Laden..."})}):s.jsxs(s.Fragment,{children:[s.jsx(wS,{}),s.jsxs(hw,{children:[s.jsx(ze,{path:"/login",element:e?s.jsx(va,{to:"/",replace:!0}):s.jsx(sk,{})}),s.jsxs(ze,{path:"/",element:s.jsx(d4,{children:s.jsx(tk,{})}),children:[s.jsx(ze,{index:!0,element:s.jsx(nk,{})}),s.jsx(ze,{path:"customers",element:s.jsx(ak,{})}),s.jsx(ze,{path:"customers/new",element:s.jsx(Ix,{})}),s.jsx(ze,{path:"customers/:id",element:s.jsx(hk,{})}),s.jsx(ze,{path:"customers/:id/edit",element:s.jsx(Ix,{})}),s.jsx(ze,{path:"contracts",element:s.jsx(Jk,{})}),s.jsx(ze,{path:"contracts/cockpit",element:s.jsx(TC,{})}),s.jsx(ze,{path:"contracts/new",element:s.jsx(_x,{})}),s.jsx(ze,{path:"contracts/:id",element:s.jsx(NC,{})}),s.jsx(ze,{path:"contracts/:id/edit",element:s.jsx(_x,{})}),s.jsx(ze,{path:"tasks",element:s.jsx(IC,{})}),s.jsx(ze,{path:"settings",element:s.jsx(l4,{})}),s.jsx(ze,{path:"settings/users",element:s.jsx(a4,{})}),s.jsx(ze,{path:"settings/platforms",element:s.jsx(zC,{})}),s.jsx(ze,{path:"settings/cancellation-periods",element:s.jsx(_C,{})}),s.jsx(ze,{path:"settings/contract-durations",element:s.jsx(BC,{})}),s.jsx(ze,{path:"settings/providers",element:s.jsx(qC,{})}),s.jsx(ze,{path:"settings/contract-categories",element:s.jsx(ZC,{})}),s.jsx(ze,{path:"settings/view",element:s.jsx(YC,{})}),s.jsx(ze,{path:"settings/portal",element:s.jsx(e4,{})}),s.jsx(ze,{path:"settings/deadlines",element:s.jsx(t4,{})}),s.jsx(ze,{path:"settings/email-providers",element:s.jsx(n4,{})}),s.jsx(ze,{path:"settings/database-backup",element:s.jsx(r4,{})}),s.jsx(ze,{path:"users",element:s.jsx(va,{to:"/settings/users",replace:!0})}),s.jsx(ze,{path:"platforms",element:s.jsx(va,{to:"/settings/platforms",replace:!0})}),s.jsx(ze,{path:"developer/database",element:s.jsx(u4,{children:s.jsx(c4,{})})})]}),s.jsx(ze,{path:"*",element:s.jsx(va,{to:"/",replace:!0})})]})]})}const h4=new Xw({defaultOptions:{queries:{retry:1,staleTime:0,gcTime:0,refetchOnMount:"always"}}});Nd.createRoot(document.getElementById("root")).render(s.jsx(Tt.StrictMode,{children:s.jsx(Yw,{client:h4,children:s.jsx(Nw,{children:s.jsx(NS,{children:s.jsxs(bS,{children:[s.jsx(m4,{}),s.jsx(V1,{position:"top-right",toastOptions:{duration:4e3,style:{background:"#363636",color:"#fff"},success:{iconTheme:{primary:"#10b981",secondary:"#fff"}},error:{iconTheme:{primary:"#ef4444",secondary:"#fff"}}}})]})})})})})); diff --git a/frontend/dist/assets/index-BLUL0czD.js b/frontend/dist/assets/index-BLUL0czD.js new file mode 100644 index 00000000..f8f72524 --- /dev/null +++ b/frontend/dist/assets/index-BLUL0czD.js @@ -0,0 +1,977 @@ +var Mv=t=>{throw TypeError(t)};var em=(t,e,n)=>e.has(t)||Mv("Cannot "+n);var P=(t,e,n)=>(em(t,e,"read from private field"),n?n.call(t):e.get(t)),ge=(t,e,n)=>e.has(t)?Mv("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),re=(t,e,n,s)=>(em(t,e,"write to private field"),s?s.call(t,n):e.set(t,n),n),Ce=(t,e,n)=>(em(t,e,"access private method"),n);var Dd=(t,e,n,s)=>({set _(r){re(t,e,r,n)},get _(){return P(t,e,s)}});function T4(t,e){for(var n=0;ns[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function n(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function s(r){if(r.ep)return;r.ep=!0;const a=n(r);fetch(r.href,a)}})();function UN(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qN={exports:{}},af={},HN={exports:{}},Le={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var cd=Symbol.for("react.element"),P4=Symbol.for("react.portal"),I4=Symbol.for("react.fragment"),R4=Symbol.for("react.strict_mode"),O4=Symbol.for("react.profiler"),L4=Symbol.for("react.provider"),F4=Symbol.for("react.context"),z4=Symbol.for("react.forward_ref"),$4=Symbol.for("react.suspense"),B4=Symbol.for("react.memo"),_4=Symbol.for("react.lazy"),Tv=Symbol.iterator;function V4(t){return t===null||typeof t!="object"?null:(t=Tv&&t[Tv]||t["@@iterator"],typeof t=="function"?t:null)}var WN={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},QN=Object.assign,GN={};function uo(t,e,n){this.props=t,this.context=e,this.refs=GN,this.updater=n||WN}uo.prototype.isReactComponent={};uo.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};uo.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function JN(){}JN.prototype=uo.prototype;function kx(t,e,n){this.props=t,this.context=e,this.refs=GN,this.updater=n||WN}var Sx=kx.prototype=new JN;Sx.constructor=kx;QN(Sx,uo.prototype);Sx.isPureReactComponent=!0;var Pv=Array.isArray,ZN=Object.prototype.hasOwnProperty,Cx={current:null},YN={key:!0,ref:!0,__self:!0,__source:!0};function XN(t,e,n){var s,r={},a=null,l=null;if(e!=null)for(s in e.ref!==void 0&&(l=e.ref),e.key!==void 0&&(a=""+e.key),e)ZN.call(e,s)&&!YN.hasOwnProperty(s)&&(r[s]=e[s]);var o=arguments.length-2;if(o===1)r.children=n;else if(1>>1,he=K[ce];if(0>>1;cer(mt,W))Ar(pt,mt)?(K[ce]=pt,K[A]=W,ce=A):(K[ce]=mt,K[et]=W,ce=et);else if(Ar(pt,W))K[ce]=pt,K[A]=W,ce=A;else break e}}return B}function r(K,B){var W=K.sortIndex-B.sortIndex;return W!==0?W:K.id-B.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;t.unstable_now=function(){return a.now()}}else{var l=Date,o=l.now();t.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,m=3,f=!1,p=!1,g=!1,x=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function b(K){for(var B=n(d);B!==null;){if(B.callback===null)s(d);else if(B.startTime<=K)s(d),B.sortIndex=B.expirationTime,e(c,B);else break;B=n(d)}}function j(K){if(g=!1,b(K),!p)if(n(c)!==null)p=!0,C(k);else{var B=n(d);B!==null&&_(j,B.startTime-K)}}function k(K,B){p=!1,g&&(g=!1,y(w),w=-1),f=!0;var W=m;try{for(b(B),h=n(c);h!==null&&(!(h.expirationTime>B)||K&&!F());){var ce=h.callback;if(typeof ce=="function"){h.callback=null,m=h.priorityLevel;var he=ce(h.expirationTime<=B);B=t.unstable_now(),typeof he=="function"?h.callback=he:h===n(c)&&s(c),b(B)}else s(c);h=n(c)}if(h!==null)var Je=!0;else{var et=n(d);et!==null&&_(j,et.startTime-B),Je=!1}return Je}finally{h=null,m=W,f=!1}}var E=!1,T=null,w=-1,S=5,M=-1;function F(){return!(t.unstable_now()-MK||125ce?(K.sortIndex=W,e(d,K),n(c)===null&&K===n(d)&&(g?(y(w),w=-1):g=!0,_(j,W-ce))):(K.sortIndex=he,e(c,K),p||f||(p=!0,C(k))),K},t.unstable_shouldYield=F,t.unstable_wrapCallback=function(K){var B=m;return function(){var W=m;m=B;try{return K.apply(this,arguments)}finally{m=W}}}})(rw);sw.exports=rw;var eA=sw.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var tA=N,ls=eA;function ne(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),gp=Object.prototype.hasOwnProperty,nA=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Rv={},Ov={};function sA(t){return gp.call(Ov,t)?!0:gp.call(Rv,t)?!1:nA.test(t)?Ov[t]=!0:(Rv[t]=!0,!1)}function rA(t,e,n,s){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return s?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function iA(t,e,n,s){if(e===null||typeof e>"u"||rA(t,e,n,s))return!0;if(s)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Rn(t,e,n,s,r,a,l){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=s,this.attributeNamespace=r,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=a,this.removeEmptyString=l}var un={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){un[t]=new Rn(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];un[e]=new Rn(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){un[t]=new Rn(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){un[t]=new Rn(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){un[t]=new Rn(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){un[t]=new Rn(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){un[t]=new Rn(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){un[t]=new Rn(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){un[t]=new Rn(t,5,!1,t.toLowerCase(),null,!1,!1)});var Ax=/[\-:]([a-z])/g;function Dx(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(Ax,Dx);un[e]=new Rn(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(Ax,Dx);un[e]=new Rn(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(Ax,Dx);un[e]=new Rn(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){un[t]=new Rn(t,1,!1,t.toLowerCase(),null,!1,!1)});un.xlinkHref=new Rn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){un[t]=new Rn(t,1,!1,t.toLowerCase(),null,!0,!0)});function Mx(t,e,n,s){var r=un.hasOwnProperty(e)?un[e]:null;(r!==null?r.type!==0:s||!(2o||r[l]!==a[o]){var c=` +`+r[l].replace(" at new "," at ");return t.displayName&&c.includes("")&&(c=c.replace("",t.displayName)),c}while(1<=l&&0<=o);break}}}finally{sm=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?Fo(t):""}function aA(t){switch(t.tag){case 5:return Fo(t.type);case 16:return Fo("Lazy");case 13:return Fo("Suspense");case 19:return Fo("SuspenseList");case 0:case 2:case 15:return t=rm(t.type,!1),t;case 11:return t=rm(t.type.render,!1),t;case 1:return t=rm(t.type,!0),t;default:return""}}function bp(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case cl:return"Fragment";case ol:return"Portal";case xp:return"Profiler";case Tx:return"StrictMode";case yp:return"Suspense";case vp:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case lw:return(t.displayName||"Context")+".Consumer";case aw:return(t._context.displayName||"Context")+".Provider";case Px:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Ix:return e=t.displayName||null,e!==null?e:bp(t.type)||"Memo";case Yr:e=t._payload,t=t._init;try{return bp(t(e))}catch{}}return null}function lA(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return bp(e);case 8:return e===Tx?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function Bi(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function cw(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function oA(t){var e=cw(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),s=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var r=n.get,a=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return r.call(this)},set:function(l){s=""+l,a.call(this,l)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return s},setValue:function(l){s=""+l},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Pd(t){t._valueTracker||(t._valueTracker=oA(t))}function dw(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),s="";return t&&(s=cw(t)?t.checked?"true":"false":t.value),t=s,t!==n?(e.setValue(t),!0):!1}function Iu(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function jp(t,e){var n=e.checked;return jt({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function Fv(t,e){var n=e.defaultValue==null?"":e.defaultValue,s=e.checked!=null?e.checked:e.defaultChecked;n=Bi(e.value!=null?e.value:n),t._wrapperState={initialChecked:s,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function uw(t,e){e=e.checked,e!=null&&Mx(t,"checked",e,!1)}function Np(t,e){uw(t,e);var n=Bi(e.value),s=e.type;if(n!=null)s==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(s==="submit"||s==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?wp(t,e.type,n):e.hasOwnProperty("defaultValue")&&wp(t,e.type,Bi(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function zv(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var s=e.type;if(!(s!=="submit"&&s!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function wp(t,e,n){(e!=="number"||Iu(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var zo=Array.isArray;function Nl(t,e,n,s){if(t=t.options,e){e={};for(var r=0;r"+e.valueOf().toString()+"",e=Id.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function xc(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var Qo={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},cA=["Webkit","ms","Moz","O"];Object.keys(Qo).forEach(function(t){cA.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),Qo[e]=Qo[t]})});function pw(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||Qo.hasOwnProperty(t)&&Qo[t]?(""+e).trim():e+"px"}function gw(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var s=n.indexOf("--")===0,r=pw(n,e[n],s);n==="float"&&(n="cssFloat"),s?t.setProperty(n,r):t[n]=r}}var dA=jt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Cp(t,e){if(e){if(dA[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(ne(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(ne(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(ne(61))}if(e.style!=null&&typeof e.style!="object")throw Error(ne(62))}}function Ep(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ap=null;function Rx(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var Dp=null,wl=null,kl=null;function _v(t){if(t=hd(t)){if(typeof Dp!="function")throw Error(ne(280));var e=t.stateNode;e&&(e=uf(e),Dp(t.stateNode,t.type,e))}}function xw(t){wl?kl?kl.push(t):kl=[t]:wl=t}function yw(){if(wl){var t=wl,e=kl;if(kl=wl=null,_v(t),e)for(t=0;t>>=0,t===0?32:31-(jA(t)/NA|0)|0}var Rd=64,Od=4194304;function $o(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function Fu(t,e){var n=t.pendingLanes;if(n===0)return 0;var s=0,r=t.suspendedLanes,a=t.pingedLanes,l=n&268435455;if(l!==0){var o=l&~r;o!==0?s=$o(o):(a&=l,a!==0&&(s=$o(a)))}else l=n&~r,l!==0?s=$o(l):a!==0&&(s=$o(a));if(s===0)return 0;if(e!==0&&e!==s&&!(e&r)&&(r=s&-s,a=e&-e,r>=a||r===16&&(a&4194240)!==0))return e;if(s&4&&(s|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=s;0n;n++)e.push(t);return e}function dd(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-$s(e),t[e]=n}function CA(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var s=t.eventTimes;for(t=t.expirationTimes;0=Jo),Jv=" ",Zv=!1;function zw(t,e){switch(t){case"keyup":return eD.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function $w(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var dl=!1;function nD(t,e){switch(t){case"compositionend":return $w(e);case"keypress":return e.which!==32?null:(Zv=!0,Jv);case"textInput":return t=e.data,t===Jv&&Zv?null:t;default:return null}}function sD(t,e){if(dl)return t==="compositionend"||!Vx&&zw(t,e)?(t=Lw(),fu=$x=bi=null,dl=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:n,offset:e-t};t=s}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=tb(n)}}function Kw(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Kw(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Uw(){for(var t=window,e=Iu();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=Iu(t.document)}return e}function Kx(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function hD(t){var e=Uw(),n=t.focusedElem,s=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&Kw(n.ownerDocument.documentElement,n)){if(s!==null&&Kx(n)){if(e=s.start,t=s.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var r=n.textContent.length,a=Math.min(s.start,r);s=s.end===void 0?a:Math.min(s.end,r),!t.extend&&a>s&&(r=s,s=a,a=r),r=nb(n,a);var l=nb(n,s);r&&l&&(t.rangeCount!==1||t.anchorNode!==r.node||t.anchorOffset!==r.offset||t.focusNode!==l.node||t.focusOffset!==l.offset)&&(e=e.createRange(),e.setStart(r.node,r.offset),t.removeAllRanges(),a>s?(t.addRange(e),t.extend(l.node,l.offset)):(e.setEnd(l.node,l.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ul=null,Op=null,Yo=null,Lp=!1;function sb(t,e,n){var s=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Lp||ul==null||ul!==Iu(s)||(s=ul,"selectionStart"in s&&Kx(s)?s={start:s.selectionStart,end:s.selectionEnd}:(s=(s.ownerDocument&&s.ownerDocument.defaultView||window).getSelection(),s={anchorNode:s.anchorNode,anchorOffset:s.anchorOffset,focusNode:s.focusNode,focusOffset:s.focusOffset}),Yo&&wc(Yo,s)||(Yo=s,s=Bu(Op,"onSelect"),0ml||(t.current=Vp[ml],Vp[ml]=null,ml--)}function st(t,e){ml++,Vp[ml]=t.current,t.current=e}var _i={},bn=qi(_i),Hn=qi(!1),Pa=_i;function Wl(t,e){var n=t.type.contextTypes;if(!n)return _i;var s=t.stateNode;if(s&&s.__reactInternalMemoizedUnmaskedChildContext===e)return s.__reactInternalMemoizedMaskedChildContext;var r={},a;for(a in n)r[a]=e[a];return s&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=r),r}function Wn(t){return t=t.childContextTypes,t!=null}function Vu(){ot(Hn),ot(bn)}function db(t,e,n){if(bn.current!==_i)throw Error(ne(168));st(bn,e),st(Hn,n)}function Xw(t,e,n){var s=t.stateNode;if(e=e.childContextTypes,typeof s.getChildContext!="function")return n;s=s.getChildContext();for(var r in s)if(!(r in e))throw Error(ne(108,lA(t)||"Unknown",r));return jt({},n,s)}function Ku(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||_i,Pa=bn.current,st(bn,t),st(Hn,Hn.current),!0}function ub(t,e,n){var s=t.stateNode;if(!s)throw Error(ne(169));n?(t=Xw(t,e,Pa),s.__reactInternalMemoizedMergedChildContext=t,ot(Hn),ot(bn),st(bn,t)):ot(Hn),st(Hn,n)}var Nr=null,hf=!1,ym=!1;function ek(t){Nr===null?Nr=[t]:Nr.push(t)}function kD(t){hf=!0,ek(t)}function Hi(){if(!ym&&Nr!==null){ym=!0;var t=0,e=Ye;try{var n=Nr;for(Ye=1;t>=l,r-=l,Ar=1<<32-$s(e)+r|n<w?(S=T,T=null):S=T.sibling;var M=m(y,T,b[w],j);if(M===null){T===null&&(T=S);break}t&&T&&M.alternate===null&&e(y,T),v=a(M,v,w),E===null?k=M:E.sibling=M,E=M,T=S}if(w===b.length)return n(y,T),ft&&Xi(y,w),k;if(T===null){for(;ww?(S=T,T=null):S=T.sibling;var F=m(y,T,M.value,j);if(F===null){T===null&&(T=S);break}t&&T&&F.alternate===null&&e(y,T),v=a(F,v,w),E===null?k=F:E.sibling=F,E=F,T=S}if(M.done)return n(y,T),ft&&Xi(y,w),k;if(T===null){for(;!M.done;w++,M=b.next())M=h(y,M.value,j),M!==null&&(v=a(M,v,w),E===null?k=M:E.sibling=M,E=M);return ft&&Xi(y,w),k}for(T=s(y,T);!M.done;w++,M=b.next())M=f(T,y,w,M.value,j),M!==null&&(t&&M.alternate!==null&&T.delete(M.key===null?w:M.key),v=a(M,v,w),E===null?k=M:E.sibling=M,E=M);return t&&T.forEach(function(R){return e(y,R)}),ft&&Xi(y,w),k}function x(y,v,b,j){if(typeof b=="object"&&b!==null&&b.type===cl&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case Td:e:{for(var k=b.key,E=v;E!==null;){if(E.key===k){if(k=b.type,k===cl){if(E.tag===7){n(y,E.sibling),v=r(E,b.props.children),v.return=y,y=v;break e}}else if(E.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===Yr&&mb(k)===E.type){n(y,E.sibling),v=r(E,b.props),v.ref=Do(y,E,b),v.return=y,y=v;break e}n(y,E);break}else e(y,E);E=E.sibling}b.type===cl?(v=wa(b.props.children,y.mode,j,b.key),v.return=y,y=v):(j=ju(b.type,b.key,b.props,null,y.mode,j),j.ref=Do(y,v,b),j.return=y,y=j)}return l(y);case ol:e:{for(E=b.key;v!==null;){if(v.key===E)if(v.tag===4&&v.stateNode.containerInfo===b.containerInfo&&v.stateNode.implementation===b.implementation){n(y,v.sibling),v=r(v,b.children||[]),v.return=y,y=v;break e}else{n(y,v);break}else e(y,v);v=v.sibling}v=Cm(b,y.mode,j),v.return=y,y=v}return l(y);case Yr:return E=b._init,x(y,v,E(b._payload),j)}if(zo(b))return p(y,v,b,j);if(ko(b))return g(y,v,b,j);Vd(y,b)}return typeof b=="string"&&b!==""||typeof b=="number"?(b=""+b,v!==null&&v.tag===6?(n(y,v.sibling),v=r(v,b),v.return=y,y=v):(n(y,v),v=Sm(b,y.mode,j),v.return=y,y=v),l(y)):n(y,v)}return x}var Gl=rk(!0),ik=rk(!1),Hu=qi(null),Wu=null,xl=null,Wx=null;function Qx(){Wx=xl=Wu=null}function Gx(t){var e=Hu.current;ot(Hu),t._currentValue=e}function qp(t,e,n){for(;t!==null;){var s=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,s!==null&&(s.childLanes|=e)):s!==null&&(s.childLanes&e)!==e&&(s.childLanes|=e),t===n)break;t=t.return}}function Cl(t,e){Wu=t,Wx=xl=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Kn=!0),t.firstContext=null)}function Cs(t){var e=t._currentValue;if(Wx!==t)if(t={context:t,memoizedValue:e,next:null},xl===null){if(Wu===null)throw Error(ne(308));xl=t,Wu.dependencies={lanes:0,firstContext:t}}else xl=xl.next=t;return e}var sa=null;function Jx(t){sa===null?sa=[t]:sa.push(t)}function ak(t,e,n,s){var r=e.interleaved;return r===null?(n.next=n,Jx(e)):(n.next=r.next,r.next=n),e.interleaved=n,$r(t,s)}function $r(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var Xr=!1;function Zx(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function lk(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Ir(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Mi(t,e,n){var s=t.updateQueue;if(s===null)return null;if(s=s.shared,Ve&2){var r=s.pending;return r===null?e.next=e:(e.next=r.next,r.next=e),s.pending=e,$r(t,n)}return r=s.interleaved,r===null?(e.next=e,Jx(s)):(e.next=r.next,r.next=e),s.interleaved=e,$r(t,n)}function pu(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var s=e.lanes;s&=t.pendingLanes,n|=s,e.lanes=n,Lx(t,n)}}function pb(t,e){var n=t.updateQueue,s=t.alternate;if(s!==null&&(s=s.updateQueue,n===s)){var r=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};a===null?r=a=l:a=a.next=l,n=n.next}while(n!==null);a===null?r=a=e:a=a.next=e}else r=a=e;n={baseState:s.baseState,firstBaseUpdate:r,lastBaseUpdate:a,shared:s.shared,effects:s.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function Qu(t,e,n,s){var r=t.updateQueue;Xr=!1;var a=r.firstBaseUpdate,l=r.lastBaseUpdate,o=r.shared.pending;if(o!==null){r.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?a=d:l.next=d,l=c;var u=t.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(a!==null){var h=r.baseState;l=0,u=d=c=null,o=a;do{var m=o.lane,f=o.eventTime;if((s&m)===m){u!==null&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var p=t,g=o;switch(m=e,f=n,g.tag){case 1:if(p=g.payload,typeof p=="function"){h=p.call(f,h,m);break e}h=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=g.payload,m=typeof p=="function"?p.call(f,h,m):p,m==null)break e;h=jt({},h,m);break e;case 2:Xr=!0}}o.callback!==null&&o.lane!==0&&(t.flags|=64,m=r.effects,m===null?r.effects=[o]:m.push(o))}else f={eventTime:f,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=f,c=h):u=u.next=f,l|=m;if(o=o.next,o===null){if(o=r.shared.pending,o===null)break;m=o,o=m.next,m.next=null,r.lastBaseUpdate=m,r.shared.pending=null}}while(!0);if(u===null&&(c=h),r.baseState=c,r.firstBaseUpdate=d,r.lastBaseUpdate=u,e=r.shared.interleaved,e!==null){r=e;do l|=r.lane,r=r.next;while(r!==e)}else a===null&&(r.shared.lanes=0);Oa|=l,t.lanes=l,t.memoizedState=h}}function gb(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;en?n:4,t(!0);var s=bm.transition;bm.transition={};try{t(!1),e()}finally{Ye=n,bm.transition=s}}function kk(){return Es().memoizedState}function AD(t,e,n){var s=Pi(t);if(n={lane:s,action:n,hasEagerState:!1,eagerState:null,next:null},Sk(t))Ck(e,n);else if(n=ak(t,e,n,s),n!==null){var r=Dn();Bs(n,t,s,r),Ek(n,e,s)}}function DD(t,e,n){var s=Pi(t),r={lane:s,action:n,hasEagerState:!1,eagerState:null,next:null};if(Sk(t))Ck(e,r);else{var a=t.alternate;if(t.lanes===0&&(a===null||a.lanes===0)&&(a=e.lastRenderedReducer,a!==null))try{var l=e.lastRenderedState,o=a(l,n);if(r.hasEagerState=!0,r.eagerState=o,Vs(o,l)){var c=e.interleaved;c===null?(r.next=r,Jx(e)):(r.next=c.next,c.next=r),e.interleaved=r;return}}catch{}finally{}n=ak(t,e,r,s),n!==null&&(r=Dn(),Bs(n,t,s,r),Ek(n,e,s))}}function Sk(t){var e=t.alternate;return t===vt||e!==null&&e===vt}function Ck(t,e){Xo=Ju=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function Ek(t,e,n){if(n&4194240){var s=e.lanes;s&=t.pendingLanes,n|=s,e.lanes=n,Lx(t,n)}}var Zu={readContext:Cs,useCallback:mn,useContext:mn,useEffect:mn,useImperativeHandle:mn,useInsertionEffect:mn,useLayoutEffect:mn,useMemo:mn,useReducer:mn,useRef:mn,useState:mn,useDebugValue:mn,useDeferredValue:mn,useTransition:mn,useMutableSource:mn,useSyncExternalStore:mn,useId:mn,unstable_isNewReconciler:!1},MD={readContext:Cs,useCallback:function(t,e){return Qs().memoizedState=[t,e===void 0?null:e],t},useContext:Cs,useEffect:yb,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,xu(4194308,4,vk.bind(null,e,t),n)},useLayoutEffect:function(t,e){return xu(4194308,4,t,e)},useInsertionEffect:function(t,e){return xu(4,2,t,e)},useMemo:function(t,e){var n=Qs();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var s=Qs();return e=n!==void 0?n(e):e,s.memoizedState=s.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},s.queue=t,t=t.dispatch=AD.bind(null,vt,t),[s.memoizedState,t]},useRef:function(t){var e=Qs();return t={current:t},e.memoizedState=t},useState:xb,useDebugValue:iy,useDeferredValue:function(t){return Qs().memoizedState=t},useTransition:function(){var t=xb(!1),e=t[0];return t=ED.bind(null,t[1]),Qs().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var s=vt,r=Qs();if(ft){if(n===void 0)throw Error(ne(407));n=n()}else{if(n=e(),Xt===null)throw Error(ne(349));Ra&30||uk(s,e,n)}r.memoizedState=n;var a={value:n,getSnapshot:e};return r.queue=a,yb(fk.bind(null,s,a,t),[t]),s.flags|=2048,Tc(9,hk.bind(null,s,a,n,e),void 0,null),n},useId:function(){var t=Qs(),e=Xt.identifierPrefix;if(ft){var n=Dr,s=Ar;n=(s&~(1<<32-$s(s)-1)).toString(32)+n,e=":"+e+"R"+n,n=Dc++,0<\/script>",t=t.removeChild(t.firstChild)):typeof s.is=="string"?t=l.createElement(n,{is:s.is}):(t=l.createElement(n),n==="select"&&(l=t,s.multiple?l.multiple=!0:s.size&&(l.size=s.size))):t=l.createElementNS(t,n),t[nr]=e,t[Cc]=s,Fk(t,e,!1,!1),e.stateNode=t;e:{switch(l=Ep(n,s),n){case"dialog":at("cancel",t),at("close",t),r=s;break;case"iframe":case"object":case"embed":at("load",t),r=s;break;case"video":case"audio":for(r=0;rYl&&(e.flags|=128,s=!0,Mo(a,!1),e.lanes=4194304)}else{if(!s)if(t=Gu(l),t!==null){if(e.flags|=128,s=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),Mo(a,!0),a.tail===null&&a.tailMode==="hidden"&&!l.alternate&&!ft)return pn(e),null}else 2*Pt()-a.renderingStartTime>Yl&&n!==1073741824&&(e.flags|=128,s=!0,Mo(a,!1),e.lanes=4194304);a.isBackwards?(l.sibling=e.child,e.child=l):(n=a.last,n!==null?n.sibling=l:e.child=l,a.last=l)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=Pt(),e.sibling=null,n=xt.current,st(xt,s?n&1|2:n&1),e):(pn(e),null);case 22:case 23:return uy(),s=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==s&&(e.flags|=8192),s&&e.mode&1?es&1073741824&&(pn(e),e.subtreeFlags&6&&(e.flags|=8192)):pn(e),null;case 24:return null;case 25:return null}throw Error(ne(156,e.tag))}function zD(t,e){switch(qx(e),e.tag){case 1:return Wn(e.type)&&Vu(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Jl(),ot(Hn),ot(bn),ey(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return Xx(e),null;case 13:if(ot(xt),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(ne(340));Ql()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return ot(xt),null;case 4:return Jl(),null;case 10:return Gx(e.type._context),null;case 22:case 23:return uy(),null;case 24:return null;default:return null}}var Ud=!1,yn=!1,$D=typeof WeakSet=="function"?WeakSet:Set,xe=null;function yl(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(s){Et(t,e,s)}else n.current=null}function eg(t,e,n){try{n()}catch(s){Et(t,e,s)}}var Db=!1;function BD(t,e){if(Fp=zu,t=Uw(),Kx(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var s=n.getSelection&&n.getSelection();if(s&&s.rangeCount!==0){n=s.anchorNode;var r=s.anchorOffset,a=s.focusNode;s=s.focusOffset;try{n.nodeType,a.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=t,m=null;t:for(;;){for(var f;h!==n||r!==0&&h.nodeType!==3||(o=l+r),h!==a||s!==0&&h.nodeType!==3||(c=l+s),h.nodeType===3&&(l+=h.nodeValue.length),(f=h.firstChild)!==null;)m=h,h=f;for(;;){if(h===t)break t;if(m===n&&++d===r&&(o=l),m===a&&++u===s&&(c=l),(f=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=f}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(zp={focusedElem:t,selectionRange:n},zu=!1,xe=e;xe!==null;)if(e=xe,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,xe=t;else for(;xe!==null;){e=xe;try{var p=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(p!==null){var g=p.memoizedProps,x=p.memoizedState,y=e.stateNode,v=y.getSnapshotBeforeUpdate(e.elementType===e.type?g:Ds(e.type,g),x);y.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var b=e.stateNode.containerInfo;b.nodeType===1?b.textContent="":b.nodeType===9&&b.documentElement&&b.removeChild(b.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ne(163))}}catch(j){Et(e,e.return,j)}if(t=e.sibling,t!==null){t.return=e.return,xe=t;break}xe=e.return}return p=Db,Db=!1,p}function ec(t,e,n){var s=e.updateQueue;if(s=s!==null?s.lastEffect:null,s!==null){var r=s=s.next;do{if((r.tag&t)===t){var a=r.destroy;r.destroy=void 0,a!==void 0&&eg(e,n,a)}r=r.next}while(r!==s)}}function pf(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var s=n.create;n.destroy=s()}n=n.next}while(n!==e)}}function tg(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function Bk(t){var e=t.alternate;e!==null&&(t.alternate=null,Bk(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[nr],delete e[Cc],delete e[_p],delete e[ND],delete e[wD])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function _k(t){return t.tag===5||t.tag===3||t.tag===4}function Mb(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||_k(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function ng(t,e,n){var s=t.tag;if(s===5||s===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=_u));else if(s!==4&&(t=t.child,t!==null))for(ng(t,e,n),t=t.sibling;t!==null;)ng(t,e,n),t=t.sibling}function sg(t,e,n){var s=t.tag;if(s===5||s===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(s!==4&&(t=t.child,t!==null))for(sg(t,e,n),t=t.sibling;t!==null;)sg(t,e,n),t=t.sibling}var sn=null,Ps=!1;function Qr(t,e,n){for(n=n.child;n!==null;)Vk(t,e,n),n=n.sibling}function Vk(t,e,n){if(rr&&typeof rr.onCommitFiberUnmount=="function")try{rr.onCommitFiberUnmount(lf,n)}catch{}switch(n.tag){case 5:yn||yl(n,e);case 6:var s=sn,r=Ps;sn=null,Qr(t,e,n),sn=s,Ps=r,sn!==null&&(Ps?(t=sn,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):sn.removeChild(n.stateNode));break;case 18:sn!==null&&(Ps?(t=sn,n=n.stateNode,t.nodeType===8?xm(t.parentNode,n):t.nodeType===1&&xm(t,n),jc(t)):xm(sn,n.stateNode));break;case 4:s=sn,r=Ps,sn=n.stateNode.containerInfo,Ps=!0,Qr(t,e,n),sn=s,Ps=r;break;case 0:case 11:case 14:case 15:if(!yn&&(s=n.updateQueue,s!==null&&(s=s.lastEffect,s!==null))){r=s=s.next;do{var a=r,l=a.destroy;a=a.tag,l!==void 0&&(a&2||a&4)&&eg(n,e,l),r=r.next}while(r!==s)}Qr(t,e,n);break;case 1:if(!yn&&(yl(n,e),s=n.stateNode,typeof s.componentWillUnmount=="function"))try{s.props=n.memoizedProps,s.state=n.memoizedState,s.componentWillUnmount()}catch(o){Et(n,e,o)}Qr(t,e,n);break;case 21:Qr(t,e,n);break;case 22:n.mode&1?(yn=(s=yn)||n.memoizedState!==null,Qr(t,e,n),yn=s):Qr(t,e,n);break;default:Qr(t,e,n)}}function Tb(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new $D),e.forEach(function(s){var r=GD.bind(null,t,s);n.has(s)||(n.add(s),s.then(r,r))})}}function As(t,e){var n=e.deletions;if(n!==null)for(var s=0;sr&&(r=l),s&=~a}if(s=r,s=Pt()-s,s=(120>s?120:480>s?480:1080>s?1080:1920>s?1920:3e3>s?3e3:4320>s?4320:1960*VD(s/1960))-s,10t?16:t,ji===null)var s=!1;else{if(t=ji,ji=null,eh=0,Ve&6)throw Error(ne(331));var r=Ve;for(Ve|=4,xe=t.current;xe!==null;){var a=xe,l=a.child;if(xe.flags&16){var o=a.deletions;if(o!==null){for(var c=0;cPt()-cy?Na(t,0):oy|=n),Qn(t,e)}function Jk(t,e){e===0&&(t.mode&1?(e=Od,Od<<=1,!(Od&130023424)&&(Od=4194304)):e=1);var n=Dn();t=$r(t,e),t!==null&&(dd(t,e,n),Qn(t,n))}function QD(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),Jk(t,n)}function GD(t,e){var n=0;switch(t.tag){case 13:var s=t.stateNode,r=t.memoizedState;r!==null&&(n=r.retryLane);break;case 19:s=t.stateNode;break;default:throw Error(ne(314))}s!==null&&s.delete(e),Jk(t,n)}var Zk;Zk=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||Hn.current)Kn=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return Kn=!1,LD(t,e,n);Kn=!!(t.flags&131072)}else Kn=!1,ft&&e.flags&1048576&&tk(e,qu,e.index);switch(e.lanes=0,e.tag){case 2:var s=e.type;yu(t,e),t=e.pendingProps;var r=Wl(e,bn.current);Cl(e,n),r=ny(null,e,s,t,r,n);var a=sy();return e.flags|=1,typeof r=="object"&&r!==null&&typeof r.render=="function"&&r.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,Wn(s)?(a=!0,Ku(e)):a=!1,e.memoizedState=r.state!==null&&r.state!==void 0?r.state:null,Zx(e),r.updater=mf,e.stateNode=r,r._reactInternals=e,Wp(e,s,t,n),e=Jp(null,e,s,!0,a,n)):(e.tag=0,ft&&a&&Ux(e),En(null,e,r,n),e=e.child),e;case 16:s=e.elementType;e:{switch(yu(t,e),t=e.pendingProps,r=s._init,s=r(s._payload),e.type=s,r=e.tag=ZD(s),t=Ds(s,t),r){case 0:e=Gp(null,e,s,t,n);break e;case 1:e=Cb(null,e,s,t,n);break e;case 11:e=kb(null,e,s,t,n);break e;case 14:e=Sb(null,e,s,Ds(s.type,t),n);break e}throw Error(ne(306,s,""))}return e;case 0:return s=e.type,r=e.pendingProps,r=e.elementType===s?r:Ds(s,r),Gp(t,e,s,r,n);case 1:return s=e.type,r=e.pendingProps,r=e.elementType===s?r:Ds(s,r),Cb(t,e,s,r,n);case 3:e:{if(Rk(e),t===null)throw Error(ne(387));s=e.pendingProps,a=e.memoizedState,r=a.element,lk(t,e),Qu(e,s,null,n);var l=e.memoizedState;if(s=l.element,a.isDehydrated)if(a={element:s,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},e.updateQueue.baseState=a,e.memoizedState=a,e.flags&256){r=Zl(Error(ne(423)),e),e=Eb(t,e,s,n,r);break e}else if(s!==r){r=Zl(Error(ne(424)),e),e=Eb(t,e,s,n,r);break e}else for(rs=Di(e.stateNode.containerInfo.firstChild),is=e,ft=!0,Is=null,n=ik(e,null,s,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Ql(),s===r){e=Br(t,e,n);break e}En(t,e,s,n)}e=e.child}return e;case 5:return ok(e),t===null&&Up(e),s=e.type,r=e.pendingProps,a=t!==null?t.memoizedProps:null,l=r.children,$p(s,r)?l=null:a!==null&&$p(s,a)&&(e.flags|=32),Ik(t,e),En(t,e,l,n),e.child;case 6:return t===null&&Up(e),null;case 13:return Ok(t,e,n);case 4:return Yx(e,e.stateNode.containerInfo),s=e.pendingProps,t===null?e.child=Gl(e,null,s,n):En(t,e,s,n),e.child;case 11:return s=e.type,r=e.pendingProps,r=e.elementType===s?r:Ds(s,r),kb(t,e,s,r,n);case 7:return En(t,e,e.pendingProps,n),e.child;case 8:return En(t,e,e.pendingProps.children,n),e.child;case 12:return En(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(s=e.type._context,r=e.pendingProps,a=e.memoizedProps,l=r.value,st(Hu,s._currentValue),s._currentValue=l,a!==null)if(Vs(a.value,l)){if(a.children===r.children&&!Hn.current){e=Br(t,e,n);break e}}else for(a=e.child,a!==null&&(a.return=e);a!==null;){var o=a.dependencies;if(o!==null){l=a.child;for(var c=o.firstContext;c!==null;){if(c.context===s){if(a.tag===1){c=Ir(-1,n&-n),c.tag=2;var d=a.updateQueue;if(d!==null){d=d.shared;var u=d.pending;u===null?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}a.lanes|=n,c=a.alternate,c!==null&&(c.lanes|=n),qp(a.return,n,e),o.lanes|=n;break}c=c.next}}else if(a.tag===10)l=a.type===e.type?null:a.child;else if(a.tag===18){if(l=a.return,l===null)throw Error(ne(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),qp(l,n,e),l=a.sibling}else l=a.child;if(l!==null)l.return=a;else for(l=a;l!==null;){if(l===e){l=null;break}if(a=l.sibling,a!==null){a.return=l.return,l=a;break}l=l.return}a=l}En(t,e,r.children,n),e=e.child}return e;case 9:return r=e.type,s=e.pendingProps.children,Cl(e,n),r=Cs(r),s=s(r),e.flags|=1,En(t,e,s,n),e.child;case 14:return s=e.type,r=Ds(s,e.pendingProps),r=Ds(s.type,r),Sb(t,e,s,r,n);case 15:return Tk(t,e,e.type,e.pendingProps,n);case 17:return s=e.type,r=e.pendingProps,r=e.elementType===s?r:Ds(s,r),yu(t,e),e.tag=1,Wn(s)?(t=!0,Ku(e)):t=!1,Cl(e,n),Ak(e,s,r),Wp(e,s,r,n),Jp(null,e,s,!0,t,n);case 19:return Lk(t,e,n);case 22:return Pk(t,e,n)}throw Error(ne(156,e.tag))};function Yk(t,e){return Sw(t,e)}function JD(t,e,n,s){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=s,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ns(t,e,n,s){return new JD(t,e,n,s)}function fy(t){return t=t.prototype,!(!t||!t.isReactComponent)}function ZD(t){if(typeof t=="function")return fy(t)?1:0;if(t!=null){if(t=t.$$typeof,t===Px)return 11;if(t===Ix)return 14}return 2}function Ii(t,e){var n=t.alternate;return n===null?(n=Ns(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function ju(t,e,n,s,r,a){var l=2;if(s=t,typeof t=="function")fy(t)&&(l=1);else if(typeof t=="string")l=5;else e:switch(t){case cl:return wa(n.children,r,a,e);case Tx:l=8,r|=8;break;case xp:return t=Ns(12,n,e,r|2),t.elementType=xp,t.lanes=a,t;case yp:return t=Ns(13,n,e,r),t.elementType=yp,t.lanes=a,t;case vp:return t=Ns(19,n,e,r),t.elementType=vp,t.lanes=a,t;case ow:return xf(n,r,a,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case aw:l=10;break e;case lw:l=9;break e;case Px:l=11;break e;case Ix:l=14;break e;case Yr:l=16,s=null;break e}throw Error(ne(130,t==null?t:typeof t,""))}return e=Ns(l,n,e,r),e.elementType=t,e.type=s,e.lanes=a,e}function wa(t,e,n,s){return t=Ns(7,t,s,e),t.lanes=n,t}function xf(t,e,n,s){return t=Ns(22,t,s,e),t.elementType=ow,t.lanes=n,t.stateNode={isHidden:!1},t}function Sm(t,e,n){return t=Ns(6,t,null,e),t.lanes=n,t}function Cm(t,e,n){return e=Ns(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function YD(t,e,n,s,r){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=am(0),this.expirationTimes=am(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=am(0),this.identifierPrefix=s,this.onRecoverableError=r,this.mutableSourceEagerHydrationData=null}function my(t,e,n,s,r,a,l,o,c){return t=new YD(t,e,n,o,c),e===1?(e=1,a===!0&&(e|=8)):e=0,a=Ns(3,null,null,e),t.current=a,a.stateNode=t,a.memoizedState={element:s,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Zx(a),t}function XD(t,e,n){var s=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(nS)}catch(t){console.error(t)}}nS(),nw.exports=ds;var sS=nw.exports;const rM=UN(sS);var $b=sS;pp.createRoot=$b.createRoot,pp.hydrateRoot=$b.hydrateRoot;/** + * @remix-run/router v1.23.2 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Ic(){return Ic=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function yy(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function aM(){return Math.random().toString(36).substr(2,8)}function _b(t,e){return{usr:t.state,key:t.key,idx:e}}function og(t,e,n,s){return n===void 0&&(n=null),Ic({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?mo(e):e,{state:n,key:e&&e.key||s||aM()})}function sh(t){let{pathname:e="/",search:n="",hash:s=""}=t;return n&&n!=="?"&&(e+=n.charAt(0)==="?"?n:"?"+n),s&&s!=="#"&&(e+=s.charAt(0)==="#"?s:"#"+s),e}function mo(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substr(n),t=t.substr(0,n));let s=t.indexOf("?");s>=0&&(e.search=t.substr(s),t=t.substr(0,s)),t&&(e.pathname=t)}return e}function lM(t,e,n,s){s===void 0&&(s={});let{window:r=document.defaultView,v5Compat:a=!1}=s,l=r.history,o=Ni.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(Ic({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=Ni.Pop;let x=u(),y=x==null?null:x-d;d=x,c&&c({action:o,location:g.location,delta:y})}function m(x,y){o=Ni.Push;let v=og(g.location,x,y);d=u()+1;let b=_b(v,d),j=g.createHref(v);try{l.pushState(b,"",j)}catch(k){if(k instanceof DOMException&&k.name==="DataCloneError")throw k;r.location.assign(j)}a&&c&&c({action:o,location:g.location,delta:1})}function f(x,y){o=Ni.Replace;let v=og(g.location,x,y);d=u();let b=_b(v,d),j=g.createHref(v);l.replaceState(b,"",j),a&&c&&c({action:o,location:g.location,delta:0})}function p(x){let y=r.location.origin!=="null"?r.location.origin:r.location.href,v=typeof x=="string"?x:sh(x);return v=v.replace(/ $/,"%20"),bt(y,"No window.location.(origin|href) available to create URL for href: "+v),new URL(v,y)}let g={get action(){return o},get location(){return t(r,l)},listen(x){if(c)throw new Error("A history only accepts one active listener");return r.addEventListener(Bb,h),c=x,()=>{r.removeEventListener(Bb,h),c=null}},createHref(x){return e(r,x)},createURL:p,encodeLocation(x){let y=p(x);return{pathname:y.pathname,search:y.search,hash:y.hash}},push:m,replace:f,go(x){return l.go(x)}};return g}var Vb;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(Vb||(Vb={}));function oM(t,e,n){return n===void 0&&(n="/"),cM(t,e,n)}function cM(t,e,n,s){let r=typeof e=="string"?mo(e):e,a=Xl(r.pathname||"/",n);if(a==null)return null;let l=rS(t);dM(l);let o=null;for(let c=0;o==null&&c{let c={relativePath:o===void 0?a.path||"":o,caseSensitive:a.caseSensitive===!0,childrenIndex:l,route:a};c.relativePath.startsWith("/")&&(bt(c.relativePath.startsWith(s),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+s+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(s.length));let d=Ri([s,c.relativePath]),u=n.concat(c);a.children&&a.children.length>0&&(bt(a.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),rS(a.children,e,u,d)),!(a.path==null&&!a.index)&&e.push({path:d,score:xM(d,a.index),routesMeta:u})};return t.forEach((a,l)=>{var o;if(a.path===""||!((o=a.path)!=null&&o.includes("?")))r(a,l);else for(let c of iS(a.path))r(a,l,c)}),e}function iS(t){let e=t.split("/");if(e.length===0)return[];let[n,...s]=e,r=n.endsWith("?"),a=n.replace(/\?$/,"");if(s.length===0)return r?[a,""]:[a];let l=iS(s.join("/")),o=[];return o.push(...l.map(c=>c===""?a:[a,c].join("/"))),r&&o.push(...l),o.map(c=>t.startsWith("/")&&c===""?"/":c)}function dM(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:yM(e.routesMeta.map(s=>s.childrenIndex),n.routesMeta.map(s=>s.childrenIndex)))}const uM=/^:[\w-]+$/,hM=3,fM=2,mM=1,pM=10,gM=-2,Kb=t=>t==="*";function xM(t,e){let n=t.split("/"),s=n.length;return n.some(Kb)&&(s+=gM),e&&(s+=fM),n.filter(r=>!Kb(r)).reduce((r,a)=>r+(uM.test(a)?hM:a===""?mM:pM),s)}function yM(t,e){return t.length===e.length&&t.slice(0,-1).every((s,r)=>s===e[r])?t[t.length-1]-e[e.length-1]:0}function vM(t,e,n){let{routesMeta:s}=t,r={},a="/",l=[];for(let o=0;o{let{paramName:m,isOptional:f}=u;if(m==="*"){let g=o[h]||"";l=a.slice(0,a.length-g.length).replace(/(.)\/+$/,"$1")}const p=o[h];return f&&!p?d[m]=void 0:d[m]=(p||"").replace(/%2F/g,"/"),d},{}),pathname:a,pathnameBase:l,pattern:t}}function bM(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=!0),yy(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let s=[],r="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(s.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(s.push({paramName:"*"}),r+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?r+="\\/*$":t!==""&&t!=="/"&&(r+="(?:(?=\\/|$))"),[new RegExp(r,e?void 0:"i"),s]}function jM(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return yy(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function Xl(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,s=t.charAt(n);return s&&s!=="/"?null:t.slice(n)||"/"}const NM=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,wM=t=>NM.test(t);function kM(t,e){e===void 0&&(e="/");let{pathname:n,search:s="",hash:r=""}=typeof t=="string"?mo(t):t,a;if(n)if(wM(n))a=n;else{if(n.includes("//")){let l=n;n=n.replace(/\/\/+/g,"/"),yy(!1,"Pathnames cannot have embedded double slashes - normalizing "+(l+" -> "+n))}n.startsWith("/")?a=Ub(n.substring(1),"/"):a=Ub(n,e)}else a=e;return{pathname:a,search:EM(s),hash:AM(r)}}function Ub(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(r=>{r===".."?n.length>1&&n.pop():r!=="."&&n.push(r)}),n.length>1?n.join("/"):"/"}function Em(t,e,n,s){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(s)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function SM(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function vy(t,e){let n=SM(t);return e?n.map((s,r)=>r===n.length-1?s.pathname:s.pathnameBase):n.map(s=>s.pathnameBase)}function by(t,e,n,s){s===void 0&&(s=!1);let r;typeof t=="string"?r=mo(t):(r=Ic({},t),bt(!r.pathname||!r.pathname.includes("?"),Em("?","pathname","search",r)),bt(!r.pathname||!r.pathname.includes("#"),Em("#","pathname","hash",r)),bt(!r.search||!r.search.includes("#"),Em("#","search","hash",r)));let a=t===""||r.pathname==="",l=a?"/":r.pathname,o;if(l==null)o=n;else{let h=e.length-1;if(!s&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),h-=1;r.pathname=m.join("/")}o=h>=0?e[h]:"/"}let c=kM(r,o),d=l&&l!=="/"&&l.endsWith("/"),u=(a||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const Ri=t=>t.join("/").replace(/\/\/+/g,"/"),CM=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),EM=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,AM=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function DM(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const aS=["post","put","patch","delete"];new Set(aS);const MM=["get",...aS];new Set(MM);/** + * React Router v6.30.3 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Rc(){return Rc=Object.assign?Object.assign.bind():function(t){for(var e=1;e{o.current=!0}),N.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){s.go(d);return}let h=by(d,JSON.parse(l),a,u.relative==="path");t==null&&e!=="/"&&(h.pathname=h.pathname==="/"?e:Ri([e,h.pathname])),(u.replace?s.replace:s.push)(h,u.state,u)},[e,s,l,a,t])}const IM=N.createContext(null);function RM(t){let e=N.useContext(dr).outlet;return e&&N.createElement(IM.Provider,{value:t},e)}function md(){let{matches:t}=N.useContext(dr),e=t[t.length-1];return e?e.params:{}}function kf(t,e){let{relative:n}=e===void 0?{}:e,{future:s}=N.useContext(Ur),{matches:r}=N.useContext(dr),{pathname:a}=qr(),l=JSON.stringify(vy(r,s.v7_relativeSplatPath));return N.useMemo(()=>by(t,JSON.parse(l),a,n==="path"),[t,l,a,n])}function OM(t,e){return LM(t,e)}function LM(t,e,n,s){po()||bt(!1);let{navigator:r}=N.useContext(Ur),{matches:a}=N.useContext(dr),l=a[a.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=qr(),u;if(e){var h;let x=typeof e=="string"?mo(e):e;c==="/"||(h=x.pathname)!=null&&h.startsWith(c)||bt(!1),u=x}else u=d;let m=u.pathname||"/",f=m;if(c!=="/"){let x=c.replace(/^\//,"").split("/");f="/"+m.replace(/^\//,"").split("/").slice(x.length).join("/")}let p=oM(t,{pathname:f}),g=_M(p&&p.map(x=>Object.assign({},x,{params:Object.assign({},o,x.params),pathname:Ri([c,r.encodeLocation?r.encodeLocation(x.pathname).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?c:Ri([c,r.encodeLocation?r.encodeLocation(x.pathnameBase).pathname:x.pathnameBase])})),a,n,s);return e&&g?N.createElement(wf.Provider,{value:{location:Rc({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:Ni.Pop}},g):g}function FM(){let t=qM(),e=DM(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,r={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},e),n?N.createElement("pre",{style:r},n):null,null)}const zM=N.createElement(FM,null);class $M extends N.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,n){return n.location!==e.location||n.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:n.error,location:n.location,revalidation:e.revalidation||n.revalidation}}componentDidCatch(e,n){console.error("React Router caught the following error during render",e,n)}render(){return this.state.error!==void 0?N.createElement(dr.Provider,{value:this.props.routeContext},N.createElement(oS.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function BM(t){let{routeContext:e,match:n,children:s}=t,r=N.useContext(Nf);return r&&r.static&&r.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=n.route.id),N.createElement(dr.Provider,{value:e},s)}function _M(t,e,n,s){var r;if(e===void 0&&(e=[]),n===void 0&&(n=null),s===void 0&&(s=null),t==null){var a;if(!n)return null;if(n.errors)t=n.matches;else if((a=s)!=null&&a.v7_partialHydration&&e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let l=t,o=(r=n)==null?void 0:r.errors;if(o!=null){let u=l.findIndex(h=>h.route.id&&(o==null?void 0:o[h.route.id])!==void 0);u>=0||bt(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&s&&s.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let f,p=!1,g=null,x=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,g=h.route.errorElement||zM,c&&(d<0&&m===0?(WM("route-fallback"),p=!0,x=null):d===m&&(p=!0,x=h.route.hydrateFallbackElement||null)));let y=e.concat(l.slice(0,m+1)),v=()=>{let b;return f?b=g:p?b=x:h.route.Component?b=N.createElement(h.route.Component,null):h.route.element?b=h.route.element:b=u,N.createElement(BM,{match:h,routeContext:{outlet:u,matches:y,isDataRoute:n!=null},children:b})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?N.createElement($M,{location:n.location,revalidation:n.revalidation,component:g,error:f,children:v(),routeContext:{outlet:null,matches:y,isDataRoute:!0}}):v()},null)}var dS=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(dS||{}),uS=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(uS||{});function VM(t){let e=N.useContext(Nf);return e||bt(!1),e}function KM(t){let e=N.useContext(lS);return e||bt(!1),e}function UM(t){let e=N.useContext(dr);return e||bt(!1),e}function hS(t){let e=UM(),n=e.matches[e.matches.length-1];return n.route.id||bt(!1),n.route.id}function qM(){var t;let e=N.useContext(oS),n=KM(),s=hS();return e!==void 0?e:(t=n.errors)==null?void 0:t[s]}function HM(){let{router:t}=VM(dS.UseNavigateStable),e=hS(uS.UseNavigateStable),n=N.useRef(!1);return cS(()=>{n.current=!0}),N.useCallback(function(r,a){a===void 0&&(a={}),n.current&&(typeof r=="number"?t.navigate(r):t.navigate(r,Rc({fromRouteId:e},a)))},[t,e])}const qb={};function WM(t,e,n){qb[t]||(qb[t]=!0)}function QM(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function bl(t){let{to:e,replace:n,state:s,relative:r}=t;po()||bt(!1);let{future:a,static:l}=N.useContext(Ur),{matches:o}=N.useContext(dr),{pathname:c}=qr(),d=fn(),u=by(e,vy(o,a.v7_relativeSplatPath),c,r==="path"),h=JSON.stringify(u);return N.useEffect(()=>d(JSON.parse(h),{replace:n,state:s,relative:r}),[d,h,r,n,s]),null}function GM(t){return RM(t.context)}function $e(t){bt(!1)}function JM(t){let{basename:e="/",children:n=null,location:s,navigationType:r=Ni.Pop,navigator:a,static:l=!1,future:o}=t;po()&&bt(!1);let c=e.replace(/^\/*/,"/"),d=N.useMemo(()=>({basename:c,navigator:a,static:l,future:Rc({v7_relativeSplatPath:!1},o)}),[c,o,a,l]);typeof s=="string"&&(s=mo(s));let{pathname:u="/",search:h="",hash:m="",state:f=null,key:p="default"}=s,g=N.useMemo(()=>{let x=Xl(u,c);return x==null?null:{location:{pathname:x,search:h,hash:m,state:f,key:p},navigationType:r}},[c,u,h,m,f,p,r]);return g==null?null:N.createElement(Ur.Provider,{value:d},N.createElement(wf.Provider,{children:n,value:g}))}function ZM(t){let{children:e,location:n}=t;return OM(dg(e),n)}new Promise(()=>{});function dg(t,e){e===void 0&&(e=[]);let n=[];return N.Children.forEach(t,(s,r)=>{if(!N.isValidElement(s))return;let a=[...e,r];if(s.type===N.Fragment){n.push.apply(n,dg(s.props.children,a));return}s.type!==$e&&bt(!1),!s.props.index||!s.props.children||bt(!1);let l={id:s.props.id||a.join("-"),caseSensitive:s.props.caseSensitive,element:s.props.element,Component:s.props.Component,index:s.props.index,path:s.props.path,loader:s.props.loader,action:s.props.action,errorElement:s.props.errorElement,ErrorBoundary:s.props.ErrorBoundary,hasErrorBoundary:s.props.ErrorBoundary!=null||s.props.errorElement!=null,shouldRevalidate:s.props.shouldRevalidate,handle:s.props.handle,lazy:s.props.lazy};s.props.children&&(l.children=dg(s.props.children,a)),n.push(l)}),n}/** + * React Router DOM v6.30.3 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function rh(){return rh=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(n[r]=t[r]);return n}function YM(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function XM(t,e){return t.button===0&&(!e||e==="_self")&&!YM(t)}function ug(t){return t===void 0&&(t=""),new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,n)=>{let s=t[n];return e.concat(Array.isArray(s)?s.map(r=>[n,r]):[[n,s]])},[]))}function eT(t,e){let n=ug(t);return e&&e.forEach((s,r)=>{n.has(r)||e.getAll(r).forEach(a=>{n.append(r,a)})}),n}const tT=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],nT=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],sT="6";try{window.__reactRouterVersion=sT}catch{}const rT=N.createContext({isTransitioning:!1}),iT="startTransition",Hb=W4[iT];function aT(t){let{basename:e,children:n,future:s,window:r}=t,a=N.useRef();a.current==null&&(a.current=iM({window:r,v5Compat:!0}));let l=a.current,[o,c]=N.useState({action:l.action,location:l.location}),{v7_startTransition:d}=s||{},u=N.useCallback(h=>{d&&Hb?Hb(()=>c(h)):c(h)},[c,d]);return N.useLayoutEffect(()=>l.listen(u),[l,u]),N.useEffect(()=>QM(s),[s]),N.createElement(JM,{basename:e,children:n,location:o.location,navigationType:o.action,navigator:l,future:s})}const lT=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",oT=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Me=N.forwardRef(function(e,n){let{onClick:s,relative:r,reloadDocument:a,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=e,m=fS(e,tT),{basename:f}=N.useContext(Ur),p,g=!1;if(typeof d=="string"&&oT.test(d)&&(p=d,lT))try{let b=new URL(window.location.href),j=d.startsWith("//")?new URL(b.protocol+d):new URL(d),k=Xl(j.pathname,f);j.origin===b.origin&&k!=null?d=k+j.search+j.hash:g=!0}catch{}let x=TM(d,{relative:r}),y=dT(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:r,viewTransition:h});function v(b){s&&s(b),b.defaultPrevented||y(b)}return N.createElement("a",rh({},m,{href:p||x,onClick:g||a?s:v,ref:n,target:c}))}),Am=N.forwardRef(function(e,n){let{"aria-current":s="page",caseSensitive:r=!1,className:a="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=e,h=fS(e,nT),m=kf(c,{relative:h.relative}),f=qr(),p=N.useContext(lS),{navigator:g,basename:x}=N.useContext(Ur),y=p!=null&&uT(m)&&d===!0,v=g.encodeLocation?g.encodeLocation(m).pathname:m.pathname,b=f.pathname,j=p&&p.navigation&&p.navigation.location?p.navigation.location.pathname:null;r||(b=b.toLowerCase(),j=j?j.toLowerCase():null,v=v.toLowerCase()),j&&x&&(j=Xl(j,x)||j);const k=v!=="/"&&v.endsWith("/")?v.length-1:v.length;let E=b===v||!l&&b.startsWith(v)&&b.charAt(k)==="/",T=j!=null&&(j===v||!l&&j.startsWith(v)&&j.charAt(v.length)==="/"),w={isActive:E,isPending:T,isTransitioning:y},S=E?s:void 0,M;typeof a=="function"?M=a(w):M=[a,E?"active":null,T?"pending":null,y?"transitioning":null].filter(Boolean).join(" ");let F=typeof o=="function"?o(w):o;return N.createElement(Me,rh({},h,{"aria-current":S,className:M,ref:n,style:F,to:c,viewTransition:d}),typeof u=="function"?u(w):u)});var hg;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(hg||(hg={}));var Wb;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Wb||(Wb={}));function cT(t){let e=N.useContext(Nf);return e||bt(!1),e}function dT(t,e){let{target:n,replace:s,state:r,preventScrollReset:a,relative:l,viewTransition:o}=e===void 0?{}:e,c=fn(),d=qr(),u=kf(t,{relative:l});return N.useCallback(h=>{if(XM(h,n)){h.preventDefault();let m=s!==void 0?s:sh(d)===sh(u);c(t,{replace:m,state:r,preventScrollReset:a,relative:l,viewTransition:o})}},[d,c,u,s,r,n,t,a,l,o])}function Sf(t){let e=N.useRef(ug(t)),n=N.useRef(!1),s=qr(),r=N.useMemo(()=>eT(s.search,n.current?null:e.current),[s.search]),a=fn(),l=N.useCallback((o,c)=>{const d=ug(typeof o=="function"?o(r):o);n.current=!0,a("?"+d,c)},[a,r]);return[r,l]}function uT(t,e){e===void 0&&(e={});let n=N.useContext(rT);n==null&&bt(!1);let{basename:s}=cT(hg.useViewTransitionState),r=kf(t,{relative:e.relative});if(!n.isTransitioning)return!1;let a=Xl(n.currentLocation.pathname,s)||n.currentLocation.pathname,l=Xl(n.nextLocation.pathname,s)||n.nextLocation.pathname;return cg(r.pathname,l)!=null||cg(r.pathname,a)!=null}var Qa=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},hT={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},di,wx,PN,fT=(PN=class{constructor(){ge(this,di,hT);ge(this,wx,!1)}setTimeoutProvider(t){re(this,di,t)}setTimeout(t,e){return P(this,di).setTimeout(t,e)}clearTimeout(t){P(this,di).clearTimeout(t)}setInterval(t,e){return P(this,di).setInterval(t,e)}clearInterval(t){P(this,di).clearInterval(t)}},di=new WeakMap,wx=new WeakMap,PN),ia=new fT;function mT(t){setTimeout(t,0)}var Fa=typeof window>"u"||"Deno"in globalThis;function xn(){}function pT(t,e){return typeof t=="function"?t(e):t}function fg(t){return typeof t=="number"&&t>=0&&t!==1/0}function mS(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Oi(t,e){return typeof t=="function"?t(e):t}function xs(t,e){return typeof t=="function"?t(e):t}function Qb(t,e){const{type:n="all",exact:s,fetchStatus:r,predicate:a,queryKey:l,stale:o}=t;if(l){if(s){if(e.queryHash!==jy(l,e.options))return!1}else if(!Oc(e.queryKey,l))return!1}if(n!=="all"){const c=e.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||r&&r!==e.state.fetchStatus||a&&!a(e))}function Gb(t,e){const{exact:n,status:s,predicate:r,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(n){if(za(e.options.mutationKey)!==za(a))return!1}else if(!Oc(e.options.mutationKey,a))return!1}return!(s&&e.state.status!==s||r&&!r(e))}function jy(t,e){return((e==null?void 0:e.queryKeyHashFn)||za)(t)}function za(t){return JSON.stringify(t,(e,n)=>mg(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function Oc(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>Oc(t[n],e[n])):!1}var gT=Object.prototype.hasOwnProperty;function Ny(t,e,n=0){if(t===e)return t;if(n>500)return e;const s=Jb(t)&&Jb(e);if(!s&&!(mg(t)&&mg(e)))return e;const a=(s?t:Object.keys(t)).length,l=s?e:Object.keys(e),o=l.length,c=s?new Array(o):{};let d=0;for(let u=0;u{ia.setTimeout(e,t)})}function pg(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?Ny(t,e):e}function yT(t,e,n=0){const s=[...t,e];return n&&s.length>n?s.slice(1):s}function vT(t,e,n=0){const s=[e,...t];return n&&s.length>n?s.slice(0,-1):s}var wy=Symbol();function pS(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===wy?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function ky(t,e){return typeof t=="function"?t(...e):!!t}function bT(t,e,n){let s=!1,r;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(r??(r=e()),s||(s=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),t}var fa,ui,Tl,IN,jT=(IN=class extends Qa{constructor(){super();ge(this,fa);ge(this,ui);ge(this,Tl);re(this,Tl,e=>{if(!Fa&&window.addEventListener){const n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){P(this,ui)||this.setEventListener(P(this,Tl))}onUnsubscribe(){var e;this.hasListeners()||((e=P(this,ui))==null||e.call(this),re(this,ui,void 0))}setEventListener(e){var n;re(this,Tl,e),(n=P(this,ui))==null||n.call(this),re(this,ui,e(s=>{typeof s=="boolean"?this.setFocused(s):this.onFocus()}))}setFocused(e){P(this,fa)!==e&&(re(this,fa,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){var e;return typeof P(this,fa)=="boolean"?P(this,fa):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},fa=new WeakMap,ui=new WeakMap,Tl=new WeakMap,IN),Sy=new jT;function gg(){let t,e;const n=new Promise((r,a)=>{t=r,e=a});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),t(r)},n.reject=r=>{s({status:"rejected",reason:r}),e(r)},n}var NT=mT;function wT(){let t=[],e=0,n=o=>{o()},s=o=>{o()},r=NT;const a=o=>{e?t.push(o):r(()=>{n(o)})},l=()=>{const o=t;t=[],o.length&&r(()=>{s(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;e++;try{c=o()}finally{e--,e||l()}return c},batchCalls:o=>(...c)=>{a(()=>{o(...c)})},schedule:a,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{s=o},setScheduler:o=>{r=o}}}var Mt=wT(),Pl,hi,Il,RN,kT=(RN=class extends Qa{constructor(){super();ge(this,Pl,!0);ge(this,hi);ge(this,Il);re(this,Il,e=>{if(!Fa&&window.addEventListener){const n=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",s)}}})}onSubscribe(){P(this,hi)||this.setEventListener(P(this,Il))}onUnsubscribe(){var e;this.hasListeners()||((e=P(this,hi))==null||e.call(this),re(this,hi,void 0))}setEventListener(e){var n;re(this,Il,e),(n=P(this,hi))==null||n.call(this),re(this,hi,e(this.setOnline.bind(this)))}setOnline(e){P(this,Pl)!==e&&(re(this,Pl,e),this.listeners.forEach(s=>{s(e)}))}isOnline(){return P(this,Pl)}},Pl=new WeakMap,hi=new WeakMap,Il=new WeakMap,RN),ih=new kT;function ST(t){return Math.min(1e3*2**t,3e4)}function gS(t){return(t??"online")==="online"?ih.isOnline():!0}var xg=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function xS(t){let e=!1,n=0,s;const r=gg(),a=()=>r.status!=="pending",l=g=>{var x;if(!a()){const y=new xg(g);m(y),(x=t.onCancel)==null||x.call(t,y)}},o=()=>{e=!0},c=()=>{e=!1},d=()=>Sy.isFocused()&&(t.networkMode==="always"||ih.isOnline())&&t.canRun(),u=()=>gS(t.networkMode)&&t.canRun(),h=g=>{a()||(s==null||s(),r.resolve(g))},m=g=>{a()||(s==null||s(),r.reject(g))},f=()=>new Promise(g=>{var x;s=y=>{(a()||d())&&g(y)},(x=t.onPause)==null||x.call(t)}).then(()=>{var g;s=void 0,a()||(g=t.onContinue)==null||g.call(t)}),p=()=>{if(a())return;let g;const x=n===0?t.initialPromise:void 0;try{g=x??t.fn()}catch(y){g=Promise.reject(y)}Promise.resolve(g).then(h).catch(y=>{var E;if(a())return;const v=t.retry??(Fa?0:3),b=t.retryDelay??ST,j=typeof b=="function"?b(n,y):b,k=v===!0||typeof v=="number"&&nd()?void 0:f()).then(()=>{e?m(y):p()})})};return{promise:r,status:()=>r.status,cancel:l,continue:()=>(s==null||s(),r),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?p():f().then(p),r)}}var ma,ON,yS=(ON=class{constructor(){ge(this,ma)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),fg(this.gcTime)&&re(this,ma,ia.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Fa?1/0:5*60*1e3))}clearGcTimeout(){P(this,ma)&&(ia.clearTimeout(P(this,ma)),re(this,ma,void 0))}},ma=new WeakMap,ON),pa,Rl,ps,ga,Qt,ed,xa,Ms,yr,LN,CT=(LN=class extends yS{constructor(e){super();ge(this,Ms);ge(this,pa);ge(this,Rl);ge(this,ps);ge(this,ga);ge(this,Qt);ge(this,ed);ge(this,xa);re(this,xa,!1),re(this,ed,e.defaultOptions),this.setOptions(e.options),this.observers=[],re(this,ga,e.client),re(this,ps,P(this,ga).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,re(this,pa,Xb(this.options)),this.state=e.state??P(this,pa),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=P(this,Qt))==null?void 0:e.promise}setOptions(e){if(this.options={...P(this,ed),...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=Xb(this.options);n.data!==void 0&&(this.setState(Yb(n.data,n.dataUpdatedAt)),re(this,pa,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&P(this,ps).remove(this)}setData(e,n){const s=pg(this.state.data,e,this.options);return Ce(this,Ms,yr).call(this,{data:s,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),s}setState(e,n){Ce(this,Ms,yr).call(this,{type:"setState",state:e,setStateOptions:n})}cancel(e){var s,r;const n=(s=P(this,Qt))==null?void 0:s.promise;return(r=P(this,Qt))==null||r.cancel(e),n?n.then(xn).catch(xn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(P(this,pa))}isActive(){return this.observers.some(e=>xs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===wy||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Oi(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!mS(this.state.dataUpdatedAt,e)}onFocus(){var n;const e=this.observers.find(s=>s.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(n=P(this,Qt))==null||n.continue()}onOnline(){var n;const e=this.observers.find(s=>s.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(n=P(this,Qt))==null||n.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),P(this,ps).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(n=>n!==e),this.observers.length||(P(this,Qt)&&(P(this,xa)?P(this,Qt).cancel({revert:!0}):P(this,Qt).cancelRetry()),this.scheduleGc()),P(this,ps).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ce(this,Ms,yr).call(this,{type:"invalidate"})}async fetch(e,n){var c,d,u,h,m,f,p,g,x,y,v,b;if(this.state.fetchStatus!=="idle"&&((c=P(this,Qt))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(P(this,Qt))return P(this,Qt).continueRetry(),P(this,Qt).promise}if(e&&this.setOptions(e),!this.options.queryFn){const j=this.observers.find(k=>k.options.queryFn);j&&this.setOptions(j.options)}const s=new AbortController,r=j=>{Object.defineProperty(j,"signal",{enumerable:!0,get:()=>(re(this,xa,!0),s.signal)})},a=()=>{const j=pS(this.options,n),E=(()=>{const T={client:P(this,ga),queryKey:this.queryKey,meta:this.meta};return r(T),T})();return re(this,xa,!1),this.options.persister?this.options.persister(j,E,this):j(E)},o=(()=>{const j={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:P(this,ga),state:this.state,fetchFn:a};return r(j),j})();(d=this.options.behavior)==null||d.onFetch(o,this),re(this,Rl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Ce(this,Ms,yr).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),re(this,Qt,xS({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:j=>{j instanceof xg&&j.revert&&this.setState({...P(this,Rl),fetchStatus:"idle"}),s.abort()},onFail:(j,k)=>{Ce(this,Ms,yr).call(this,{type:"failed",failureCount:j,error:k})},onPause:()=>{Ce(this,Ms,yr).call(this,{type:"pause"})},onContinue:()=>{Ce(this,Ms,yr).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const j=await P(this,Qt).start();if(j===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(j),(f=(m=P(this,ps).config).onSuccess)==null||f.call(m,j,this),(g=(p=P(this,ps).config).onSettled)==null||g.call(p,j,this.state.error,this),j}catch(j){if(j instanceof xg){if(j.silent)return P(this,Qt).promise;if(j.revert){if(this.state.data===void 0)throw j;return this.state.data}}throw Ce(this,Ms,yr).call(this,{type:"error",error:j}),(y=(x=P(this,ps).config).onError)==null||y.call(x,j,this),(b=(v=P(this,ps).config).onSettled)==null||b.call(v,this.state.data,j,this),j}finally{this.scheduleGc()}}},pa=new WeakMap,Rl=new WeakMap,ps=new WeakMap,ga=new WeakMap,Qt=new WeakMap,ed=new WeakMap,xa=new WeakMap,Ms=new WeakSet,yr=function(e){const n=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...vS(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,...Yb(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return re(this,Rl,e.manual?r:void 0),r;case"error":const a=e.error;return{...s,error:a,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=n(this.state),Mt.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),P(this,ps).notify({query:this,type:"updated",action:e})})},LN);function vS(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:gS(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function Yb(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Xb(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,s=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var zn,ze,td,kn,ya,Ol,kr,fi,nd,Ll,Fl,va,ba,mi,zl,Qe,_o,yg,vg,bg,jg,Ng,wg,kg,bS,FN,Cy=(FN=class extends Qa{constructor(e,n){super();ge(this,Qe);ge(this,zn);ge(this,ze);ge(this,td);ge(this,kn);ge(this,ya);ge(this,Ol);ge(this,kr);ge(this,fi);ge(this,nd);ge(this,Ll);ge(this,Fl);ge(this,va);ge(this,ba);ge(this,mi);ge(this,zl,new Set);this.options=n,re(this,zn,e),re(this,fi,null),re(this,kr,gg()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(P(this,ze).addObserver(this),e1(P(this,ze),this.options)?Ce(this,Qe,_o).call(this):this.updateResult(),Ce(this,Qe,jg).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Sg(P(this,ze),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Sg(P(this,ze),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Ce(this,Qe,Ng).call(this),Ce(this,Qe,wg).call(this),P(this,ze).removeObserver(this)}setOptions(e){const n=this.options,s=P(this,ze);if(this.options=P(this,zn).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof xs(this.options.enabled,P(this,ze))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Ce(this,Qe,kg).call(this),P(this,ze).setOptions(this.options),n._defaulted&&!Lc(this.options,n)&&P(this,zn).getQueryCache().notify({type:"observerOptionsUpdated",query:P(this,ze),observer:this});const r=this.hasListeners();r&&t1(P(this,ze),s,this.options,n)&&Ce(this,Qe,_o).call(this),this.updateResult(),r&&(P(this,ze)!==s||xs(this.options.enabled,P(this,ze))!==xs(n.enabled,P(this,ze))||Oi(this.options.staleTime,P(this,ze))!==Oi(n.staleTime,P(this,ze)))&&Ce(this,Qe,yg).call(this);const a=Ce(this,Qe,vg).call(this);r&&(P(this,ze)!==s||xs(this.options.enabled,P(this,ze))!==xs(n.enabled,P(this,ze))||a!==P(this,mi))&&Ce(this,Qe,bg).call(this,a)}getOptimisticResult(e){const n=P(this,zn).getQueryCache().build(P(this,zn),e),s=this.createResult(n,e);return AT(this,s)&&(re(this,kn,s),re(this,Ol,this.options),re(this,ya,P(this,ze).state)),s}getCurrentResult(){return P(this,kn)}trackResult(e,n){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),n==null||n(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&P(this,kr).status==="pending"&&P(this,kr).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){P(this,zl).add(e)}getCurrentQuery(){return P(this,ze)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const n=P(this,zn).defaultQueryOptions(e),s=P(this,zn).getQueryCache().build(P(this,zn),n);return s.fetch().then(()=>this.createResult(s,n))}fetch(e){return Ce(this,Qe,_o).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),P(this,kn)))}createResult(e,n){var S;const s=P(this,ze),r=this.options,a=P(this,kn),l=P(this,ya),o=P(this,Ol),d=e!==s?e.state:P(this,td),{state:u}=e;let h={...u},m=!1,f;if(n._optimisticResults){const M=this.hasListeners(),F=!M&&e1(e,n),R=M&&t1(e,s,n,r);(F||R)&&(h={...h,...vS(u.data,e.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:p,errorUpdatedAt:g,status:x}=h;f=h.data;let y=!1;if(n.placeholderData!==void 0&&f===void 0&&x==="pending"){let M;a!=null&&a.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(M=a.data,y=!0):M=typeof n.placeholderData=="function"?n.placeholderData((S=P(this,Fl))==null?void 0:S.state.data,P(this,Fl)):n.placeholderData,M!==void 0&&(x="success",f=pg(a==null?void 0:a.data,M,n),m=!0)}if(n.select&&f!==void 0&&!y)if(a&&f===(l==null?void 0:l.data)&&n.select===P(this,nd))f=P(this,Ll);else try{re(this,nd,n.select),f=n.select(f),f=pg(a==null?void 0:a.data,f,n),re(this,Ll,f),re(this,fi,null)}catch(M){re(this,fi,M)}P(this,fi)&&(p=P(this,fi),f=P(this,Ll),g=Date.now(),x="error");const v=h.fetchStatus==="fetching",b=x==="pending",j=x==="error",k=b&&v,E=f!==void 0,w={status:x,fetchStatus:h.fetchStatus,isPending:b,isSuccess:x==="success",isError:j,isInitialLoading:k,isLoading:k,data:f,dataUpdatedAt:h.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:v,isRefetching:v&&!b,isLoadingError:j&&!E,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:j&&E,isStale:Ey(e,n),refetch:this.refetch,promise:P(this,kr),isEnabled:xs(n.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const M=w.data!==void 0,F=w.status==="error"&&!M,R=z=>{F?z.reject(w.error):M&&z.resolve(w.data)},V=()=>{const z=re(this,kr,w.promise=gg());R(z)},D=P(this,kr);switch(D.status){case"pending":e.queryHash===s.queryHash&&R(D);break;case"fulfilled":(F||w.data!==D.value)&&V();break;case"rejected":(!F||w.error!==D.reason)&&V();break}}return w}updateResult(){const e=P(this,kn),n=this.createResult(P(this,ze),this.options);if(re(this,ya,P(this,ze).state),re(this,Ol,this.options),P(this,ya).data!==void 0&&re(this,Fl,P(this,ze)),Lc(n,e))return;re(this,kn,n);const s=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,a=typeof r=="function"?r():r;if(a==="all"||!a&&!P(this,zl).size)return!0;const l=new Set(a??P(this,zl));return this.options.throwOnError&&l.add("error"),Object.keys(P(this,kn)).some(o=>{const c=o;return P(this,kn)[c]!==e[c]&&l.has(c)})};Ce(this,Qe,bS).call(this,{listeners:s()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Ce(this,Qe,jg).call(this)}},zn=new WeakMap,ze=new WeakMap,td=new WeakMap,kn=new WeakMap,ya=new WeakMap,Ol=new WeakMap,kr=new WeakMap,fi=new WeakMap,nd=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,va=new WeakMap,ba=new WeakMap,mi=new WeakMap,zl=new WeakMap,Qe=new WeakSet,_o=function(e){Ce(this,Qe,kg).call(this);let n=P(this,ze).fetch(this.options,e);return e!=null&&e.throwOnError||(n=n.catch(xn)),n},yg=function(){Ce(this,Qe,Ng).call(this);const e=Oi(this.options.staleTime,P(this,ze));if(Fa||P(this,kn).isStale||!fg(e))return;const s=mS(P(this,kn).dataUpdatedAt,e)+1;re(this,va,ia.setTimeout(()=>{P(this,kn).isStale||this.updateResult()},s))},vg=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(P(this,ze)):this.options.refetchInterval)??!1},bg=function(e){Ce(this,Qe,wg).call(this),re(this,mi,e),!(Fa||xs(this.options.enabled,P(this,ze))===!1||!fg(P(this,mi))||P(this,mi)===0)&&re(this,ba,ia.setInterval(()=>{(this.options.refetchIntervalInBackground||Sy.isFocused())&&Ce(this,Qe,_o).call(this)},P(this,mi)))},jg=function(){Ce(this,Qe,yg).call(this),Ce(this,Qe,bg).call(this,Ce(this,Qe,vg).call(this))},Ng=function(){P(this,va)&&(ia.clearTimeout(P(this,va)),re(this,va,void 0))},wg=function(){P(this,ba)&&(ia.clearInterval(P(this,ba)),re(this,ba,void 0))},kg=function(){const e=P(this,zn).getQueryCache().build(P(this,zn),this.options);if(e===P(this,ze))return;const n=P(this,ze);re(this,ze,e),re(this,td,e.state),this.hasListeners()&&(n==null||n.removeObserver(this),e.addObserver(this))},bS=function(e){Mt.batch(()=>{e.listeners&&this.listeners.forEach(n=>{n(P(this,kn))}),P(this,zn).getQueryCache().notify({query:P(this,ze),type:"observerResultsUpdated"})})},FN);function ET(t,e){return xs(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function e1(t,e){return ET(t,e)||t.state.data!==void 0&&Sg(t,e,e.refetchOnMount)}function Sg(t,e,n){if(xs(e.enabled,t)!==!1&&Oi(e.staleTime,t)!=="static"){const s=typeof n=="function"?n(t):n;return s==="always"||s!==!1&&Ey(t,e)}return!1}function t1(t,e,n,s){return(t!==e||xs(s.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&Ey(t,n)}function Ey(t,e){return xs(e.enabled,t)!==!1&&t.isStaleByTime(Oi(e.staleTime,t))}function AT(t,e){return!Lc(t.getCurrentResult(),e)}function n1(t){return{onFetch:(e,n)=>{var u,h,m,f,p;const s=e.options,r=(m=(h=(u=e.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,a=((f=e.state.data)==null?void 0:f.pages)||[],l=((p=e.state.data)==null?void 0:p.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let g=!1;const x=b=>{bT(b,()=>e.signal,()=>g=!0)},y=pS(e.options,e.fetchOptions),v=async(b,j,k)=>{if(g)return Promise.reject();if(j==null&&b.pages.length)return Promise.resolve(b);const T=(()=>{const F={client:e.client,queryKey:e.queryKey,pageParam:j,direction:k?"backward":"forward",meta:e.options.meta};return x(F),F})(),w=await y(T),{maxPages:S}=e.options,M=k?vT:yT;return{pages:M(b.pages,w,S),pageParams:M(b.pageParams,j,S)}};if(r&&a.length){const b=r==="backward",j=b?DT:s1,k={pages:a,pageParams:l},E=j(s,k);o=await v(k,E,b)}else{const b=t??a.length;do{const j=c===0?l[0]??s.initialPageParam:s1(s,o);if(c>0&&j==null)break;o=await v(o,j),c++}while(c{var g,x;return(x=(g=e.options).persister)==null?void 0:x.call(g,d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n)}:e.fetchFn=d}}}function s1(t,{pages:e,pageParams:n}){const s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,n[s],n):void 0}function DT(t,{pages:e,pageParams:n}){var s;return e.length>0?(s=t.getPreviousPageParam)==null?void 0:s.call(t,e[0],e,n[0],n):void 0}var sd,Xs,Sn,ja,er,Jr,zN,MT=(zN=class extends yS{constructor(e){super();ge(this,er);ge(this,sd);ge(this,Xs);ge(this,Sn);ge(this,ja);re(this,sd,e.client),this.mutationId=e.mutationId,re(this,Sn,e.mutationCache),re(this,Xs,[]),this.state=e.state||jS(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){P(this,Xs).includes(e)||(P(this,Xs).push(e),this.clearGcTimeout(),P(this,Sn).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){re(this,Xs,P(this,Xs).filter(n=>n!==e)),this.scheduleGc(),P(this,Sn).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){P(this,Xs).length||(this.state.status==="pending"?this.scheduleGc():P(this,Sn).remove(this))}continue(){var e;return((e=P(this,ja))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var l,o,c,d,u,h,m,f,p,g,x,y,v,b,j,k,E,T,w,S;const n=()=>{Ce(this,er,Jr).call(this,{type:"continue"})},s={client:P(this,sd),meta:this.options.meta,mutationKey:this.options.mutationKey};re(this,ja,xS({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(M,F)=>{Ce(this,er,Jr).call(this,{type:"failed",failureCount:M,error:F})},onPause:()=>{Ce(this,er,Jr).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>P(this,Sn).canRun(this)}));const r=this.state.status==="pending",a=!P(this,ja).canStart();try{if(r)n();else{Ce(this,er,Jr).call(this,{type:"pending",variables:e,isPaused:a}),await((o=(l=P(this,Sn).config).onMutate)==null?void 0:o.call(l,e,this,s));const F=await((d=(c=this.options).onMutate)==null?void 0:d.call(c,e,s));F!==this.state.context&&Ce(this,er,Jr).call(this,{type:"pending",context:F,variables:e,isPaused:a})}const M=await P(this,ja).start();return await((h=(u=P(this,Sn).config).onSuccess)==null?void 0:h.call(u,M,e,this.state.context,this,s)),await((f=(m=this.options).onSuccess)==null?void 0:f.call(m,M,e,this.state.context,s)),await((g=(p=P(this,Sn).config).onSettled)==null?void 0:g.call(p,M,null,this.state.variables,this.state.context,this,s)),await((y=(x=this.options).onSettled)==null?void 0:y.call(x,M,null,e,this.state.context,s)),Ce(this,er,Jr).call(this,{type:"success",data:M}),M}catch(M){try{await((b=(v=P(this,Sn).config).onError)==null?void 0:b.call(v,M,e,this.state.context,this,s))}catch(F){Promise.reject(F)}try{await((k=(j=this.options).onError)==null?void 0:k.call(j,M,e,this.state.context,s))}catch(F){Promise.reject(F)}try{await((T=(E=P(this,Sn).config).onSettled)==null?void 0:T.call(E,void 0,M,this.state.variables,this.state.context,this,s))}catch(F){Promise.reject(F)}try{await((S=(w=this.options).onSettled)==null?void 0:S.call(w,void 0,M,e,this.state.context,s))}catch(F){Promise.reject(F)}throw Ce(this,er,Jr).call(this,{type:"error",error:M}),M}finally{P(this,Sn).runNext(this)}}},sd=new WeakMap,Xs=new WeakMap,Sn=new WeakMap,ja=new WeakMap,er=new WeakSet,Jr=function(e){const n=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Mt.batch(()=>{P(this,Xs).forEach(s=>{s.onMutationUpdate(e)}),P(this,Sn).notify({mutation:this,type:"updated",action:e})})},zN);function jS(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Sr,Ts,rd,$N,TT=($N=class extends Qa{constructor(e={}){super();ge(this,Sr);ge(this,Ts);ge(this,rd);this.config=e,re(this,Sr,new Set),re(this,Ts,new Map),re(this,rd,0)}build(e,n,s){const r=new MT({client:e,mutationCache:this,mutationId:++Dd(this,rd)._,options:e.defaultMutationOptions(n),state:s});return this.add(r),r}add(e){P(this,Sr).add(e);const n=Wd(e);if(typeof n=="string"){const s=P(this,Ts).get(n);s?s.push(e):P(this,Ts).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(P(this,Sr).delete(e)){const n=Wd(e);if(typeof n=="string"){const s=P(this,Ts).get(n);if(s)if(s.length>1){const r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&P(this,Ts).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){const n=Wd(e);if(typeof n=="string"){const s=P(this,Ts).get(n),r=s==null?void 0:s.find(a=>a.state.status==="pending");return!r||r===e}else return!0}runNext(e){var s;const n=Wd(e);if(typeof n=="string"){const r=(s=P(this,Ts).get(n))==null?void 0:s.find(a=>a!==e&&a.state.isPaused);return(r==null?void 0:r.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Mt.batch(()=>{P(this,Sr).forEach(e=>{this.notify({type:"removed",mutation:e})}),P(this,Sr).clear(),P(this,Ts).clear()})}getAll(){return Array.from(P(this,Sr))}find(e){const n={exact:!0,...e};return this.getAll().find(s=>Gb(n,s))}findAll(e={}){return this.getAll().filter(n=>Gb(e,n))}notify(e){Mt.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){const e=this.getAll().filter(n=>n.state.isPaused);return Mt.batch(()=>Promise.all(e.map(n=>n.continue().catch(xn))))}},Sr=new WeakMap,Ts=new WeakMap,rd=new WeakMap,$N);function Wd(t){var e;return(e=t.options.scope)==null?void 0:e.id}var Cr,pi,$n,Er,Lr,Nu,Cg,BN,PT=(BN=class extends Qa{constructor(n,s){super();ge(this,Lr);ge(this,Cr);ge(this,pi);ge(this,$n);ge(this,Er);re(this,Cr,n),this.setOptions(s),this.bindMethods(),Ce(this,Lr,Nu).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var r;const s=this.options;this.options=P(this,Cr).defaultMutationOptions(n),Lc(this.options,s)||P(this,Cr).getMutationCache().notify({type:"observerOptionsUpdated",mutation:P(this,$n),observer:this}),s!=null&&s.mutationKey&&this.options.mutationKey&&za(s.mutationKey)!==za(this.options.mutationKey)?this.reset():((r=P(this,$n))==null?void 0:r.state.status)==="pending"&&P(this,$n).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=P(this,$n))==null||n.removeObserver(this)}onMutationUpdate(n){Ce(this,Lr,Nu).call(this),Ce(this,Lr,Cg).call(this,n)}getCurrentResult(){return P(this,pi)}reset(){var n;(n=P(this,$n))==null||n.removeObserver(this),re(this,$n,void 0),Ce(this,Lr,Nu).call(this),Ce(this,Lr,Cg).call(this)}mutate(n,s){var r;return re(this,Er,s),(r=P(this,$n))==null||r.removeObserver(this),re(this,$n,P(this,Cr).getMutationCache().build(P(this,Cr),this.options)),P(this,$n).addObserver(this),P(this,$n).execute(n)}},Cr=new WeakMap,pi=new WeakMap,$n=new WeakMap,Er=new WeakMap,Lr=new WeakSet,Nu=function(){var s;const n=((s=P(this,$n))==null?void 0:s.state)??jS();re(this,pi,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},Cg=function(n){Mt.batch(()=>{var s,r,a,l,o,c,d,u;if(P(this,Er)&&this.hasListeners()){const h=P(this,pi).variables,m=P(this,pi).context,f={client:P(this,Cr),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(r=(s=P(this,Er)).onSuccess)==null||r.call(s,n.data,h,m,f)}catch(p){Promise.reject(p)}try{(l=(a=P(this,Er)).onSettled)==null||l.call(a,n.data,null,h,m,f)}catch(p){Promise.reject(p)}}else if((n==null?void 0:n.type)==="error"){try{(c=(o=P(this,Er)).onError)==null||c.call(o,n.error,h,m,f)}catch(p){Promise.reject(p)}try{(u=(d=P(this,Er)).onSettled)==null||u.call(d,void 0,n.error,h,m,f)}catch(p){Promise.reject(p)}}}this.listeners.forEach(h=>{h(P(this,pi))})})},BN);function r1(t,e){const n=new Set(e);return t.filter(s=>!n.has(s))}function IT(t,e,n){const s=t.slice(0);return s[e]=n,s}var $l,Xn,Bl,_l,gs,gi,id,ad,ld,od,hn,Eg,Ag,Dg,Mg,Tg,_N,RT=(_N=class extends Qa{constructor(e,n,s){super();ge(this,hn);ge(this,$l);ge(this,Xn);ge(this,Bl);ge(this,_l);ge(this,gs);ge(this,gi);ge(this,id);ge(this,ad);ge(this,ld);ge(this,od,[]);re(this,$l,e),re(this,_l,s),re(this,Bl,[]),re(this,gs,[]),re(this,Xn,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&P(this,gs).forEach(e=>{e.subscribe(n=>{Ce(this,hn,Mg).call(this,e,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,P(this,gs).forEach(e=>{e.destroy()})}setQueries(e,n){re(this,Bl,e),re(this,_l,n),Mt.batch(()=>{const s=P(this,gs),r=Ce(this,hn,Dg).call(this,P(this,Bl));r.forEach(h=>h.observer.setOptions(h.defaultedQueryOptions));const a=r.map(h=>h.observer),l=a.map(h=>h.getCurrentResult()),o=s.length!==a.length,c=a.some((h,m)=>h!==s[m]),d=o||c,u=d?!0:l.some((h,m)=>{const f=P(this,Xn)[m];return!f||!Lc(h,f)});!d&&!u||(d&&(re(this,od,r),re(this,gs,a)),re(this,Xn,l),this.hasListeners()&&(d&&(r1(s,a).forEach(h=>{h.destroy()}),r1(a,s).forEach(h=>{h.subscribe(m=>{Ce(this,hn,Mg).call(this,h,m)})})),Ce(this,hn,Tg).call(this)))})}getCurrentResult(){return P(this,Xn)}getQueries(){return P(this,gs).map(e=>e.getCurrentQuery())}getObservers(){return P(this,gs)}getOptimisticResult(e,n){const s=Ce(this,hn,Dg).call(this,e),r=s.map(l=>l.observer.getOptimisticResult(l.defaultedQueryOptions)),a=s.map(l=>l.defaultedQueryOptions.queryHash);return[r,l=>Ce(this,hn,Ag).call(this,l??r,n,a),()=>Ce(this,hn,Eg).call(this,r,s)]}},$l=new WeakMap,Xn=new WeakMap,Bl=new WeakMap,_l=new WeakMap,gs=new WeakMap,gi=new WeakMap,id=new WeakMap,ad=new WeakMap,ld=new WeakMap,od=new WeakMap,hn=new WeakSet,Eg=function(e,n){return n.map((s,r)=>{const a=e[r];return s.defaultedQueryOptions.notifyOnChangeProps?a:s.observer.trackResult(a,l=>{n.forEach(o=>{o.observer.trackProp(l)})})})},Ag=function(e,n,s){if(n){const r=P(this,ld),a=s!==void 0&&r!==void 0&&(r.length!==s.length||s.some((l,o)=>l!==r[o]));return(!P(this,gi)||P(this,Xn)!==P(this,ad)||a||n!==P(this,id))&&(re(this,id,n),re(this,ad,P(this,Xn)),s!==void 0&&re(this,ld,s),re(this,gi,Ny(P(this,gi),n(e)))),P(this,gi)}return e},Dg=function(e){const n=new Map;P(this,gs).forEach(r=>{const a=r.options.queryHash;if(!a)return;const l=n.get(a);l?l.push(r):n.set(a,[r])});const s=[];return e.forEach(r=>{var c;const a=P(this,$l).defaultQueryOptions(r),o=((c=n.get(a.queryHash))==null?void 0:c.shift())??new Cy(P(this,$l),a);s.push({defaultedQueryOptions:a,observer:o})}),s},Mg=function(e,n){const s=P(this,gs).indexOf(e);s!==-1&&(re(this,Xn,IT(P(this,Xn),s,n)),Ce(this,hn,Tg).call(this))},Tg=function(){var e;if(this.hasListeners()){const n=P(this,gi),s=Ce(this,hn,Eg).call(this,P(this,Xn),P(this,od)),r=Ce(this,hn,Ag).call(this,s,(e=P(this,_l))==null?void 0:e.combine);n!==r&&Mt.batch(()=>{this.listeners.forEach(a=>{a(P(this,Xn))})})}},_N),tr,VN,OT=(VN=class extends Qa{constructor(e={}){super();ge(this,tr);this.config=e,re(this,tr,new Map)}build(e,n,s){const r=n.queryKey,a=n.queryHash??jy(r,n);let l=this.get(a);return l||(l=new CT({client:e,queryKey:r,queryHash:a,options:e.defaultQueryOptions(n),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(l)),l}add(e){P(this,tr).has(e.queryHash)||(P(this,tr).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const n=P(this,tr).get(e.queryHash);n&&(e.destroy(),n===e&&P(this,tr).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Mt.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return P(this,tr).get(e)}getAll(){return[...P(this,tr).values()]}find(e){const n={exact:!0,...e};return this.getAll().find(s=>Qb(n,s))}findAll(e={}){const n=this.getAll();return Object.keys(e).length>0?n.filter(s=>Qb(e,s)):n}notify(e){Mt.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){Mt.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Mt.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},tr=new WeakMap,VN),St,xi,yi,Vl,Kl,vi,Ul,ql,KN,LT=(KN=class{constructor(t={}){ge(this,St);ge(this,xi);ge(this,yi);ge(this,Vl);ge(this,Kl);ge(this,vi);ge(this,Ul);ge(this,ql);re(this,St,t.queryCache||new OT),re(this,xi,t.mutationCache||new TT),re(this,yi,t.defaultOptions||{}),re(this,Vl,new Map),re(this,Kl,new Map),re(this,vi,0)}mount(){Dd(this,vi)._++,P(this,vi)===1&&(re(this,Ul,Sy.subscribe(async t=>{t&&(await this.resumePausedMutations(),P(this,St).onFocus())})),re(this,ql,ih.subscribe(async t=>{t&&(await this.resumePausedMutations(),P(this,St).onOnline())})))}unmount(){var t,e;Dd(this,vi)._--,P(this,vi)===0&&((t=P(this,Ul))==null||t.call(this),re(this,Ul,void 0),(e=P(this,ql))==null||e.call(this),re(this,ql,void 0))}isFetching(t){return P(this,St).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return P(this,xi).findAll({...t,status:"pending"}).length}getQueryData(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=P(this,St).get(e.queryHash))==null?void 0:n.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=P(this,St).build(this,e),s=n.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(Oi(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return P(this,St).findAll(t).map(({queryKey:e,state:n})=>{const s=n.data;return[e,s]})}setQueryData(t,e,n){const s=this.defaultQueryOptions({queryKey:t}),r=P(this,St).get(s.queryHash),a=r==null?void 0:r.state.data,l=pT(e,a);if(l!==void 0)return P(this,St).build(this,s).setData(l,{...n,manual:!0})}setQueriesData(t,e,n){return Mt.batch(()=>P(this,St).findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,n)]))}getQueryState(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=P(this,St).get(e.queryHash))==null?void 0:n.state}removeQueries(t){const e=P(this,St);Mt.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=P(this,St);return Mt.batch(()=>(n.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},s=Mt.batch(()=>P(this,St).findAll(t).map(r=>r.cancel(n)));return Promise.all(s).then(xn).catch(xn)}invalidateQueries(t,e={}){return Mt.batch(()=>(P(this,St).findAll(t).forEach(n=>{n.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const n={...e,cancelRefetch:e.cancelRefetch??!0},s=Mt.batch(()=>P(this,St).findAll(t).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let a=r.fetch(void 0,n);return n.throwOnError||(a=a.catch(xn)),r.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(s).then(xn)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=P(this,St).build(this,e);return n.isStaleByTime(Oi(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(xn).catch(xn)}fetchInfiniteQuery(t){return t.behavior=n1(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(xn).catch(xn)}ensureInfiniteQueryData(t){return t.behavior=n1(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return ih.isOnline()?P(this,xi).resumePausedMutations():Promise.resolve()}getQueryCache(){return P(this,St)}getMutationCache(){return P(this,xi)}getDefaultOptions(){return P(this,yi)}setDefaultOptions(t){re(this,yi,t)}setQueryDefaults(t,e){P(this,Vl).set(za(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...P(this,Vl).values()],n={};return e.forEach(s=>{Oc(t,s.queryKey)&&Object.assign(n,s.defaultOptions)}),n}setMutationDefaults(t,e){P(this,Kl).set(za(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...P(this,Kl).values()],n={};return e.forEach(s=>{Oc(t,s.mutationKey)&&Object.assign(n,s.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...P(this,yi).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=jy(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===wy&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...P(this,yi).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){P(this,St).clear(),P(this,xi).clear()}},St=new WeakMap,xi=new WeakMap,yi=new WeakMap,Vl=new WeakMap,Kl=new WeakMap,vi=new WeakMap,Ul=new WeakMap,ql=new WeakMap,KN),NS=N.createContext(void 0),ye=t=>{const e=N.useContext(NS);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},FT=({client:t,children:e})=>(N.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),i.jsx(NS.Provider,{value:t,children:e})),wS=N.createContext(!1),kS=()=>N.useContext(wS);wS.Provider;function zT(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var $T=N.createContext(zT()),SS=()=>N.useContext($T),CS=(t,e,n)=>{const s=n!=null&&n.state.error&&typeof t.throwOnError=="function"?ky(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},ES=t=>{N.useEffect(()=>{t.clearReset()},[t])},AS=({result:t,errorResetBoundary:e,throwOnError:n,query:s,suspense:r})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(r&&t.data===void 0||ky(n,[t.error,s])),DS=t=>{if(t.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),s=t.staleTime;t.staleTime=typeof s=="function"?(...r)=>n(s(...r)):n(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},MS=(t,e)=>t.isLoading&&t.isFetching&&!e,Pg=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,ah=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function BT({queries:t,...e},n){const s=ye(),r=kS(),a=SS(),l=N.useMemo(()=>t.map(g=>{const x=s.defaultQueryOptions(g);return x._optimisticResults=r?"isRestoring":"optimistic",x}),[t,s,r]);l.forEach(g=>{DS(g);const x=s.getQueryCache().get(g.queryHash);CS(g,a,x)}),ES(a);const[o]=N.useState(()=>new RT(s,l,e)),[c,d,u]=o.getOptimisticResult(l,e.combine),h=!r&&e.subscribed!==!1;N.useSyncExternalStore(N.useCallback(g=>h?o.subscribe(Mt.batchCalls(g)):xn,[o,h]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),N.useEffect(()=>{o.setQueries(l,e)},[l,e,o]);const f=c.some((g,x)=>Pg(l[x],g))?c.flatMap((g,x)=>{const y=l[x];if(y){const v=new Cy(s,y);if(Pg(y,g))return ah(y,v,a);MS(g,r)&&ah(y,v,a)}return[]}):[];if(f.length>0)throw Promise.all(f);const p=c.find((g,x)=>{const y=l[x];return y&&AS({result:g,errorResetBoundary:a,throwOnError:y.throwOnError,query:s.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(p!=null&&p.error)throw p.error;return d(u())}function _T(t,e,n){var m,f,p,g;const s=kS(),r=SS(),a=ye(),l=a.defaultQueryOptions(t);(f=(m=a.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||f.call(m,l);const o=a.getQueryCache().get(l.queryHash);l._optimisticResults=s?"isRestoring":"optimistic",DS(l),CS(l,r,o),ES(r);const c=!a.getQueryCache().get(l.queryHash),[d]=N.useState(()=>new e(a,l)),u=d.getOptimisticResult(l),h=!s&&t.subscribed!==!1;if(N.useSyncExternalStore(N.useCallback(x=>{const y=h?d.subscribe(Mt.batchCalls(x)):xn;return d.updateResult(),y},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),N.useEffect(()=>{d.setOptions(l)},[l,d]),Pg(l,u))throw ah(l,d,r);if(AS({result:u,errorResetBoundary:r,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw u.error;if((g=(p=a.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||g.call(p,l,u),l.experimental_prefetchInRender&&!Fa&&MS(u,s)){const x=c?ah(l,d,r):o==null?void 0:o.promise;x==null||x.catch(xn).finally(()=>{d.updateResult()})}return l.notifyOnChangeProps?u:d.trackResult(u)}function fe(t,e){return _T(t,Cy)}function G(t,e){const n=ye(),[s]=N.useState(()=>new PT(n,t));N.useEffect(()=>{s.setOptions(t)},[s,t]);const r=N.useSyncExternalStore(N.useCallback(l=>s.subscribe(Mt.batchCalls(l)),[s]),()=>s.getCurrentResult(),()=>s.getCurrentResult()),a=N.useCallback((l,o)=>{s.mutate(l,o).catch(xn)},[s]);if(r.error&&ky(s.options.throwOnError,[r.error]))throw r.error;return{...r,mutate:a,mutateAsync:r.mutate}}let VT={data:""},KT=t=>{if(typeof window=="object"){let e=(t?t.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return e.nonce=window.__nonce__,e.parentNode||(t||document.head).appendChild(e),e.firstChild}return t||VT},UT=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,qT=/\/\*[^]*?\*\/| +/g,i1=/\n+/g,ii=(t,e)=>{let n="",s="",r="";for(let a in t){let l=t[a];a[0]=="@"?a[1]=="i"?n=a+" "+l+";":s+=a[1]=="f"?ii(l,a):a+"{"+ii(l,a[1]=="k"?"":e)+"}":typeof l=="object"?s+=ii(l,e?e.replace(/([^,])+/g,o=>a.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,c=>/&/.test(c)?c.replace(/&/g,o):o?o+" "+c:c)):a):l!=null&&(a=/^--/.test(a)?a:a.replace(/[A-Z]/g,"-$&").toLowerCase(),r+=ii.p?ii.p(a,l):a+":"+l+";")}return n+(e&&r?e+"{"+r+"}":r)+s},fr={},TS=t=>{if(typeof t=="object"){let e="";for(let n in t)e+=n+TS(t[n]);return e}return t},HT=(t,e,n,s,r)=>{let a=TS(t),l=fr[a]||(fr[a]=(c=>{let d=0,u=11;for(;d>>0;return"go"+u})(a));if(!fr[l]){let c=a!==t?t:(d=>{let u,h,m=[{}];for(;u=UT.exec(d.replace(qT,""));)u[4]?m.shift():u[3]?(h=u[3].replace(i1," ").trim(),m.unshift(m[0][h]=m[0][h]||{})):m[0][u[1]]=u[2].replace(i1," ").trim();return m[0]})(t);fr[l]=ii(r?{["@keyframes "+l]:c}:c,n?"":"."+l)}let o=n&&fr.g?fr.g:null;return n&&(fr.g=fr[l]),((c,d,u,h)=>{h?d.data=d.data.replace(h,c):d.data.indexOf(c)===-1&&(d.data=u?c+d.data:d.data+c)})(fr[l],e,s,o),l},WT=(t,e,n)=>t.reduce((s,r,a)=>{let l=e[a];if(l&&l.call){let o=l(n),c=o&&o.props&&o.props.className||/^go/.test(o)&&o;l=c?"."+c:o&&typeof o=="object"?o.props?"":ii(o,""):o===!1?"":o}return s+r+(l??"")},"");function Cf(t){let e=this||{},n=t.call?t(e.p):t;return HT(n.unshift?n.raw?WT(n,[].slice.call(arguments,1),e.p):n.reduce((s,r)=>Object.assign(s,r&&r.call?r(e.p):r),{}):n,KT(e.target),e.g,e.o,e.k)}let PS,Ig,Rg;Cf.bind({g:1});let _r=Cf.bind({k:1});function QT(t,e,n,s){ii.p=e,PS=t,Ig=n,Rg=s}function Wi(t,e){let n=this||{};return function(){let s=arguments;function r(a,l){let o=Object.assign({},a),c=o.className||r.className;n.p=Object.assign({theme:Ig&&Ig()},o),n.o=/ *go\d+/.test(c),o.className=Cf.apply(n,s)+(c?" "+c:"");let d=t;return t[0]&&(d=o.as||t,delete o.as),Rg&&d[0]&&Rg(o),PS(d,o)}return r}}var GT=t=>typeof t=="function",lh=(t,e)=>GT(t)?t(e):t,JT=(()=>{let t=0;return()=>(++t).toString()})(),IS=(()=>{let t;return()=>{if(t===void 0&&typeof window<"u"){let e=matchMedia("(prefers-reduced-motion: reduce)");t=!e||e.matches}return t}})(),ZT=20,Ay="default",RS=(t,e)=>{let{toastLimit:n}=t.settings;switch(e.type){case 0:return{...t,toasts:[e.toast,...t.toasts].slice(0,n)};case 1:return{...t,toasts:t.toasts.map(l=>l.id===e.toast.id?{...l,...e.toast}:l)};case 2:let{toast:s}=e;return RS(t,{type:t.toasts.find(l=>l.id===s.id)?1:0,toast:s});case 3:let{toastId:r}=e;return{...t,toasts:t.toasts.map(l=>l.id===r||r===void 0?{...l,dismissed:!0,visible:!1}:l)};case 4:return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(l=>l.id!==e.toastId)};case 5:return{...t,pausedAt:e.time};case 6:let a=e.time-(t.pausedAt||0);return{...t,pausedAt:void 0,toasts:t.toasts.map(l=>({...l,pauseDuration:l.pauseDuration+a}))}}},wu=[],OS={toasts:[],pausedAt:void 0,settings:{toastLimit:ZT}},sr={},LS=(t,e=Ay)=>{sr[e]=RS(sr[e]||OS,t),wu.forEach(([n,s])=>{n===e&&s(sr[e])})},FS=t=>Object.keys(sr).forEach(e=>LS(t,e)),YT=t=>Object.keys(sr).find(e=>sr[e].toasts.some(n=>n.id===t)),Ef=(t=Ay)=>e=>{LS(e,t)},XT={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},eP=(t={},e=Ay)=>{let[n,s]=N.useState(sr[e]||OS),r=N.useRef(sr[e]);N.useEffect(()=>(r.current!==sr[e]&&s(sr[e]),wu.push([e,s]),()=>{let l=wu.findIndex(([o])=>o===e);l>-1&&wu.splice(l,1)}),[e]);let a=n.toasts.map(l=>{var o,c,d;return{...t,...t[l.type],...l,removeDelay:l.removeDelay||((o=t[l.type])==null?void 0:o.removeDelay)||(t==null?void 0:t.removeDelay),duration:l.duration||((c=t[l.type])==null?void 0:c.duration)||(t==null?void 0:t.duration)||XT[l.type],style:{...t.style,...(d=t[l.type])==null?void 0:d.style,...l.style}}});return{...n,toasts:a}},tP=(t,e="blank",n)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:e,ariaProps:{role:"status","aria-live":"polite"},message:t,pauseDuration:0,...n,id:(n==null?void 0:n.id)||JT()}),pd=t=>(e,n)=>{let s=tP(e,t,n);return Ef(s.toasterId||YT(s.id))({type:2,toast:s}),s.id},Ut=(t,e)=>pd("blank")(t,e);Ut.error=pd("error");Ut.success=pd("success");Ut.loading=pd("loading");Ut.custom=pd("custom");Ut.dismiss=(t,e)=>{let n={type:3,toastId:t};e?Ef(e)(n):FS(n)};Ut.dismissAll=t=>Ut.dismiss(void 0,t);Ut.remove=(t,e)=>{let n={type:4,toastId:t};e?Ef(e)(n):FS(n)};Ut.removeAll=t=>Ut.remove(void 0,t);Ut.promise=(t,e,n)=>{let s=Ut.loading(e.loading,{...n,...n==null?void 0:n.loading});return typeof t=="function"&&(t=t()),t.then(r=>{let a=e.success?lh(e.success,r):void 0;return a?Ut.success(a,{id:s,...n,...n==null?void 0:n.success}):Ut.dismiss(s),r}).catch(r=>{let a=e.error?lh(e.error,r):void 0;a?Ut.error(a,{id:s,...n,...n==null?void 0:n.error}):Ut.dismiss(s)}),t};var nP=1e3,sP=(t,e="default")=>{let{toasts:n,pausedAt:s}=eP(t,e),r=N.useRef(new Map).current,a=N.useCallback((h,m=nP)=>{if(r.has(h))return;let f=setTimeout(()=>{r.delete(h),l({type:4,toastId:h})},m);r.set(h,f)},[]);N.useEffect(()=>{if(s)return;let h=Date.now(),m=n.map(f=>{if(f.duration===1/0)return;let p=(f.duration||0)+f.pauseDuration-(h-f.createdAt);if(p<0){f.visible&&Ut.dismiss(f.id);return}return setTimeout(()=>Ut.dismiss(f.id,e),p)});return()=>{m.forEach(f=>f&&clearTimeout(f))}},[n,s,e]);let l=N.useCallback(Ef(e),[e]),o=N.useCallback(()=>{l({type:5,time:Date.now()})},[l]),c=N.useCallback((h,m)=>{l({type:1,toast:{id:h,height:m}})},[l]),d=N.useCallback(()=>{s&&l({type:6,time:Date.now()})},[s,l]),u=N.useCallback((h,m)=>{let{reverseOrder:f=!1,gutter:p=8,defaultPosition:g}=m||{},x=n.filter(b=>(b.position||g)===(h.position||g)&&b.height),y=x.findIndex(b=>b.id===h.id),v=x.filter((b,j)=>jb.visible).slice(...f?[v+1]:[0,v]).reduce((b,j)=>b+(j.height||0)+p,0)},[n]);return N.useEffect(()=>{n.forEach(h=>{if(h.dismissed)a(h.id,h.removeDelay);else{let m=r.get(h.id);m&&(clearTimeout(m),r.delete(h.id))}})},[n,a]),{toasts:n,handlers:{updateHeight:c,startPause:o,endPause:d,calculateOffset:u}}},rP=_r` +from { + transform: scale(0) rotate(45deg); + opacity: 0; +} +to { + transform: scale(1) rotate(45deg); + opacity: 1; +}`,iP=_r` +from { + transform: scale(0); + opacity: 0; +} +to { + transform: scale(1); + opacity: 1; +}`,aP=_r` +from { + transform: scale(0) rotate(90deg); + opacity: 0; +} +to { + transform: scale(1) rotate(90deg); + opacity: 1; +}`,lP=Wi("div")` + width: 20px; + opacity: 0; + height: 20px; + border-radius: 10px; + background: ${t=>t.primary||"#ff4b4b"}; + position: relative; + transform: rotate(45deg); + + animation: ${rP} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; + animation-delay: 100ms; + + &:after, + &:before { + content: ''; + animation: ${iP} 0.15s ease-out forwards; + animation-delay: 150ms; + position: absolute; + border-radius: 3px; + opacity: 0; + background: ${t=>t.secondary||"#fff"}; + bottom: 9px; + left: 4px; + height: 2px; + width: 12px; + } + + &:before { + animation: ${aP} 0.15s ease-out forwards; + animation-delay: 180ms; + transform: rotate(90deg); + } +`,oP=_r` + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +`,cP=Wi("div")` + width: 12px; + height: 12px; + box-sizing: border-box; + border: 2px solid; + border-radius: 100%; + border-color: ${t=>t.secondary||"#e0e0e0"}; + border-right-color: ${t=>t.primary||"#616161"}; + animation: ${oP} 1s linear infinite; +`,dP=_r` +from { + transform: scale(0) rotate(45deg); + opacity: 0; +} +to { + transform: scale(1) rotate(45deg); + opacity: 1; +}`,uP=_r` +0% { + height: 0; + width: 0; + opacity: 0; +} +40% { + height: 0; + width: 6px; + opacity: 1; +} +100% { + opacity: 1; + height: 10px; +}`,hP=Wi("div")` + width: 20px; + opacity: 0; + height: 20px; + border-radius: 10px; + background: ${t=>t.primary||"#61d345"}; + position: relative; + transform: rotate(45deg); + + animation: ${dP} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; + animation-delay: 100ms; + &:after { + content: ''; + box-sizing: border-box; + animation: ${uP} 0.2s ease-out forwards; + opacity: 0; + animation-delay: 200ms; + position: absolute; + border-right: 2px solid; + border-bottom: 2px solid; + border-color: ${t=>t.secondary||"#fff"}; + bottom: 6px; + left: 6px; + height: 10px; + width: 6px; + } +`,fP=Wi("div")` + position: absolute; +`,mP=Wi("div")` + position: relative; + display: flex; + justify-content: center; + align-items: center; + min-width: 20px; + min-height: 20px; +`,pP=_r` +from { + transform: scale(0.6); + opacity: 0.4; +} +to { + transform: scale(1); + opacity: 1; +}`,gP=Wi("div")` + position: relative; + transform: scale(0.6); + opacity: 0.4; + min-width: 20px; + animation: ${pP} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; +`,xP=({toast:t})=>{let{icon:e,type:n,iconTheme:s}=t;return e!==void 0?typeof e=="string"?N.createElement(gP,null,e):e:n==="blank"?null:N.createElement(mP,null,N.createElement(cP,{...s}),n!=="loading"&&N.createElement(fP,null,n==="error"?N.createElement(lP,{...s}):N.createElement(hP,{...s})))},yP=t=>` +0% {transform: translate3d(0,${t*-200}%,0) scale(.6); opacity:.5;} +100% {transform: translate3d(0,0,0) scale(1); opacity:1;} +`,vP=t=>` +0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} +100% {transform: translate3d(0,${t*-150}%,-1px) scale(.6); opacity:0;} +`,bP="0%{opacity:0;} 100%{opacity:1;}",jP="0%{opacity:1;} 100%{opacity:0;}",NP=Wi("div")` + display: flex; + align-items: center; + background: #fff; + color: #363636; + line-height: 1.3; + will-change: transform; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05); + max-width: 350px; + pointer-events: auto; + padding: 8px 10px; + border-radius: 8px; +`,wP=Wi("div")` + display: flex; + justify-content: center; + margin: 4px 10px; + color: inherit; + flex: 1 1 auto; + white-space: pre-line; +`,kP=(t,e)=>{let n=t.includes("top")?1:-1,[s,r]=IS()?[bP,jP]:[yP(n),vP(n)];return{animation:e?`${_r(s)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${_r(r)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},SP=N.memo(({toast:t,position:e,style:n,children:s})=>{let r=t.height?kP(t.position||e||"top-center",t.visible):{opacity:0},a=N.createElement(xP,{toast:t}),l=N.createElement(wP,{...t.ariaProps},lh(t.message,t));return N.createElement(NP,{className:t.className,style:{...r,...n,...t.style}},typeof s=="function"?s({icon:a,message:l}):N.createElement(N.Fragment,null,a,l))});QT(N.createElement);var CP=({id:t,className:e,style:n,onHeightUpdate:s,children:r})=>{let a=N.useCallback(l=>{if(l){let o=()=>{let c=l.getBoundingClientRect().height;s(t,c)};o(),new MutationObserver(o).observe(l,{subtree:!0,childList:!0,characterData:!0})}},[t,s]);return N.createElement("div",{ref:a,className:e,style:n},r)},EP=(t,e)=>{let n=t.includes("top"),s=n?{top:0}:{bottom:0},r=t.includes("center")?{justifyContent:"center"}:t.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:IS()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${e*(n?1:-1)}px)`,...s,...r}},AP=Cf` + z-index: 9999; + > * { + pointer-events: auto; + } +`,Qd=16,DP=({reverseOrder:t,position:e="top-center",toastOptions:n,gutter:s,children:r,toasterId:a,containerStyle:l,containerClassName:o})=>{let{toasts:c,handlers:d}=sP(n,a);return N.createElement("div",{"data-rht-toaster":a||"",style:{position:"fixed",zIndex:9999,top:Qd,left:Qd,right:Qd,bottom:Qd,pointerEvents:"none",...l},className:o,onMouseEnter:d.startPause,onMouseLeave:d.endPause},c.map(u=>{let h=u.position||e,m=d.calculateOffset(u,{reverseOrder:t,gutter:s,defaultPosition:e}),f=EP(h,m);return N.createElement(CP,{id:u.id,key:u.id,onHeightUpdate:d.updateHeight,className:u.visible?AP:"",style:f},u.type==="custom"?lh(u.message,u):r?r(u):N.createElement(SP,{toast:u,position:h}))}))},Ue=Ut;function zS(t,e){return function(){return t.apply(e,arguments)}}const{toString:MP}=Object.prototype,{getPrototypeOf:Dy}=Object,{iterator:Af,toStringTag:$S}=Symbol,Df=(t=>e=>{const n=MP.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Ks=t=>(t=t.toLowerCase(),e=>Df(e)===t),Mf=t=>e=>typeof e===t,{isArray:go}=Array,eo=Mf("undefined");function gd(t){return t!==null&&!eo(t)&&t.constructor!==null&&!eo(t.constructor)&&Gn(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const BS=Ks("ArrayBuffer");function TP(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&BS(t.buffer),e}const PP=Mf("string"),Gn=Mf("function"),_S=Mf("number"),xd=t=>t!==null&&typeof t=="object",IP=t=>t===!0||t===!1,ku=t=>{if(Df(t)!=="object")return!1;const e=Dy(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!($S in t)&&!(Af in t)},RP=t=>{if(!xd(t)||gd(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},OP=Ks("Date"),LP=Ks("File"),FP=Ks("Blob"),zP=Ks("FileList"),$P=t=>xd(t)&&Gn(t.pipe),BP=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Gn(t.append)&&((e=Df(t))==="formdata"||e==="object"&&Gn(t.toString)&&t.toString()==="[object FormData]"))},_P=Ks("URLSearchParams"),[VP,KP,UP,qP]=["ReadableStream","Request","Response","Headers"].map(Ks),HP=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function yd(t,e,{allOwnKeys:n=!1}={}){if(t===null||typeof t>"u")return;let s,r;if(typeof t!="object"&&(t=[t]),go(t))for(s=0,r=t.length;s0;)if(r=n[s],e===r.toLowerCase())return r;return null}const aa=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,KS=t=>!eo(t)&&t!==aa;function Og(){const{caseless:t,skipUndefined:e}=KS(this)&&this||{},n={},s=(r,a)=>{const l=t&&VS(n,a)||a;ku(n[l])&&ku(r)?n[l]=Og(n[l],r):ku(r)?n[l]=Og({},r):go(r)?n[l]=r.slice():(!e||!eo(r))&&(n[l]=r)};for(let r=0,a=arguments.length;r(yd(e,(r,a)=>{n&&Gn(r)?t[a]=zS(r,n):t[a]=r},{allOwnKeys:s}),t),QP=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),GP=(t,e,n,s)=>{t.prototype=Object.create(e.prototype,s),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},JP=(t,e,n,s)=>{let r,a,l;const o={};if(e=e||{},t==null)return e;do{for(r=Object.getOwnPropertyNames(t),a=r.length;a-- >0;)l=r[a],(!s||s(l,t,e))&&!o[l]&&(e[l]=t[l],o[l]=!0);t=n!==!1&&Dy(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},ZP=(t,e,n)=>{t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;const s=t.indexOf(e,n);return s!==-1&&s===n},YP=t=>{if(!t)return null;if(go(t))return t;let e=t.length;if(!_S(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},XP=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Dy(Uint8Array)),eI=(t,e)=>{const s=(t&&t[Af]).call(t);let r;for(;(r=s.next())&&!r.done;){const a=r.value;e.call(t,a[0],a[1])}},tI=(t,e)=>{let n;const s=[];for(;(n=t.exec(e))!==null;)s.push(n);return s},nI=Ks("HTMLFormElement"),sI=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,s,r){return s.toUpperCase()+r}),a1=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),rI=Ks("RegExp"),US=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),s={};yd(n,(r,a)=>{let l;(l=e(r,a,t))!==!1&&(s[a]=l||r)}),Object.defineProperties(t,s)},iI=t=>{US(t,(e,n)=>{if(Gn(t)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const s=t[n];if(Gn(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},aI=(t,e)=>{const n={},s=r=>{r.forEach(a=>{n[a]=!0})};return go(t)?s(t):s(String(t).split(e)),n},lI=()=>{},oI=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function cI(t){return!!(t&&Gn(t.append)&&t[$S]==="FormData"&&t[Af])}const dI=t=>{const e=new Array(10),n=(s,r)=>{if(xd(s)){if(e.indexOf(s)>=0)return;if(gd(s))return s;if(!("toJSON"in s)){e[r]=s;const a=go(s)?[]:{};return yd(s,(l,o)=>{const c=n(l,r+1);!eo(c)&&(a[o]=c)}),e[r]=void 0,a}}return s};return n(t,0)},uI=Ks("AsyncFunction"),hI=t=>t&&(xd(t)||Gn(t))&&Gn(t.then)&&Gn(t.catch),qS=((t,e)=>t?setImmediate:e?((n,s)=>(aa.addEventListener("message",({source:r,data:a})=>{r===aa&&a===n&&s.length&&s.shift()()},!1),r=>{s.push(r),aa.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Gn(aa.postMessage)),fI=typeof queueMicrotask<"u"?queueMicrotask.bind(aa):typeof process<"u"&&process.nextTick||qS,mI=t=>t!=null&&Gn(t[Af]),H={isArray:go,isArrayBuffer:BS,isBuffer:gd,isFormData:BP,isArrayBufferView:TP,isString:PP,isNumber:_S,isBoolean:IP,isObject:xd,isPlainObject:ku,isEmptyObject:RP,isReadableStream:VP,isRequest:KP,isResponse:UP,isHeaders:qP,isUndefined:eo,isDate:OP,isFile:LP,isBlob:FP,isRegExp:rI,isFunction:Gn,isStream:$P,isURLSearchParams:_P,isTypedArray:XP,isFileList:zP,forEach:yd,merge:Og,extend:WP,trim:HP,stripBOM:QP,inherits:GP,toFlatObject:JP,kindOf:Df,kindOfTest:Ks,endsWith:ZP,toArray:YP,forEachEntry:eI,matchAll:tI,isHTMLForm:nI,hasOwnProperty:a1,hasOwnProp:a1,reduceDescriptors:US,freezeMethods:iI,toObjectSet:aI,toCamelCase:sI,noop:lI,toFiniteNumber:oI,findKey:VS,global:aa,isContextDefined:KS,isSpecCompliantForm:cI,toJSONObject:dI,isAsyncFn:uI,isThenable:hI,setImmediate:qS,asap:fI,isIterable:mI};function Te(t,e,n,s,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),s&&(this.request=s),r&&(this.response=r,this.status=r.status?r.status:null)}H.inherits(Te,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:H.toJSONObject(this.config),code:this.code,status:this.status}}});const HS=Te.prototype,WS={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{WS[t]={value:t}});Object.defineProperties(Te,WS);Object.defineProperty(HS,"isAxiosError",{value:!0});Te.from=(t,e,n,s,r,a)=>{const l=Object.create(HS);H.toFlatObject(t,l,function(u){return u!==Error.prototype},d=>d!=="isAxiosError");const o=t&&t.message?t.message:"Error",c=e==null&&t?t.code:e;return Te.call(l,o,c,n,s,r),t&&l.cause==null&&Object.defineProperty(l,"cause",{value:t,configurable:!0}),l.name=t&&t.name||"Error",a&&Object.assign(l,a),l};const pI=null;function Lg(t){return H.isPlainObject(t)||H.isArray(t)}function QS(t){return H.endsWith(t,"[]")?t.slice(0,-2):t}function l1(t,e,n){return t?t.concat(e).map(function(r,a){return r=QS(r),!n&&a?"["+r+"]":r}).join(n?".":""):e}function gI(t){return H.isArray(t)&&!t.some(Lg)}const xI=H.toFlatObject(H,{},null,function(e){return/^is[A-Z]/.test(e)});function Tf(t,e,n){if(!H.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,n=H.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,x){return!H.isUndefined(x[g])});const s=n.metaTokens,r=n.visitor||u,a=n.dots,l=n.indexes,c=(n.Blob||typeof Blob<"u"&&Blob)&&H.isSpecCompliantForm(e);if(!H.isFunction(r))throw new TypeError("visitor must be a function");function d(p){if(p===null)return"";if(H.isDate(p))return p.toISOString();if(H.isBoolean(p))return p.toString();if(!c&&H.isBlob(p))throw new Te("Blob is not supported. Use a Buffer instead.");return H.isArrayBuffer(p)||H.isTypedArray(p)?c&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,g,x){let y=p;if(p&&!x&&typeof p=="object"){if(H.endsWith(g,"{}"))g=s?g:g.slice(0,-2),p=JSON.stringify(p);else if(H.isArray(p)&&gI(p)||(H.isFileList(p)||H.endsWith(g,"[]"))&&(y=H.toArray(p)))return g=QS(g),y.forEach(function(b,j){!(H.isUndefined(b)||b===null)&&e.append(l===!0?l1([g],j,a):l===null?g:g+"[]",d(b))}),!1}return Lg(p)?!0:(e.append(l1(x,g,a),d(p)),!1)}const h=[],m=Object.assign(xI,{defaultVisitor:u,convertValue:d,isVisitable:Lg});function f(p,g){if(!H.isUndefined(p)){if(h.indexOf(p)!==-1)throw Error("Circular reference detected in "+g.join("."));h.push(p),H.forEach(p,function(y,v){(!(H.isUndefined(y)||y===null)&&r.call(e,y,H.isString(v)?v.trim():v,g,m))===!0&&f(y,g?g.concat(v):[v])}),h.pop()}}if(!H.isObject(t))throw new TypeError("data must be an object");return f(t),e}function o1(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(s){return e[s]})}function My(t,e){this._pairs=[],t&&Tf(t,this,e)}const GS=My.prototype;GS.append=function(e,n){this._pairs.push([e,n])};GS.toString=function(e){const n=e?function(s){return e.call(this,s,o1)}:o1;return this._pairs.map(function(r){return n(r[0])+"="+n(r[1])},"").join("&")};function yI(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function JS(t,e,n){if(!e)return t;const s=n&&n.encode||yI;H.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let a;if(r?a=r(e,n):a=H.isURLSearchParams(e)?e.toString():new My(e,n).toString(s),a){const l=t.indexOf("#");l!==-1&&(t=t.slice(0,l)),t+=(t.indexOf("?")===-1?"?":"&")+a}return t}class c1{constructor(){this.handlers=[]}use(e,n,s){return this.handlers.push({fulfilled:e,rejected:n,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){H.forEach(this.handlers,function(s){s!==null&&e(s)})}}const ZS={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},vI=typeof URLSearchParams<"u"?URLSearchParams:My,bI=typeof FormData<"u"?FormData:null,jI=typeof Blob<"u"?Blob:null,NI={isBrowser:!0,classes:{URLSearchParams:vI,FormData:bI,Blob:jI},protocols:["http","https","file","blob","url","data"]},Ty=typeof window<"u"&&typeof document<"u",Fg=typeof navigator=="object"&&navigator||void 0,wI=Ty&&(!Fg||["ReactNative","NativeScript","NS"].indexOf(Fg.product)<0),kI=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",SI=Ty&&window.location.href||"http://localhost",CI=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ty,hasStandardBrowserEnv:wI,hasStandardBrowserWebWorkerEnv:kI,navigator:Fg,origin:SI},Symbol.toStringTag,{value:"Module"})),vn={...CI,...NI};function EI(t,e){return Tf(t,new vn.classes.URLSearchParams,{visitor:function(n,s,r,a){return vn.isNode&&H.isBuffer(n)?(this.append(s,n.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...e})}function AI(t){return H.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function DI(t){const e={},n=Object.keys(t);let s;const r=n.length;let a;for(s=0;s=n.length;return l=!l&&H.isArray(r)?r.length:l,c?(H.hasOwnProp(r,l)?r[l]=[r[l],s]:r[l]=s,!o):((!r[l]||!H.isObject(r[l]))&&(r[l]=[]),e(n,s,r[l],a)&&H.isArray(r[l])&&(r[l]=DI(r[l])),!o)}if(H.isFormData(t)&&H.isFunction(t.entries)){const n={};return H.forEachEntry(t,(s,r)=>{e(AI(s),r,n,0)}),n}return null}function MI(t,e,n){if(H.isString(t))try{return(e||JSON.parse)(t),H.trim(t)}catch(s){if(s.name!=="SyntaxError")throw s}return(n||JSON.stringify)(t)}const vd={transitional:ZS,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const s=n.getContentType()||"",r=s.indexOf("application/json")>-1,a=H.isObject(e);if(a&&H.isHTMLForm(e)&&(e=new FormData(e)),H.isFormData(e))return r?JSON.stringify(YS(e)):e;if(H.isArrayBuffer(e)||H.isBuffer(e)||H.isStream(e)||H.isFile(e)||H.isBlob(e)||H.isReadableStream(e))return e;if(H.isArrayBufferView(e))return e.buffer;if(H.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(a){if(s.indexOf("application/x-www-form-urlencoded")>-1)return EI(e,this.formSerializer).toString();if((o=H.isFileList(e))||s.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return Tf(o?{"files[]":e}:e,c&&new c,this.formSerializer)}}return a||r?(n.setContentType("application/json",!1),MI(e)):e}],transformResponse:[function(e){const n=this.transitional||vd.transitional,s=n&&n.forcedJSONParsing,r=this.responseType==="json";if(H.isResponse(e)||H.isReadableStream(e))return e;if(e&&H.isString(e)&&(s&&!this.responseType||r)){const l=!(n&&n.silentJSONParsing)&&r;try{return JSON.parse(e,this.parseReviver)}catch(o){if(l)throw o.name==="SyntaxError"?Te.from(o,Te.ERR_BAD_RESPONSE,this,null,this.response):o}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:vn.classes.FormData,Blob:vn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};H.forEach(["delete","get","head","post","put","patch"],t=>{vd.headers[t]={}});const TI=H.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),PI=t=>{const e={};let n,s,r;return t&&t.split(` +`).forEach(function(l){r=l.indexOf(":"),n=l.substring(0,r).trim().toLowerCase(),s=l.substring(r+1).trim(),!(!n||e[n]&&TI[n])&&(n==="set-cookie"?e[n]?e[n].push(s):e[n]=[s]:e[n]=e[n]?e[n]+", "+s:s)}),e},d1=Symbol("internals");function Po(t){return t&&String(t).trim().toLowerCase()}function Su(t){return t===!1||t==null?t:H.isArray(t)?t.map(Su):String(t)}function II(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(t);)e[s[1]]=s[2];return e}const RI=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function Dm(t,e,n,s,r){if(H.isFunction(s))return s.call(this,e,n);if(r&&(e=n),!!H.isString(e)){if(H.isString(s))return e.indexOf(s)!==-1;if(H.isRegExp(s))return s.test(e)}}function OI(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,s)=>n.toUpperCase()+s)}function LI(t,e){const n=H.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(t,s+n,{value:function(r,a,l){return this[s].call(this,e,r,a,l)},configurable:!0})})}let Jn=class{constructor(e){e&&this.set(e)}set(e,n,s){const r=this;function a(o,c,d){const u=Po(c);if(!u)throw new Error("header name must be a non-empty string");const h=H.findKey(r,u);(!h||r[h]===void 0||d===!0||d===void 0&&r[h]!==!1)&&(r[h||c]=Su(o))}const l=(o,c)=>H.forEach(o,(d,u)=>a(d,u,c));if(H.isPlainObject(e)||e instanceof this.constructor)l(e,n);else if(H.isString(e)&&(e=e.trim())&&!RI(e))l(PI(e),n);else if(H.isObject(e)&&H.isIterable(e)){let o={},c,d;for(const u of e){if(!H.isArray(u))throw TypeError("Object iterator must return a key-value pair");o[d=u[0]]=(c=o[d])?H.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}l(o,n)}else e!=null&&a(n,e,s);return this}get(e,n){if(e=Po(e),e){const s=H.findKey(this,e);if(s){const r=this[s];if(!n)return r;if(n===!0)return II(r);if(H.isFunction(n))return n.call(this,r,s);if(H.isRegExp(n))return n.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=Po(e),e){const s=H.findKey(this,e);return!!(s&&this[s]!==void 0&&(!n||Dm(this,this[s],s,n)))}return!1}delete(e,n){const s=this;let r=!1;function a(l){if(l=Po(l),l){const o=H.findKey(s,l);o&&(!n||Dm(s,s[o],o,n))&&(delete s[o],r=!0)}}return H.isArray(e)?e.forEach(a):a(e),r}clear(e){const n=Object.keys(this);let s=n.length,r=!1;for(;s--;){const a=n[s];(!e||Dm(this,this[a],a,e,!0))&&(delete this[a],r=!0)}return r}normalize(e){const n=this,s={};return H.forEach(this,(r,a)=>{const l=H.findKey(s,a);if(l){n[l]=Su(r),delete n[a];return}const o=e?OI(a):String(a).trim();o!==a&&delete n[a],n[o]=Su(r),s[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return H.forEach(this,(s,r)=>{s!=null&&s!==!1&&(n[r]=e&&H.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const s=new this(e);return n.forEach(r=>s.set(r)),s}static accessor(e){const s=(this[d1]=this[d1]={accessors:{}}).accessors,r=this.prototype;function a(l){const o=Po(l);s[o]||(LI(r,l),s[o]=!0)}return H.isArray(e)?e.forEach(a):a(e),this}};Jn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);H.reduceDescriptors(Jn.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(s){this[n]=s}}});H.freezeMethods(Jn);function Mm(t,e){const n=this||vd,s=e||n,r=Jn.from(s.headers);let a=s.data;return H.forEach(t,function(o){a=o.call(n,a,r.normalize(),e?e.status:void 0)}),r.normalize(),a}function XS(t){return!!(t&&t.__CANCEL__)}function xo(t,e,n){Te.call(this,t??"canceled",Te.ERR_CANCELED,e,n),this.name="CanceledError"}H.inherits(xo,Te,{__CANCEL__:!0});function eC(t,e,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?t(n):e(new Te("Request failed with status code "+n.status,[Te.ERR_BAD_REQUEST,Te.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function FI(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function zI(t,e){t=t||10;const n=new Array(t),s=new Array(t);let r=0,a=0,l;return e=e!==void 0?e:1e3,function(c){const d=Date.now(),u=s[a];l||(l=d),n[r]=c,s[r]=d;let h=a,m=0;for(;h!==r;)m+=n[h++],h=h%t;if(r=(r+1)%t,r===a&&(a=(a+1)%t),d-l{n=u,r=null,a&&(clearTimeout(a),a=null),t(...d)};return[(...d)=>{const u=Date.now(),h=u-n;h>=s?l(d,u):(r=d,a||(a=setTimeout(()=>{a=null,l(r)},s-h)))},()=>r&&l(r)]}const oh=(t,e,n=3)=>{let s=0;const r=zI(50,250);return $I(a=>{const l=a.loaded,o=a.lengthComputable?a.total:void 0,c=l-s,d=r(c),u=l<=o;s=l;const h={loaded:l,total:o,progress:o?l/o:void 0,bytes:c,rate:d||void 0,estimated:d&&o&&u?(o-l)/d:void 0,event:a,lengthComputable:o!=null,[e?"download":"upload"]:!0};t(h)},n)},u1=(t,e)=>{const n=t!=null;return[s=>e[0]({lengthComputable:n,total:t,loaded:s}),e[1]]},h1=t=>(...e)=>H.asap(()=>t(...e)),BI=vn.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,vn.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(vn.origin),vn.navigator&&/(msie|trident)/i.test(vn.navigator.userAgent)):()=>!0,_I=vn.hasStandardBrowserEnv?{write(t,e,n,s,r,a,l){if(typeof document>"u")return;const o=[`${t}=${encodeURIComponent(e)}`];H.isNumber(n)&&o.push(`expires=${new Date(n).toUTCString()}`),H.isString(s)&&o.push(`path=${s}`),H.isString(r)&&o.push(`domain=${r}`),a===!0&&o.push("secure"),H.isString(l)&&o.push(`SameSite=${l}`),document.cookie=o.join("; ")},read(t){if(typeof document>"u")return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function VI(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function KI(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function tC(t,e,n){let s=!VI(e);return t&&(s||n==!1)?KI(t,e):e}const f1=t=>t instanceof Jn?{...t}:t;function $a(t,e){e=e||{};const n={};function s(d,u,h,m){return H.isPlainObject(d)&&H.isPlainObject(u)?H.merge.call({caseless:m},d,u):H.isPlainObject(u)?H.merge({},u):H.isArray(u)?u.slice():u}function r(d,u,h,m){if(H.isUndefined(u)){if(!H.isUndefined(d))return s(void 0,d,h,m)}else return s(d,u,h,m)}function a(d,u){if(!H.isUndefined(u))return s(void 0,u)}function l(d,u){if(H.isUndefined(u)){if(!H.isUndefined(d))return s(void 0,d)}else return s(void 0,u)}function o(d,u,h){if(h in e)return s(d,u);if(h in t)return s(void 0,d)}const c={url:a,method:a,data:a,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:o,headers:(d,u,h)=>r(f1(d),f1(u),h,!0)};return H.forEach(Object.keys({...t,...e}),function(u){const h=c[u]||r,m=h(t[u],e[u],u);H.isUndefined(m)&&h!==o||(n[u]=m)}),n}const nC=t=>{const e=$a({},t);let{data:n,withXSRFToken:s,xsrfHeaderName:r,xsrfCookieName:a,headers:l,auth:o}=e;if(e.headers=l=Jn.from(l),e.url=JS(tC(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),o&&l.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),H.isFormData(n)){if(vn.hasStandardBrowserEnv||vn.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if(H.isFunction(n.getHeaders)){const c=n.getHeaders(),d=["content-type","content-length"];Object.entries(c).forEach(([u,h])=>{d.includes(u.toLowerCase())&&l.set(u,h)})}}if(vn.hasStandardBrowserEnv&&(s&&H.isFunction(s)&&(s=s(e)),s||s!==!1&&BI(e.url))){const c=r&&a&&_I.read(a);c&&l.set(r,c)}return e},UI=typeof XMLHttpRequest<"u",qI=UI&&function(t){return new Promise(function(n,s){const r=nC(t);let a=r.data;const l=Jn.from(r.headers).normalize();let{responseType:o,onUploadProgress:c,onDownloadProgress:d}=r,u,h,m,f,p;function g(){f&&f(),p&&p(),r.cancelToken&&r.cancelToken.unsubscribe(u),r.signal&&r.signal.removeEventListener("abort",u)}let x=new XMLHttpRequest;x.open(r.method.toUpperCase(),r.url,!0),x.timeout=r.timeout;function y(){if(!x)return;const b=Jn.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),k={data:!o||o==="text"||o==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:b,config:t,request:x};eC(function(T){n(T),g()},function(T){s(T),g()},k),x=null}"onloadend"in x?x.onloadend=y:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(y)},x.onabort=function(){x&&(s(new Te("Request aborted",Te.ECONNABORTED,t,x)),x=null)},x.onerror=function(j){const k=j&&j.message?j.message:"Network Error",E=new Te(k,Te.ERR_NETWORK,t,x);E.event=j||null,s(E),x=null},x.ontimeout=function(){let j=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const k=r.transitional||ZS;r.timeoutErrorMessage&&(j=r.timeoutErrorMessage),s(new Te(j,k.clarifyTimeoutError?Te.ETIMEDOUT:Te.ECONNABORTED,t,x)),x=null},a===void 0&&l.setContentType(null),"setRequestHeader"in x&&H.forEach(l.toJSON(),function(j,k){x.setRequestHeader(k,j)}),H.isUndefined(r.withCredentials)||(x.withCredentials=!!r.withCredentials),o&&o!=="json"&&(x.responseType=r.responseType),d&&([m,p]=oh(d,!0),x.addEventListener("progress",m)),c&&x.upload&&([h,f]=oh(c),x.upload.addEventListener("progress",h),x.upload.addEventListener("loadend",f)),(r.cancelToken||r.signal)&&(u=b=>{x&&(s(!b||b.type?new xo(null,t,x):b),x.abort(),x=null)},r.cancelToken&&r.cancelToken.subscribe(u),r.signal&&(r.signal.aborted?u():r.signal.addEventListener("abort",u)));const v=FI(r.url);if(v&&vn.protocols.indexOf(v)===-1){s(new Te("Unsupported protocol "+v+":",Te.ERR_BAD_REQUEST,t));return}x.send(a||null)})},HI=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let s=new AbortController,r;const a=function(d){if(!r){r=!0,o();const u=d instanceof Error?d:this.reason;s.abort(u instanceof Te?u:new xo(u instanceof Error?u.message:u))}};let l=e&&setTimeout(()=>{l=null,a(new Te(`timeout ${e} of ms exceeded`,Te.ETIMEDOUT))},e);const o=()=>{t&&(l&&clearTimeout(l),l=null,t.forEach(d=>{d.unsubscribe?d.unsubscribe(a):d.removeEventListener("abort",a)}),t=null)};t.forEach(d=>d.addEventListener("abort",a));const{signal:c}=s;return c.unsubscribe=()=>H.asap(o),c}},WI=function*(t,e){let n=t.byteLength;if(n{const r=QI(t,e);let a=0,l,o=c=>{l||(l=!0,s&&s(c))};return new ReadableStream({async pull(c){try{const{done:d,value:u}=await r.next();if(d){o(),c.close();return}let h=u.byteLength;if(n){let m=a+=h;n(m)}c.enqueue(new Uint8Array(u))}catch(d){throw o(d),d}},cancel(c){return o(c),r.return()}},{highWaterMark:2})},p1=64*1024,{isFunction:Gd}=H,JI=(({Request:t,Response:e})=>({Request:t,Response:e}))(H.global),{ReadableStream:g1,TextEncoder:x1}=H.global,y1=(t,...e)=>{try{return!!t(...e)}catch{return!1}},ZI=t=>{t=H.merge.call({skipUndefined:!0},JI,t);const{fetch:e,Request:n,Response:s}=t,r=e?Gd(e):typeof fetch=="function",a=Gd(n),l=Gd(s);if(!r)return!1;const o=r&&Gd(g1),c=r&&(typeof x1=="function"?(p=>g=>p.encode(g))(new x1):async p=>new Uint8Array(await new n(p).arrayBuffer())),d=a&&o&&y1(()=>{let p=!1;const g=new n(vn.origin,{body:new g1,method:"POST",get duplex(){return p=!0,"half"}}).headers.has("Content-Type");return p&&!g}),u=l&&o&&y1(()=>H.isReadableStream(new s("").body)),h={stream:u&&(p=>p.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(p=>{!h[p]&&(h[p]=(g,x)=>{let y=g&&g[p];if(y)return y.call(g);throw new Te(`Response type '${p}' is not supported`,Te.ERR_NOT_SUPPORT,x)})});const m=async p=>{if(p==null)return 0;if(H.isBlob(p))return p.size;if(H.isSpecCompliantForm(p))return(await new n(vn.origin,{method:"POST",body:p}).arrayBuffer()).byteLength;if(H.isArrayBufferView(p)||H.isArrayBuffer(p))return p.byteLength;if(H.isURLSearchParams(p)&&(p=p+""),H.isString(p))return(await c(p)).byteLength},f=async(p,g)=>{const x=H.toFiniteNumber(p.getContentLength());return x??m(g)};return async p=>{let{url:g,method:x,data:y,signal:v,cancelToken:b,timeout:j,onDownloadProgress:k,onUploadProgress:E,responseType:T,headers:w,withCredentials:S="same-origin",fetchOptions:M}=nC(p),F=e||fetch;T=T?(T+"").toLowerCase():"text";let R=HI([v,b&&b.toAbortSignal()],j),V=null;const D=R&&R.unsubscribe&&(()=>{R.unsubscribe()});let z;try{if(E&&d&&x!=="get"&&x!=="head"&&(z=await f(w,y))!==0){let ce=new n(g,{method:"POST",body:y,duplex:"half"}),he;if(H.isFormData(y)&&(he=ce.headers.get("content-type"))&&w.setContentType(he),ce.body){const[Je,et]=u1(z,oh(h1(E)));y=m1(ce.body,p1,Je,et)}}H.isString(S)||(S=S?"include":"omit");const C=a&&"credentials"in n.prototype,_={...M,signal:R,method:x.toUpperCase(),headers:w.normalize().toJSON(),body:y,duplex:"half",credentials:C?S:void 0};V=a&&new n(g,_);let K=await(a?F(V,M):F(g,_));const B=u&&(T==="stream"||T==="response");if(u&&(k||B&&D)){const ce={};["status","statusText","headers"].forEach(mt=>{ce[mt]=K[mt]});const he=H.toFiniteNumber(K.headers.get("content-length")),[Je,et]=k&&u1(he,oh(h1(k),!0))||[];K=new s(m1(K.body,p1,Je,()=>{et&&et(),D&&D()}),ce)}T=T||"text";let W=await h[H.findKey(h,T)||"text"](K,p);return!B&&D&&D(),await new Promise((ce,he)=>{eC(ce,he,{data:W,headers:Jn.from(K.headers),status:K.status,statusText:K.statusText,config:p,request:V})})}catch(C){throw D&&D(),C&&C.name==="TypeError"&&/Load failed|fetch/i.test(C.message)?Object.assign(new Te("Network Error",Te.ERR_NETWORK,p,V),{cause:C.cause||C}):Te.from(C,C&&C.code,p,V)}}},YI=new Map,sC=t=>{let e=t&&t.env||{};const{fetch:n,Request:s,Response:r}=e,a=[s,r,n];let l=a.length,o=l,c,d,u=YI;for(;o--;)c=a[o],d=u.get(c),d===void 0&&u.set(c,d=o?new Map:ZI(e)),u=d;return d};sC();const Py={http:pI,xhr:qI,fetch:{get:sC}};H.forEach(Py,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const v1=t=>`- ${t}`,XI=t=>H.isFunction(t)||t===null||t===!1;function e5(t,e){t=H.isArray(t)?t:[t];const{length:n}=t;let s,r;const a={};for(let l=0;l`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let o=n?l.length>1?`since : +`+l.map(v1).join(` +`):" "+v1(l[0]):"as no adapter specified";throw new Te("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return r}const rC={getAdapter:e5,adapters:Py};function Tm(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new xo(null,t)}function b1(t){return Tm(t),t.headers=Jn.from(t.headers),t.data=Mm.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),rC.getAdapter(t.adapter||vd.adapter,t)(t).then(function(s){return Tm(t),s.data=Mm.call(t,t.transformResponse,s),s.headers=Jn.from(s.headers),s},function(s){return XS(s)||(Tm(t),s&&s.response&&(s.response.data=Mm.call(t,t.transformResponse,s.response),s.response.headers=Jn.from(s.response.headers))),Promise.reject(s)})}const iC="1.13.2",Pf={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Pf[t]=function(s){return typeof s===t||"a"+(e<1?"n ":" ")+t}});const j1={};Pf.transitional=function(e,n,s){function r(a,l){return"[Axios v"+iC+"] Transitional option '"+a+"'"+l+(s?". "+s:"")}return(a,l,o)=>{if(e===!1)throw new Te(r(l," has been removed"+(n?" in "+n:"")),Te.ERR_DEPRECATED);return n&&!j1[l]&&(j1[l]=!0,console.warn(r(l," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(a,l,o):!0}};Pf.spelling=function(e){return(n,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)};function t5(t,e,n){if(typeof t!="object")throw new Te("options must be an object",Te.ERR_BAD_OPTION_VALUE);const s=Object.keys(t);let r=s.length;for(;r-- >0;){const a=s[r],l=e[a];if(l){const o=t[a],c=o===void 0||l(o,a,t);if(c!==!0)throw new Te("option "+a+" must be "+c,Te.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Te("Unknown option "+a,Te.ERR_BAD_OPTION)}}const Cu={assertOptions:t5,validators:Pf},Ws=Cu.validators;let ka=class{constructor(e){this.defaults=e||{},this.interceptors={request:new c1,response:new c1}}async request(e,n){try{return await this._request(e,n)}catch(s){if(s instanceof Error){let r={};Error.captureStackTrace?Error.captureStackTrace(r):r=new Error;const a=r.stack?r.stack.replace(/^.+\n/,""):"";try{s.stack?a&&!String(s.stack).endsWith(a.replace(/^.+\n.+\n/,""))&&(s.stack+=` +`+a):s.stack=a}catch{}}throw s}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=$a(this.defaults,n);const{transitional:s,paramsSerializer:r,headers:a}=n;s!==void 0&&Cu.assertOptions(s,{silentJSONParsing:Ws.transitional(Ws.boolean),forcedJSONParsing:Ws.transitional(Ws.boolean),clarifyTimeoutError:Ws.transitional(Ws.boolean)},!1),r!=null&&(H.isFunction(r)?n.paramsSerializer={serialize:r}:Cu.assertOptions(r,{encode:Ws.function,serialize:Ws.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Cu.assertOptions(n,{baseUrl:Ws.spelling("baseURL"),withXsrfToken:Ws.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let l=a&&H.merge(a.common,a[n.method]);a&&H.forEach(["delete","get","head","post","put","patch","common"],p=>{delete a[p]}),n.headers=Jn.concat(l,a);const o=[];let c=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(c=c&&g.synchronous,o.unshift(g.fulfilled,g.rejected))});const d=[];this.interceptors.response.forEach(function(g){d.push(g.fulfilled,g.rejected)});let u,h=0,m;if(!c){const p=[b1.bind(this),void 0];for(p.unshift(...o),p.push(...d),m=p.length,u=Promise.resolve(n);h{if(!s._listeners)return;let a=s._listeners.length;for(;a-- >0;)s._listeners[a](r);s._listeners=null}),this.promise.then=r=>{let a;const l=new Promise(o=>{s.subscribe(o),a=o}).then(r);return l.cancel=function(){s.unsubscribe(a)},l},e(function(a,l,o){s.reason||(s.reason=new xo(a,l,o),n(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=s=>{e.abort(s)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new aC(function(r){e=r}),cancel:e}}};function s5(t){return function(n){return t.apply(null,n)}}function r5(t){return H.isObject(t)&&t.isAxiosError===!0}const zg={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(zg).forEach(([t,e])=>{zg[e]=t});function lC(t){const e=new ka(t),n=zS(ka.prototype.request,e);return H.extend(n,ka.prototype,e,{allOwnKeys:!0}),H.extend(n,e,null,{allOwnKeys:!0}),n.create=function(r){return lC($a(t,r))},n}const Tt=lC(vd);Tt.Axios=ka;Tt.CanceledError=xo;Tt.CancelToken=n5;Tt.isCancel=XS;Tt.VERSION=iC;Tt.toFormData=Tf;Tt.AxiosError=Te;Tt.Cancel=Tt.CanceledError;Tt.all=function(e){return Promise.all(e)};Tt.spread=s5;Tt.isAxiosError=r5;Tt.mergeConfig=$a;Tt.AxiosHeaders=Jn;Tt.formToJSON=t=>YS(H.isHTMLForm(t)?new FormData(t):t);Tt.getAdapter=rC.getAdapter;Tt.HttpStatusCode=zg;Tt.default=Tt;const{Axios:IV,AxiosError:RV,CanceledError:OV,isCancel:LV,CancelToken:FV,VERSION:zV,all:$V,Cancel:BV,isAxiosError:_V,spread:VV,toFormData:KV,AxiosHeaders:UV,HttpStatusCode:qV,formToJSON:HV,getAdapter:WV,mergeConfig:QV}=Tt,$=Tt.create({baseURL:"/api",headers:{"Content-Type":"application/json"}});$.interceptors.request.use(t=>{const e=localStorage.getItem("token");return e&&(t.headers.Authorization=`Bearer ${e}`),t});$.interceptors.response.use(t=>t,t=>{var r,a,l,o,c,d,u;const e=((a=(r=t.config)==null?void 0:r.url)==null?void 0:a.includes("/auth/login"))||((o=(l=t.config)==null?void 0:l.url)==null?void 0:o.includes("/auth/customer-login"));((c=t.response)==null?void 0:c.status)===401&&!e&&(localStorage.removeItem("token"),localStorage.removeItem("user"),window.location.href="/login");const n=((u=(d=t.response)==null?void 0:d.data)==null?void 0:u.error)||t.message||"Ein Fehler ist aufgetreten",s=new Error(n);return Promise.reject(s)});const Jd={login:async(t,e)=>(await $.post("/auth/login",{email:t,password:e})).data,customerLogin:async(t,e)=>(await $.post("/auth/customer-login",{email:t,password:e})).data,me:async()=>(await $.get("/auth/me")).data},Zt={getAll:async t=>(await $.get("/customers",{params:t})).data,getById:async t=>(await $.get(`/customers/${t}`)).data,create:async t=>(await $.post("/customers",t)).data,update:async(t,e)=>(await $.put(`/customers/${t}`,e)).data,delete:async t=>(await $.delete(`/customers/${t}`)).data,getPortalSettings:async t=>(await $.get(`/customers/${t}/portal`)).data,updatePortalSettings:async(t,e)=>(await $.put(`/customers/${t}/portal`,e)).data,setPortalPassword:async(t,e)=>(await $.post(`/customers/${t}/portal/password`,{password:e})).data,getPortalPassword:async t=>(await $.get(`/customers/${t}/portal/password`)).data,getRepresentatives:async t=>(await $.get(`/customers/${t}/representatives`)).data,addRepresentative:async(t,e,n)=>(await $.post(`/customers/${t}/representatives`,{representativeId:e,notes:n})).data,removeRepresentative:async(t,e)=>(await $.delete(`/customers/${t}/representatives/${e}`)).data,searchForRepresentative:async(t,e)=>(await $.get(`/customers/${t}/representatives/search`,{params:{search:e}})).data},$g={getByCustomer:async t=>(await $.get(`/customers/${t}/addresses`)).data,create:async(t,e)=>(await $.post(`/customers/${t}/addresses`,e)).data,update:async(t,e)=>(await $.put(`/addresses/${t}`,e)).data,delete:async t=>(await $.delete(`/addresses/${t}`)).data},ch={getByCustomer:async(t,e=!1)=>(await $.get(`/customers/${t}/bank-cards`,{params:{showInactive:e}})).data,create:async(t,e)=>(await $.post(`/customers/${t}/bank-cards`,e)).data,update:async(t,e)=>(await $.put(`/bank-cards/${t}`,e)).data,delete:async t=>(await $.delete(`/bank-cards/${t}`)).data},dh={getByCustomer:async(t,e=!1)=>(await $.get(`/customers/${t}/documents`,{params:{showInactive:e}})).data,create:async(t,e)=>(await $.post(`/customers/${t}/documents`,e)).data,update:async(t,e)=>(await $.put(`/documents/${t}`,e)).data,delete:async t=>(await $.delete(`/documents/${t}`)).data},ar={getByCustomer:async(t,e=!1)=>(await $.get(`/customers/${t}/meters`,{params:{showInactive:e}})).data,create:async(t,e)=>(await $.post(`/customers/${t}/meters`,e)).data,update:async(t,e)=>(await $.put(`/meters/${t}`,e)).data,delete:async t=>(await $.delete(`/meters/${t}`)).data,getReadings:async t=>(await $.get(`/meters/${t}/readings`)).data,addReading:async(t,e)=>(await $.post(`/meters/${t}/readings`,e)).data,updateReading:async(t,e,n)=>(await $.put(`/meters/${t}/readings/${e}`,n)).data,deleteReading:async(t,e)=>(await $.delete(`/meters/${t}/readings/${e}`)).data},sl={getInvoices:async t=>(await $.get(`/energy-details/${t}/invoices`)).data,addInvoice:async(t,e)=>(await $.post(`/energy-details/${t}/invoices`,e)).data,updateInvoice:async(t,e,n)=>(await $.put(`/energy-details/${t}/invoices/${e}`,n)).data,deleteInvoice:async(t,e)=>(await $.delete(`/energy-details/${t}/invoices/${e}`)).data,uploadDocument:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/invoices/${t}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteDocument:async t=>(await $.delete(`/upload/invoices/${t}`)).data},ts={getByCustomer:async(t,e=!1)=>(await $.get(`/customers/${t}/stressfrei-emails`,{params:{includeInactive:e}})).data,create:async(t,e)=>(await $.post(`/customers/${t}/stressfrei-emails`,e)).data,update:async(t,e)=>(await $.put(`/stressfrei-emails/${t}`,e)).data,delete:async t=>(await $.delete(`/stressfrei-emails/${t}`)).data,enableMailbox:async t=>(await $.post(`/stressfrei-emails/${t}/enable-mailbox`)).data,syncMailboxStatus:async t=>(await $.post(`/stressfrei-emails/${t}/sync-mailbox-status`)).data,getMailboxCredentials:async t=>(await $.get(`/stressfrei-emails/${t}/credentials`)).data,resetPassword:async t=>(await $.post(`/stressfrei-emails/${t}/reset-password`)).data,syncEmails:async(t,e=!1)=>(await $.post(`/stressfrei-emails/${t}/sync`,{},{params:{full:e}})).data,sendEmail:async(t,e)=>(await $.post(`/stressfrei-emails/${t}/send`,e)).data,getFolderCounts:async t=>(await $.get(`/stressfrei-emails/${t}/folder-counts`)).data},Be={getForCustomer:async(t,e)=>(await $.get(`/customers/${t}/emails`,{params:e})).data,getForContract:async(t,e)=>(await $.get(`/contracts/${t}/emails`,{params:e})).data,getContractFolderCounts:async t=>(await $.get(`/contracts/${t}/emails/folder-counts`)).data,getMailboxAccounts:async t=>(await $.get(`/customers/${t}/mailbox-accounts`)).data,getById:async t=>(await $.get(`/emails/${t}`)).data,getThread:async t=>(await $.get(`/emails/${t}/thread`)).data,markAsRead:async(t,e)=>(await $.patch(`/emails/${t}/read`,{isRead:e})).data,toggleStar:async t=>(await $.post(`/emails/${t}/star`)).data,assignToContract:async(t,e)=>(await $.post(`/emails/${t}/assign`,{contractId:e})).data,unassignFromContract:async t=>(await $.delete(`/emails/${t}/assign`)).data,delete:async t=>(await $.delete(`/emails/${t}`)).data,getAttachmentUrl:(t,e,n)=>{const s=localStorage.getItem("token"),r=encodeURIComponent(e),a=n?"&view=true":"";return`${$.defaults.baseURL}/emails/${t}/attachments/${r}?token=${s}${a}`},getUnreadCount:async t=>(await $.get("/emails/unread-count",{params:t})).data,getTrash:async t=>(await $.get(`/customers/${t}/emails/trash`)).data,getTrashCount:async t=>(await $.get(`/customers/${t}/emails/trash/count`)).data,restore:async t=>(await $.post(`/emails/${t}/restore`)).data,permanentDelete:async t=>(await $.delete(`/emails/${t}/permanent`)).data,getAttachmentTargets:async t=>(await $.get(`/emails/${t}/attachment-targets`)).data,saveAttachmentTo:async(t,e,n)=>{const s=encodeURIComponent(e);return(await $.post(`/emails/${t}/attachments/${s}/save-to`,n)).data},saveEmailAsPdf:async(t,e)=>(await $.post(`/emails/${t}/save-as-pdf`,e)).data,saveEmailAsInvoice:async(t,e)=>(await $.post(`/emails/${t}/save-as-invoice`,e)).data,saveAttachmentAsInvoice:async(t,e,n)=>{const s=encodeURIComponent(e);return(await $.post(`/emails/${t}/attachments/${s}/save-as-invoice`,n)).data}},He={getAll:async t=>(await $.get("/contracts",{params:t})).data,getTreeForCustomer:async t=>(await $.get("/contracts",{params:{customerId:t,tree:"true"}})).data,getById:async t=>(await $.get(`/contracts/${t}`)).data,create:async t=>(await $.post("/contracts",t)).data,update:async(t,e)=>(await $.put(`/contracts/${t}`,e)).data,delete:async t=>(await $.delete(`/contracts/${t}`)).data,createFollowUp:async t=>(await $.post(`/contracts/${t}/follow-up`)).data,getPassword:async t=>(await $.get(`/contracts/${t}/password`)).data,getSimCardCredentials:async t=>(await $.get(`/contracts/simcard/${t}/credentials`)).data,getInternetCredentials:async t=>(await $.get(`/contracts/${t}/internet-credentials`)).data,getSipCredentials:async t=>(await $.get(`/contracts/phonenumber/${t}/sip-credentials`)).data,getCockpit:async()=>(await $.get("/contracts/cockpit")).data,snooze:async(t,e)=>(await $.patch(`/contracts/${t}/snooze`,e)).data},uh={getByContract:async t=>(await $.get(`/contracts/${t}/history`)).data,create:async(t,e)=>(await $.post(`/contracts/${t}/history`,e)).data,update:async(t,e,n)=>(await $.put(`/contracts/${t}/history/${e}`,n)).data,delete:async(t,e)=>(await $.delete(`/contracts/${t}/history/${e}`)).data},ht={getAll:async t=>(await $.get("/tasks",{params:t})).data,getStats:async()=>(await $.get("/tasks/stats")).data,getByContract:async(t,e)=>(await $.get(`/contracts/${t}/tasks`,{params:{status:e}})).data,create:async(t,e)=>(await $.post(`/contracts/${t}/tasks`,e)).data,update:async(t,e)=>(await $.put(`/tasks/${t}`,e)).data,complete:async t=>(await $.post(`/tasks/${t}/complete`)).data,reopen:async t=>(await $.post(`/tasks/${t}/reopen`)).data,delete:async t=>(await $.delete(`/tasks/${t}`)).data,createSubtask:async(t,e)=>(await $.post(`/tasks/${t}/subtasks`,{title:e})).data,createReply:async(t,e)=>(await $.post(`/tasks/${t}/reply`,{title:e})).data,updateSubtask:async(t,e)=>(await $.put(`/subtasks/${t}`,{title:e})).data,completeSubtask:async t=>(await $.post(`/subtasks/${t}/complete`)).data,reopenSubtask:async t=>(await $.post(`/subtasks/${t}/reopen`)).data,deleteSubtask:async t=>(await $.delete(`/subtasks/${t}`)).data,createSupportTicket:async(t,e)=>(await $.post(`/contracts/${t}/support-ticket`,e)).data},Ba={getPublic:async()=>(await $.get("/settings/public")).data,getAll:async()=>(await $.get("/settings")).data,update:async t=>(await $.put("/settings",t)).data,updateOne:async(t,e)=>(await $.put(`/settings/${t}`,{value:e})).data},Zi={list:async()=>(await $.get("/settings/backups")).data,create:async()=>(await $.post("/settings/backup")).data,restore:async t=>(await $.post(`/settings/backup/${t}/restore`)).data,delete:async t=>(await $.delete(`/settings/backup/${t}`)).data,getDownloadUrl:t=>`/api/settings/backup/${t}/download`,upload:async t=>{const e=new FormData;return e.append("backup",t),(await $.post("/settings/backup/upload",e,{headers:{"Content-Type":"multipart/form-data"}})).data},factoryReset:async()=>(await $.post("/settings/factory-reset")).data},Fc={getAll:async(t=!1)=>(await $.get("/platforms",{params:{includeInactive:t}})).data,getById:async t=>(await $.get(`/platforms/${t}`)).data,create:async t=>(await $.post("/platforms",t)).data,update:async(t,e)=>(await $.put(`/platforms/${t}`,e)).data,delete:async t=>(await $.delete(`/platforms/${t}`)).data},zc={getAll:async(t=!1)=>(await $.get("/cancellation-periods",{params:{includeInactive:t}})).data,getById:async t=>(await $.get(`/cancellation-periods/${t}`)).data,create:async t=>(await $.post("/cancellation-periods",t)).data,update:async(t,e)=>(await $.put(`/cancellation-periods/${t}`,e)).data,delete:async t=>(await $.delete(`/cancellation-periods/${t}`)).data},$c={getAll:async(t=!1)=>(await $.get("/contract-durations",{params:{includeInactive:t}})).data,getById:async t=>(await $.get(`/contract-durations/${t}`)).data,create:async t=>(await $.post("/contract-durations",t)).data,update:async(t,e)=>(await $.put(`/contract-durations/${t}`,e)).data,delete:async t=>(await $.delete(`/contract-durations/${t}`)).data},Bc={getAll:async(t=!1)=>(await $.get("/contract-categories",{params:{includeInactive:t}})).data,getById:async t=>(await $.get(`/contract-categories/${t}`)).data,create:async t=>(await $.post("/contract-categories",t)).data,update:async(t,e)=>(await $.put(`/contract-categories/${t}`,e)).data,delete:async t=>(await $.delete(`/contract-categories/${t}`)).data},to={getAll:async(t=!1)=>(await $.get("/providers",{params:{includeInactive:t}})).data,getById:async t=>(await $.get(`/providers/${t}`)).data,create:async t=>(await $.post("/providers",t)).data,update:async(t,e)=>(await $.put(`/providers/${t}`,e)).data,delete:async t=>(await $.delete(`/providers/${t}`)).data,getTariffs:async(t,e=!1)=>(await $.get(`/providers/${t}/tariffs`,{params:{includeInactive:e}})).data,createTariff:async(t,e)=>(await $.post(`/providers/${t}/tariffs`,e)).data},oC={getById:async t=>(await $.get(`/tariffs/${t}`)).data,update:async(t,e)=>(await $.put(`/tariffs/${t}`,e)).data,delete:async t=>(await $.delete(`/tariffs/${t}`)).data},Ct={uploadBankCardDocument:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/bank-cards/${t}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},uploadIdentityDocument:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/documents/${t}`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteBankCardDocument:async t=>(await $.delete(`/upload/bank-cards/${t}`)).data,deleteIdentityDocument:async t=>(await $.delete(`/upload/documents/${t}`)).data,uploadBusinessRegistration:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/customers/${t}/business-registration`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteBusinessRegistration:async t=>(await $.delete(`/upload/customers/${t}/business-registration`)).data,uploadCommercialRegister:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/customers/${t}/commercial-register`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCommercialRegister:async t=>(await $.delete(`/upload/customers/${t}/commercial-register`)).data,uploadPrivacyPolicy:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/customers/${t}/privacy-policy`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deletePrivacyPolicy:async t=>(await $.delete(`/upload/customers/${t}/privacy-policy`)).data,uploadCancellationLetter:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/contracts/${t}/cancellation-letter`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationLetter:async t=>(await $.delete(`/upload/contracts/${t}/cancellation-letter`)).data,uploadCancellationConfirmation:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/contracts/${t}/cancellation-confirmation`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationConfirmation:async t=>(await $.delete(`/upload/contracts/${t}/cancellation-confirmation`)).data,uploadCancellationLetterOptions:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/contracts/${t}/cancellation-letter-options`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationLetterOptions:async t=>(await $.delete(`/upload/contracts/${t}/cancellation-letter-options`)).data,uploadCancellationConfirmationOptions:async(t,e)=>{const n=new FormData;return n.append("document",e),(await $.post(`/upload/contracts/${t}/cancellation-confirmation-options`,n,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteCancellationConfirmationOptions:async t=>(await $.delete(`/upload/contracts/${t}/cancellation-confirmation-options`)).data},sc={getAll:async t=>(await $.get("/users",{params:t})).data,getById:async t=>(await $.get(`/users/${t}`)).data,create:async t=>(await $.post("/users",t)).data,update:async(t,e)=>(await $.put(`/users/${t}`,e)).data,delete:async t=>(await $.delete(`/users/${t}`)).data,getRoles:async()=>(await $.get("/users/roles/list")).data},Vo={getSchema:async()=>(await $.get("/developer/schema")).data,getTableData:async(t,e=1,n=50)=>(await $.get(`/developer/table/${t}`,{params:{page:e,limit:n}})).data,updateRow:async(t,e,n)=>(await $.put(`/developer/table/${t}/${e}`,n)).data,deleteRow:async(t,e)=>(await $.delete(`/developer/table/${t}/${e}`)).data,getReference:async t=>(await $.get(`/developer/reference/${t}`)).data},wr={getConfigs:async()=>(await $.get("/email-providers/configs")).data,getConfig:async t=>(await $.get(`/email-providers/configs/${t}`)).data,createConfig:async t=>(await $.post("/email-providers/configs",t)).data,updateConfig:async(t,e)=>(await $.put(`/email-providers/configs/${t}`,e)).data,deleteConfig:async t=>(await $.delete(`/email-providers/configs/${t}`)).data,testConnection:async t=>{const e=t!=null&&t.testData?{...t.testData}:t!=null&&t.id?{id:t.id}:{};return(await $.post("/email-providers/test-connection",e)).data},getDomain:async()=>(await $.get("/email-providers/domain")).data,checkEmailExists:async t=>(await $.get(`/email-providers/check/${t}`)).data,provisionEmail:async(t,e)=>(await $.post("/email-providers/provision",{localPart:t,customerEmail:e})).data,deprovisionEmail:async t=>(await $.delete(`/email-providers/deprovision/${t}`)).data},Pm={search:async t=>(await $.get("/audit-logs",{params:t})).data,getById:async t=>(await $.get(`/audit-logs/${t}`)).data,getByCustomer:async t=>(await $.get(`/audit-logs/customer/${t}`)).data,export:async t=>(await $.get("/audit-logs/export",{params:t})).data,verifyIntegrity:async()=>(await $.post("/audit-logs/verify")).data,getRetentionPolicies:async()=>(await $.get("/audit-logs/retention-policies")).data,updateRetentionPolicy:async(t,e)=>(await $.put(`/audit-logs/retention-policies/${t}`,e)).data,runRetentionCleanup:async()=>(await $.post("/audit-logs/cleanup")).data},Mr={getDashboardStats:async()=>(await $.get("/gdpr/dashboard")).data,exportCustomerData:async t=>(await $.get(`/gdpr/customer/${t}/export`)).data,getDeletionRequests:async t=>(await $.get("/gdpr/deletions",{params:t})).data,getDeletionRequest:async t=>(await $.get(`/gdpr/deletions/${t}`)).data,createDeletionRequest:async t=>(await $.post("/gdpr/deletions",t)).data,processDeletionRequest:async(t,e)=>(await $.put(`/gdpr/deletions/${t}/process`,e)).data,getCustomerConsents:async t=>(await $.get(`/gdpr/customer/${t}/consents`)).data,updateConsent:async(t,e,n)=>(await $.put(`/gdpr/customer/${t}/consents/${e}`,n)).data,getConsentOverview:async()=>(await $.get("/gdpr/consents/overview")).data,getPrivacyPolicy:async()=>(await $.get("/gdpr/privacy-policy")).data,updatePrivacyPolicy:async t=>(await $.put("/gdpr/privacy-policy",{html:t})).data,sendConsentLink:async(t,e)=>(await $.post(`/gdpr/customer/${t}/send-consent-link`,{channel:e})).data},N1=Tt.create({baseURL:"/api/public",headers:{"Content-Type":"application/json"}}),Im={getConsentPage:async t=>(await N1.get(`/consent/${t}`)).data,grantAllConsents:async t=>(await N1.post(`/consent/${t}/grant`)).data,getConsentPdfUrl:t=>`/api/public/consent/${t}/pdf`},cC=N.createContext(null);function i5({children:t}){const[e,n]=N.useState(null),[s,r]=N.useState(!0),[a,l]=N.useState(()=>localStorage.getItem("developerMode")==="true"),o=g=>{l(g),localStorage.setItem("developerMode",String(g))};N.useEffect(()=>{var g;console.log("useEffect check - user:",e==null?void 0:e.email,"developerMode:",a,"has developer:access:",(g=e==null?void 0:e.permissions)==null?void 0:g.includes("developer:access")),e&&a&&!e.permissions.includes("developer:access")&&(console.log("Disabling developer mode because user lacks developer:access permission"),o(!1))},[e,a]),N.useEffect(()=>{localStorage.getItem("token")?Jd.me().then(x=>{x.success&&x.data?n(x.data):localStorage.removeItem("token")}).catch(()=>{localStorage.removeItem("token")}).finally(()=>{r(!1)}):r(!1)},[]);const c=async(g,x)=>{const y=await Jd.login(g,x);if(y.success&&y.data)localStorage.setItem("token",y.data.token),n(y.data.user);else throw new Error(y.error||"Login fehlgeschlagen")},d=async(g,x)=>{const y=await Jd.customerLogin(g,x);if(y.success&&y.data)localStorage.setItem("token",y.data.token),n(y.data.user);else throw new Error(y.error||"Login fehlgeschlagen")},u=()=>{localStorage.removeItem("token"),n(null)},h=async()=>{var x;if(localStorage.getItem("token"))try{const y=await Jd.me();console.log("refreshUser response:",y),console.log("permissions:",(x=y.data)==null?void 0:x.permissions),y.success&&y.data&&n(y.data)}catch(y){console.error("refreshUser error:",y)}},m=g=>e?e.permissions.includes(g):!1,f=!!(e!=null&&e.customerId),p=!!(e!=null&&e.isCustomerPortal);return i.jsx(cC.Provider,{value:{user:e,isLoading:s,isAuthenticated:!!e,login:c,customerLogin:d,logout:u,hasPermission:m,isCustomer:f,isCustomerPortal:p,developerMode:a,setDeveloperMode:o,refreshUser:h},children:t})}function nt(){const t=N.useContext(cC);if(!t)throw new Error("useAuth must be used within an AuthProvider");return t}const Rm={scrollToTopThreshold:.7},dC=N.createContext(void 0),w1="opencrm_app_settings";function a5({children:t}){const[e,n]=N.useState(()=>{const r=localStorage.getItem(w1);if(r)try{return{...Rm,...JSON.parse(r)}}catch{return Rm}return Rm});N.useEffect(()=>{localStorage.setItem(w1,JSON.stringify(e))},[e]);const s=r=>{n(a=>({...a,...r}))};return i.jsx(dC.Provider,{value:{settings:e,updateSettings:s},children:t})}function uC(){const t=N.useContext(dC);if(!t)throw new Error("useAppSettings must be used within AppSettingsProvider");return t}function l5(){const{pathname:t}=qr();return N.useEffect(()=>{window.scrollTo(0,0)},[t]),null}/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const o5=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),hC=(...t)=>t.filter((e,n,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===n).join(" ").trim();/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var c5={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const d5=N.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:s,className:r="",children:a,iconNode:l,...o},c)=>N.createElement("svg",{ref:c,...c5,width:e,height:e,stroke:t,strokeWidth:s?Number(n)*24/Number(e):n,className:hC("lucide",r),...o},[...l.map(([d,u])=>N.createElement(d,u)),...Array.isArray(a)?a:[a]]));/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Y=(t,e)=>{const n=N.forwardRef(({className:s,...r},a)=>N.createElement(d5,{ref:a,iconNode:e,className:hC(`lucide-${o5(t)}`,s),...r}));return n.displayName=`${t}`,n};/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const u5=Y("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Yn=Y("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fC=Y("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mC=Y("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const h5=Y("Bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const f5=Y("Bomb",[["circle",{cx:"11",cy:"13",r:"9",key:"hd149"}],["path",{d:"M14.35 4.65 16.3 2.7a2.41 2.41 0 0 1 3.4 0l1.6 1.6a2.4 2.4 0 0 1 0 3.4l-1.95 1.95",key:"jp4j1b"}],["path",{d:"m22 2-1.5 1.5",key:"ay92ug"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const m5=Y("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const p5=Y("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const g5=Y("Cable",[["path",{d:"M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1",key:"10bnsj"}],["path",{d:"M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9",key:"1eqmu1"}],["path",{d:"M21 21v-2h-4",key:"14zm7j"}],["path",{d:"M3 5h4V3",key:"z442eg"}],["path",{d:"M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3",key:"ebdjd7"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const x5=Y("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const pC=Y("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gC=Y("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vr=Y("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Us=Y("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xC=Y("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const At=Y("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const If=Y("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Tr=Y("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Un=Y("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Om=Y("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Bg=Y("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Eu=Y("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _c=Y("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const cs=Y("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const la=Y("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Iy=Y("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ry=Y("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Rf=Y("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const qn=Y("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Oy=Y("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const on=Y("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Oe=Y("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yC=Y("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const y5=Y("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const We=Y("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const v5=Y("FileType",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 13v-1h6v1",key:"1bb014"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M11 18h2",key:"12mj7e"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vC=Y("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const b5=Y("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bC=Y("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const k1=Y("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ly=Y("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const j5=Y("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const S1=Y("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const N5=Y("Heading1",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"m17 12 3-2v8",key:"1hhhft"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const w5=Y("Heading2",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1",key:"9jr5yi"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const k5=Y("Heading3",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2",key:"68ncm8"}],["path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2",key:"1ejuhz"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const S5=Y("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jC=Y("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Sa=Y("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const bd=Y("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const C5=Y("Italic",[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const E5=Y("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const A5=Y("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const C1=Y("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const D5=Y("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const M5=Y("ListOrdered",[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const T5=Y("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const E1=Y("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const P5=Y("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const NC=Y("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Fs=Y("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const I5=Y("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const R5=Y("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Vc=Y("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const O5=Y("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const L5=Y("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Of=Y("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ge=Y("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Fy=Y("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const F5=Y("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ai=Y("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const z5=Y("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wC=Y("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const zy=Y("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jd=Y("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Nd=Y("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const kC=Y("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const hh=Y("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const SC=Y("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const CC=Y("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lr=Y("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $y=Y("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const rt=Y("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const By=Y("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const $5=Y("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7",key:"6c3vgh"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const B5=Y("Table",[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ee=Y("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Mn=Y("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const EC=Y("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _5=Y("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const AC=Y("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const V5=Y("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _g=Y("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const K5=Y("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const U5=Y("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yo=Y("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ca=Y("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const A1=Y("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Al=Y("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const nn=Y("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _y=Y("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const q5=Y("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** + * @license lucide-react v0.454.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const H5=Y("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function W5(){const{user:t,logout:e,hasPermission:n,isCustomer:s,developerMode:r}=nt(),a=[{to:"/",icon:A5,label:"Dashboard",show:!0,end:!0},{to:"/customers",icon:Ca,label:"Kunden",show:n("customers:read")&&!s},{to:"/contracts",icon:We,label:"Verträge",show:n("contracts:read"),end:!0},{to:"/contracts/cockpit",icon:Tr,label:"Vertrags-Cockpit",show:n("contracts:read")&&!s},{to:"/tasks",icon:s?Vc:_c,label:s?"Support-Anfragen":"Aufgaben",show:n("contracts:read")}],l=[{to:"/developer/database",icon:Rf,label:"Datenbankstruktur"}];return i.jsxs("aside",{className:"w-64 bg-gray-900 text-white min-h-screen flex flex-col",children:[i.jsx("div",{className:"p-4 border-b border-gray-800",children:i.jsx("h1",{className:"text-xl font-bold",children:"OpenCRM"})}),i.jsxs("nav",{className:"flex-1 p-4 overflow-y-auto",children:[i.jsx("ul",{className:"space-y-2",children:a.filter(o=>o.show).map(o=>i.jsx("li",{children:i.jsxs(Am,{to:o.to,end:o.end,className:({isActive:c})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${c?"bg-blue-600 text-white":"text-gray-300 hover:bg-gray-800"}`,children:[i.jsx(o.icon,{className:"w-5 h-5"}),o.label]})},o.to))}),r&&n("developer:access")&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"mt-6 mb-2 px-4",children:i.jsxs("p",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider flex items-center gap-2",children:[i.jsx(la,{className:"w-3 h-3"}),"Entwickler"]})}),i.jsx("ul",{className:"space-y-2",children:l.map(o=>i.jsx("li",{children:i.jsxs(Am,{to:o.to,className:({isActive:c})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${c?"bg-purple-600 text-white":"text-purple-300 hover:bg-gray-800"}`,children:[i.jsx(o.icon,{className:"w-5 h-5"}),o.label]})},o.to))})]}),i.jsx("div",{className:"mt-6 pt-6 border-t border-gray-800",children:i.jsxs(Am,{to:"/settings",className:({isActive:o})=>`flex items-center gap-3 px-4 py-2 rounded-lg transition-colors ${o?"bg-blue-600 text-white":"text-gray-300 hover:bg-gray-800"}`,children:[i.jsx(kC,{className:"w-5 h-5"}),"Einstellungen"]})})]}),i.jsxs("div",{className:"p-4 border-t border-gray-800",children:[i.jsxs("div",{className:"mb-4 text-sm",children:[i.jsx("p",{className:"text-gray-400",children:"Angemeldet als"}),i.jsxs("p",{className:"font-medium",children:[t==null?void 0:t.firstName," ",t==null?void 0:t.lastName]})]}),i.jsxs("button",{onClick:e,className:"flex items-center gap-3 w-full px-4 py-2 text-gray-300 hover:bg-gray-800 rounded-lg transition-colors",children:[i.jsx(P5,{className:"w-5 h-5"}),"Abmelden"]})]})]})}function Q5(){const{settings:t}=uC(),[e,n]=N.useState(!1);N.useEffect(()=>{const r=()=>{window.scrollY>window.innerHeight*t.scrollToTopThreshold?n(!0):n(!1)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[t.scrollToTopThreshold]);const s=()=>{window.scrollTo({top:0,behavior:"smooth"})};return e?i.jsx("button",{onClick:s,className:"fixed bottom-6 right-6 p-3 bg-gray-200 hover:bg-gray-300 text-gray-600 rounded-full shadow-md transition-all duration-300 opacity-70 hover:opacity-100 z-50","aria-label":"Nach oben scrollen",title:"Nach oben",children:i.jsx(If,{className:"w-5 h-5"})}):null}function G5(){return i.jsxs("div",{className:"flex min-h-screen",children:[i.jsx(W5,{}),i.jsx("main",{className:"flex-1 p-8 overflow-auto",children:i.jsx(GM,{})}),i.jsx(Q5,{})]})}const I=N.forwardRef(({className:t="",variant:e="primary",size:n="md",children:s,disabled:r,...a},l)=>{const o="inline-flex items-center justify-center font-medium rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-gray-200 text-gray-900 hover:bg-gray-300 focus:ring-gray-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500",ghost:"bg-transparent text-gray-700 hover:bg-gray-100 focus:ring-gray-500"},d={sm:"px-3 py-1.5 text-sm",md:"px-4 py-2 text-sm",lg:"px-6 py-3 text-base"};return i.jsx("button",{ref:l,className:`${o} ${c[e]} ${d[n]} ${t}`,disabled:r,...a,children:s})});I.displayName="Button";const q=N.forwardRef(({className:t="",label:e,error:n,id:s,onClear:r,...a},l)=>{const o=s||a.name,c=a.type==="date",d=a.value!==void 0&&a.value!==null&&a.value!=="",u=c&&r&&d;return i.jsxs("div",{className:"w-full",children:[e&&i.jsx("label",{htmlFor:o,className:"block text-sm font-medium text-gray-700 mb-1",children:e}),i.jsxs("div",{className:u?"flex gap-2":"",children:[i.jsx("input",{ref:l,id:o,className:`block w-full px-3 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${n?"border-red-500":"border-gray-300"} ${t}`,...a}),u&&i.jsx("button",{type:"button",onClick:r,className:"px-3 py-2 text-gray-400 hover:text-red-500 hover:bg-red-50 border border-gray-300 rounded-lg transition-colors",title:"Datum löschen",children:i.jsx(Ee,{className:"w-4 h-4"})})]}),n&&i.jsx("p",{className:"mt-1 text-sm text-red-600",children:n})]})});q.displayName="Input";function Z({children:t,className:e="",title:n,actions:s}){return i.jsxs("div",{className:`bg-white rounded-lg shadow ${e}`,children:[(n||s)&&i.jsxs("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center justify-between",children:[n&&i.jsx("div",{className:"text-lg font-medium text-gray-900",children:n}),s&&i.jsx("div",{className:"flex items-center gap-2",children:s})]}),i.jsx("div",{className:"p-6",children:t})]})}function J5(){const[t,e]=N.useState(""),[n,s]=N.useState(""),[r,a]=N.useState(""),[l,o]=N.useState(!1),{login:c,customerLogin:d}=nt(),u=fn(),h=async m=>{m.preventDefault(),a(""),o(!0);try{await c(t,n),u("/");return}catch{}try{await d(t,n),u("/")}catch{a("Ungültige Anmeldedaten"),o(!1)}};return i.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-100",children:i.jsxs(Z,{className:"w-full max-w-md",children:[i.jsxs("div",{className:"text-center mb-8",children:[i.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"OpenCRM"}),i.jsx("p",{className:"text-gray-600 mt-2",children:"Melden Sie sich an"})]}),r&&i.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:r}),i.jsxs("form",{onSubmit:h,className:"space-y-4",children:[i.jsx(q,{label:"E-Mail",type:"email",value:t,onChange:m=>e(m.target.value),required:!0,autoComplete:"email"}),i.jsx(q,{label:"Passwort",type:"password",value:n,onChange:m=>s(m.target.value),required:!0,autoComplete:"current-password"}),i.jsx(I,{type:"submit",className:"w-full",disabled:l,children:l?"Anmeldung...":"Anmelden"})]})]})})}function Xe({isOpen:t,onClose:e,title:n,children:s,size:r="md"}){if(N.useEffect(()=>(t?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[t]),!t)return null;const a={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl",xl:"max-w-4xl"};return i.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto",children:i.jsxs("div",{className:"flex min-h-full items-center justify-center p-4",children:[i.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:e}),i.jsxs("div",{className:`relative bg-white rounded-lg shadow-xl w-full ${a[r]}`,children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",children:[i.jsx("h2",{className:"text-lg font-semibold",children:n}),i.jsx(I,{variant:"ghost",size:"sm",onClick:e,children:i.jsx(nn,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"p-6",children:s})]})]})})}function Z5(){var w,S,M,F,R,V;const{user:t,isCustomer:e,isCustomerPortal:n}=nt(),[s,r]=N.useState(!1),{data:a,isLoading:l}=fe({queryKey:["app-settings-public"],queryFn:()=>Ba.getPublic(),enabled:n,staleTime:0}),o=!l&&((w=a==null?void 0:a.data)==null?void 0:w.customerSupportTicketsEnabled)==="true",{data:c}=fe({queryKey:["customers-count"],queryFn:()=>Zt.getAll({limit:1}),enabled:!e}),{data:d}=fe({queryKey:["contracts",e?t==null?void 0:t.customerId:void 0],queryFn:()=>He.getAll(e?{customerId:t==null?void 0:t.customerId}:{limit:1})}),{data:u}=fe({queryKey:["contracts-active",e?t==null?void 0:t.customerId:void 0],queryFn:()=>He.getAll({status:"ACTIVE",...e?{customerId:t==null?void 0:t.customerId}:{limit:1}})}),{data:h}=fe({queryKey:["contracts-pending",e?t==null?void 0:t.customerId:void 0],queryFn:()=>He.getAll({status:"PENDING",...e?{customerId:t==null?void 0:t.customerId}:{limit:1}})}),{data:m}=fe({queryKey:["task-stats"],queryFn:()=>ht.getStats()}),{data:f}=fe({queryKey:["contract-cockpit"],queryFn:()=>He.getCockpit(),enabled:!e,staleTime:0}),{ownContracts:p,representedContracts:g}=N.useMemo(()=>{if(!n||!(d!=null&&d.data))return{ownContracts:[],representedContracts:[]};const D=[],z={};for(const C of d.data)if(C.customerId===(t==null?void 0:t.customerId))D.push(C);else{const _=C.customerId;if(!z[_]){const K=C.customer?C.customer.companyName||`${C.customer.firstName} ${C.customer.lastName}`:`Kunde ${_}`;z[_]={customerName:K,contracts:[]}}z[_].contracts.push(C)}return{ownContracts:D,representedContracts:Object.values(z).sort((C,_)=>C.customerName.localeCompare(_.customerName))}},[d==null?void 0:d.data,n,t==null?void 0:t.customerId]),x=N.useMemo(()=>p.filter(D=>D.status==="ACTIVE").length,[p]),y=N.useMemo(()=>p.filter(D=>D.status==="PENDING").length,[p]),v=N.useMemo(()=>p.filter(D=>D.status==="EXPIRED").length,[p]),b=N.useMemo(()=>g.reduce((D,z)=>D+z.contracts.length,0),[g]),j=N.useMemo(()=>g.reduce((D,z)=>D+z.contracts.filter(C=>C.status==="ACTIVE").length,0),[g]),k=N.useMemo(()=>g.reduce((D,z)=>D+z.contracts.filter(C=>C.status==="EXPIRED").length,0),[g]),E=((S=m==null?void 0:m.data)==null?void 0:S.openCount)||0,T=D=>i.jsx(Z,{className:D.link?"cursor-pointer hover:shadow-md transition-shadow":"",children:D.link?i.jsx(Me,{to:D.link,className:"block",children:i.jsxs("div",{className:"flex items-center",children:[i.jsx("div",{className:`p-3 rounded-lg ${D.color}`,children:i.jsx(D.icon,{className:"w-6 h-6 text-white"})}),i.jsxs("div",{className:"ml-4",children:[i.jsx("p",{className:"text-sm text-gray-500",children:D.label}),i.jsx("p",{className:"text-2xl font-bold",children:D.value})]})]})}):i.jsxs("div",{className:"flex items-center",children:[i.jsx("div",{className:`p-3 rounded-lg ${D.color}`,children:i.jsx(D.icon,{className:"w-6 h-6 text-white"})}),i.jsxs("div",{className:"ml-4",children:[i.jsx("p",{className:"text-sm text-gray-500",children:D.label}),i.jsx("p",{className:"text-2xl font-bold",children:D.value})]})]})},D.label);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsxs("h1",{className:"text-2xl font-bold",children:["Willkommen, ",t==null?void 0:t.firstName,"!"]}),n&&o&&i.jsxs(I,{onClick:()=>r(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Support-Anfrage"]})]}),n?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mb-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(yo,{className:"w-5 h-5 text-blue-600"}),i.jsx("h2",{className:"text-lg font-semibold",children:"Meine Verträge"})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[T({label:"Eigene Verträge",value:p.length,icon:We,color:"bg-blue-500",link:"/contracts"}),T({label:"Davon aktiv",value:x,icon:Un,color:"bg-green-500"}),T({label:"Davon ausstehend",value:y,icon:cs,color:"bg-yellow-500"}),T({label:"Davon abgelaufen",value:v,icon:Bg,color:"bg-red-500"})]})]}),b>0&&i.jsxs("div",{className:"mb-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(Ca,{className:"w-5 h-5 text-purple-600"}),i.jsx("h2",{className:"text-lg font-semibold",children:"Fremdverträge"})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[T({label:"Fremdverträge",value:b,icon:Ca,color:"bg-purple-500",link:"/contracts"}),T({label:"Davon aktiv",value:j,icon:Un,color:"bg-green-500"}),i.jsx("div",{className:"hidden lg:block"}),T({label:"Davon abgelaufen",value:k,icon:Bg,color:"bg-red-500"})]})]}),i.jsxs("div",{className:"mb-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(Vc,{className:"w-5 h-5 text-orange-600"}),i.jsx("h2",{className:"text-lg font-semibold",children:"Support-Anfragen"})]}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:T({label:"Offene Anfragen",value:E,icon:Vc,color:"bg-orange-500",link:"/tasks"})})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6",children:[T({label:"Kunden",value:((M=c==null?void 0:c.pagination)==null?void 0:M.total)||0,icon:Ca,color:"bg-blue-500",link:"/customers"}),T({label:"Verträge gesamt",value:((F=d==null?void 0:d.pagination)==null?void 0:F.total)||0,icon:We,color:"bg-purple-500",link:"/contracts"}),T({label:"Aktive Verträge",value:((R=u==null?void 0:u.pagination)==null?void 0:R.total)||0,icon:Un,color:"bg-green-500"}),T({label:"Ausstehende Verträge",value:((V=h==null?void 0:h.pagination)==null?void 0:V.total)||0,icon:Tr,color:"bg-yellow-500"})]}),(f==null?void 0:f.data)&&i.jsxs("div",{className:"mb-6",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Tr,{className:"w-5 h-5 text-red-500"}),i.jsx("h2",{className:"text-lg font-semibold",children:"Vertrags-Cockpit"})]}),i.jsx(Me,{to:"/contracts/cockpit",className:"text-sm text-blue-600 hover:underline",children:"Alle anzeigen"})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsx(Z,{className:"cursor-pointer hover:shadow-md transition-shadow",children:i.jsx(Me,{to:"/contracts/cockpit?filter=critical",className:"block",children:i.jsxs("div",{className:"flex items-center",children:[i.jsx("div",{className:"p-3 rounded-lg bg-red-100",children:i.jsx(Tr,{className:"w-6 h-6 text-red-500"})}),i.jsxs("div",{className:"ml-4",children:[i.jsxs("p",{className:"text-sm text-gray-500",children:["Kritisch (<",f.data.thresholds.criticalDays," Tage)"]}),i.jsx("p",{className:"text-2xl font-bold text-red-600",children:f.data.summary.criticalCount})]})]})})}),i.jsx(Z,{className:"cursor-pointer hover:shadow-md transition-shadow",children:i.jsx(Me,{to:"/contracts/cockpit?filter=warning",className:"block",children:i.jsxs("div",{className:"flex items-center",children:[i.jsx("div",{className:"p-3 rounded-lg bg-yellow-100",children:i.jsx(Mn,{className:"w-6 h-6 text-yellow-500"})}),i.jsxs("div",{className:"ml-4",children:[i.jsxs("p",{className:"text-sm text-gray-500",children:["Warnung (<",f.data.thresholds.warningDays," Tage)"]}),i.jsx("p",{className:"text-2xl font-bold text-yellow-600",children:f.data.summary.warningCount})]})]})})}),i.jsx(Z,{className:"cursor-pointer hover:shadow-md transition-shadow",children:i.jsx(Me,{to:"/contracts/cockpit?filter=ok",className:"block",children:i.jsxs("div",{className:"flex items-center",children:[i.jsx("div",{className:"p-3 rounded-lg bg-green-100",children:i.jsx(Un,{className:"w-6 h-6 text-green-500"})}),i.jsxs("div",{className:"ml-4",children:[i.jsxs("p",{className:"text-sm text-gray-500",children:["OK (<",f.data.thresholds.okDays," Tage)"]}),i.jsx("p",{className:"text-2xl font-bold text-green-600",children:f.data.summary.okCount})]})]})})}),i.jsx(Z,{className:"cursor-pointer hover:shadow-md transition-shadow",children:i.jsx(Me,{to:"/contracts/cockpit",className:"block",children:i.jsxs("div",{className:"flex items-center",children:[i.jsx("div",{className:"p-3 rounded-lg bg-gray-100",children:i.jsx(We,{className:"w-6 h-6 text-gray-500"})}),i.jsxs("div",{className:"ml-4",children:[i.jsx("p",{className:"text-sm text-gray-500",children:"Handlungsbedarf"}),i.jsx("p",{className:"text-2xl font-bold text-gray-600",children:f.data.summary.totalContracts})]})]})})})]})]}),i.jsxs("div",{className:"mb-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(_c,{className:"w-5 h-5 text-orange-600"}),i.jsx("h2",{className:"text-lg font-semibold",children:"Aufgaben"})]}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:T({label:"Offene Aufgaben",value:E,icon:_c,color:"bg-orange-500",link:"/tasks"})})]})]}),n&&i.jsx(Y5,{isOpen:s,onClose:()=>r(!1)})]})}function Y5({isOpen:t,onClose:e}){const{user:n}=nt(),s=fn(),r=ye(),[a,l]=N.useState("own"),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,p]=N.useState(!1),[g,x]=N.useState(""),{data:y}=fe({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>He.getAll({customerId:n==null?void 0:n.customerId}),enabled:t}),v=N.useMemo(()=>{if(!(y!=null&&y.data))return{own:[],represented:{}};const w=[],S={};for(const M of y.data)if(M.customerId===(n==null?void 0:n.customerId))w.push(M);else{if(!S[M.customerId]){const F=M.customer?M.customer.companyName||`${M.customer.firstName} ${M.customer.lastName}`:`Kunde ${M.customerId}`;S[M.customerId]={name:F,contracts:[]}}S[M.customerId].contracts.push(M)}return{own:w,represented:S}},[y==null?void 0:y.data,n==null?void 0:n.customerId]),b=Object.keys(v.represented).length>0,j=N.useMemo(()=>{var w;return a==="own"?v.own:((w=v.represented[a])==null?void 0:w.contracts)||[]},[a,v]),k=N.useMemo(()=>{if(!g)return j;const w=g.toLowerCase();return j.filter(S=>S.contractNumber.toLowerCase().includes(w)||(S.providerName||"").toLowerCase().includes(w)||(S.tariffName||"").toLowerCase().includes(w))},[j,g]),E=async()=>{if(!(!o||!d.trim())){p(!0);try{await ht.createSupportTicket(o,{title:d.trim(),description:h.trim()||void 0}),r.invalidateQueries({queryKey:["task-stats"]}),r.invalidateQueries({queryKey:["all-tasks"]}),e(),u(""),m(""),c(null),l("own"),s(`/contracts/${o}`)}catch(w){console.error("Fehler beim Erstellen der Support-Anfrage:",w),alert("Fehler beim Erstellen der Support-Anfrage. Bitte versuchen Sie es erneut.")}finally{p(!1)}}},T=()=>{u(""),m(""),c(null),l("own"),x(""),e()};return i.jsx(Xe,{isOpen:t,onClose:T,title:"Neue Support-Anfrage",children:i.jsxs("div",{className:"space-y-4",children:[b&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde"}),i.jsxs("select",{value:a,onChange:w=>{const S=w.target.value;l(S==="own"?"own":parseInt(S)),c(null),x("")},className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",children:[i.jsx("option",{value:"own",children:"Eigene Verträge"}),Object.entries(v.represented).map(([w,{name:S}])=>i.jsx("option",{value:w,children:S},w))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),i.jsx(q,{placeholder:"Vertrag suchen...",value:g,onChange:w=>x(w.target.value),className:"mb-2"}),i.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-lg",children:k.length>0?k.map(w=>i.jsxs("div",{onClick:()=>c(w.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${o===w.id?"bg-blue-50 border-blue-200":""}`,children:[i.jsx("div",{className:"font-medium",children:w.contractNumber}),i.jsxs("div",{className:"text-sm text-gray-500",children:[w.providerName||"Kein Anbieter",w.tariffName&&` - ${w.tariffName}`]})]},w.id)):i.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Verträge gefunden."})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),i.jsx(q,{value:d,onChange:w=>u(w.target.value),placeholder:"Kurze Beschreibung Ihres Anliegens"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),i.jsx("textarea",{value:h,onChange:w=>m(w.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:4,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:T,children:"Abbrechen"}),i.jsx(I,{onClick:E,disabled:!o||!d.trim()||f,children:f?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function je({children:t,variant:e="default",className:n="",onClick:s}){const r={default:"bg-gray-100 text-gray-800",success:"bg-green-100 text-green-800",warning:"bg-yellow-100 text-yellow-800",danger:"bg-red-100 text-red-800",info:"bg-blue-100 text-blue-800"};return i.jsx("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r[e]} ${n}`,onClick:s,children:t})}function X5(){const[t,e]=N.useState(""),[n,s]=N.useState(""),[r,a]=N.useState(1),{hasPermission:l}=nt(),{data:o,isLoading:c}=fe({queryKey:["customers",t,n,r],queryFn:()=>Zt.getAll({search:t,type:n||void 0,page:r,limit:20})});return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold",children:"Kunden"}),l("customers:create")&&i.jsx(Me,{to:"/customers/new",children:i.jsxs(I,{children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neuer Kunde"]})})]}),i.jsx(Z,{className:"mb-6",children:i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx(q,{placeholder:"Suchen...",value:t,onChange:d=>e(d.target.value),className:"flex-1"}),i.jsxs("select",{value:n,onChange:d=>s(d.target.value),className:"px-3 py-2 border border-gray-300 rounded-lg w-28 flex-shrink-0",children:[i.jsx("option",{value:"",children:"Alle"}),i.jsx("option",{value:"PRIVATE",children:"Privat"}),i.jsx("option",{value:"BUSINESS",children:"Firma"})]}),i.jsx(I,{variant:"secondary",className:"flex-shrink-0",children:i.jsx(jd,{className:"w-4 h-4"})})]})}),i.jsx(Z,{children:c?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):o!=null&&o.data&&o.data.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kundennr."}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Typ"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"E-Mail"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Verträge"}),i.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),i.jsx("tbody",{children:o.data.map(d=>{var u;return i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsx("td",{className:"py-3 px-4 font-mono text-sm",children:d.customerNumber}),i.jsx("td",{className:"py-3 px-4",children:d.type==="BUSINESS"&&d.companyName?d.companyName:`${d.firstName} ${d.lastName}`}),i.jsx("td",{className:"py-3 px-4",children:i.jsx(je,{variant:d.type==="BUSINESS"?"info":"default",children:d.type==="BUSINESS"?"Firma":"Privat"})}),i.jsx("td",{className:"py-3 px-4",children:d.email||"-"}),i.jsx("td",{className:"py-3 px-4",children:((u=d._count)==null?void 0:u.contracts)||0}),i.jsx("td",{className:"py-3 px-4 text-right",children:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Me,{to:`/customers/${d.id}`,children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(Oe,{className:"w-4 h-4"})})}),l("customers:update")&&i.jsx(Me,{to:`/customers/${d.id}/edit`,children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(rt,{className:"w-4 h-4"})})})]})})]},d.id)})})]})}),o.pagination&&o.pagination.totalPages>1&&i.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[i.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",o.pagination.page," von ",o.pagination.totalPages," (",o.pagination.total," Einträge)"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>a(d=>Math.max(1,d-1)),disabled:r===1,children:"Zurück"}),i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>a(d=>d+1),disabled:r>=o.pagination.totalPages,children:"Weiter"})]})]})]}):i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Kunden gefunden."})})]})}function eR({emails:t,selectedEmailId:e,onSelectEmail:n,onEmailDeleted:s,isLoading:r,folder:a="INBOX",accountId:l}){const o=a==="SENT",[c,d]=N.useState(null),{hasPermission:u}=nt(),h=S=>{if(o)try{const M=JSON.parse(S.toAddresses);if(M.length>0)return`An: ${M[0]}${M.length>1?` (+${M.length-1})`:""}`}catch{return"An: (Unbekannt)"}return S.fromName||S.fromAddress},m=ye(),f=G({mutationFn:S=>Be.toggleStar(S),onSuccess:(S,M)=>{m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["email",M]})}}),p=G({mutationFn:({emailId:S,isRead:M})=>Be.markAsRead(S,M),onSuccess:(S,M)=>{m.invalidateQueries({queryKey:["emails"]}),m.invalidateQueries({queryKey:["email",M.emailId]}),l&&m.invalidateQueries({queryKey:["folder-counts",l]})}}),g=G({mutationFn:S=>Be.delete(S),onSuccess:(S,M)=>{m.invalidateQueries({queryKey:["emails"]}),l&&m.invalidateQueries({queryKey:["folder-counts",l]}),Ue.success("E-Mail in Papierkorb verschoben"),d(null),s==null||s(M)},onError:S=>{console.error("Delete error:",S),Ue.error(S.message||"Fehler beim Löschen der E-Mail"),d(null)}}),x=G({mutationFn:S=>Be.unassignFromContract(S),onSuccess:()=>{m.invalidateQueries({queryKey:["emails"]}),Ue.success("Vertragszuordnung aufgehoben")},onError:S=>{console.error("Unassign error:",S),Ue.error(S.message||"Fehler beim Aufheben der Zuordnung")}}),y=(S,M)=>{S.stopPropagation(),x.mutate(M)},v=(S,M)=>{S.stopPropagation(),d(M)},b=S=>{S.stopPropagation(),c&&g.mutate(c)},j=S=>{S.stopPropagation(),d(null)},k=S=>{const M=new Date(S),F=new Date;return M.toDateString()===F.toDateString()?M.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):M.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},E=(S,M)=>{S.stopPropagation(),f.mutate(M)},T=(S,M)=>{S.stopPropagation(),p.mutate({emailId:M.id,isRead:!M.isRead})},w=S=>{S.isRead||p.mutate({emailId:S.id,isRead:!0}),n(S)};return r?i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):t.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[i.jsx(Fs,{className:"w-12 h-12 mb-2 opacity-50"}),i.jsx("p",{children:"Keine E-Mails vorhanden"})]}):i.jsxs("div",{className:"divide-y divide-gray-200",children:[t.map(S=>i.jsxs("div",{onClick:()=>w(S),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",e===S.id?"bg-blue-100":["hover:bg-gray-100",S.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:e===S.id?"4px solid #2563eb":"4px solid transparent"},children:[i.jsx("button",{onClick:M=>T(M,S),className:` + flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 + ${S.isRead?"text-gray-400":"text-blue-600"} + `,title:S.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:S.isRead?i.jsx(NC,{className:"w-4 h-4"}):i.jsx(Fs,{className:"w-4 h-4"})}),i.jsx("button",{onClick:M=>E(M,S.id),className:` + flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 + ${S.isStarred?"text-yellow-500":"text-gray-400"} + `,title:S.isStarred?"Stern entfernen":"Als wichtig markieren",children:i.jsx(By,{className:`w-4 h-4 ${S.isStarred?"fill-current":""}`})}),u("emails:delete")&&i.jsx("button",{onClick:M=>v(M,S.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"E-Mail löschen",children:i.jsx(Ee,{className:"w-4 h-4"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[i.jsx("span",{className:`text-sm truncate ${S.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:h(S)}),i.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:k(S.receivedAt)})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`text-sm truncate ${S.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:S.subject||"(Kein Betreff)"}),S.hasAttachments&&i.jsx(Of,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),S.contract&&i.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[i.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:S.contract.contractNumber}),(a==="INBOX"||a==="SENT"&&!S.isAutoAssigned)&&i.jsx("button",{onClick:M=>y(M,S.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:x.isPending,children:i.jsx(nn,{className:"w-3.5 h-3.5"})})]})]}),i.jsx(At,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},S.id)),c&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),i.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:j,disabled:g.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"danger",onClick:b,disabled:g.isPending,children:g.isPending?"Löschen...":"Löschen"})]})]})})]})}const Fe=N.forwardRef(({className:t="",label:e,error:n,options:s,id:r,placeholder:a="Bitte wählen...",...l},o)=>{const c=r||l.name,d=/\bw-\d+\b|\bw-\[|\bflex-/.test(t);return i.jsxs("div",{className:d?t:"w-full",children:[e&&i.jsx("label",{htmlFor:c,className:"block text-sm font-medium text-gray-700 mb-1",children:e}),i.jsxs("select",{ref:o,id:c,className:`block w-full px-3 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${n?"border-red-500":"border-gray-300"}`,...l,children:[i.jsx("option",{value:"",children:a}),s.map(u=>i.jsx("option",{value:u.value,children:u.label},u.value))]}),n&&i.jsx("p",{className:"mt-1 text-sm text-red-600",children:n})]})});Fe.displayName="Select";function tR({isOpen:t,onClose:e,emailId:n,attachmentFilename:s,onSuccess:r}){var F,R,V;const[a,l]=N.useState(null),[o,c]=N.useState(new Set(["customer"])),[d,u]=N.useState("document"),[h,m]=N.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),f=ye(),{data:p,isLoading:g,error:x}=fe({queryKey:["attachment-targets",n],queryFn:()=>Be.getAttachmentTargets(n),enabled:t}),y=p==null?void 0:p.data,v=((F=y==null?void 0:y.contract)==null?void 0:F.type)==="ELECTRICITY"||((R=y==null?void 0:y.contract)==null?void 0:R.type)==="GAS",b=G({mutationFn:()=>{if(!a)throw new Error("Kein Ziel ausgewählt");return Be.saveAttachmentTo(n,s,{entityType:a.entityType,entityId:a.entityId,targetKey:a.targetKey})},onSuccess:()=>{var D,z;Ue.success("Anhang gespeichert"),f.invalidateQueries({queryKey:["attachment-targets",n]}),f.invalidateQueries({queryKey:["customers"]}),f.invalidateQueries({queryKey:["contracts"]}),(D=y==null?void 0:y.customer)!=null&&D.id&&f.invalidateQueries({queryKey:["customer",y.customer.id.toString()]}),(z=y==null?void 0:y.contract)!=null&&z.id&&f.invalidateQueries({queryKey:["contract",y.contract.id.toString()]}),r==null||r(),k()},onError:D=>{Ue.error(D.message||"Fehler beim Speichern")}}),j=G({mutationFn:()=>Be.saveAttachmentAsInvoice(n,s,{invoiceDate:h.invoiceDate,invoiceType:h.invoiceType,notes:h.notes||void 0}),onSuccess:()=>{var D;Ue.success("Anhang als Rechnung gespeichert"),f.invalidateQueries({queryKey:["attachment-targets",n]}),f.invalidateQueries({queryKey:["customers"]}),f.invalidateQueries({queryKey:["contracts"]}),(D=y==null?void 0:y.contract)!=null&&D.id&&f.invalidateQueries({queryKey:["contract",y.contract.id.toString()]}),r==null||r(),k()},onError:D=>{Ue.error(D.message||"Fehler beim Speichern der Rechnung")}}),k=()=>{l(null),u("document"),m({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),e()},E=D=>{const z=new Set(o);z.has(D)?z.delete(D):z.add(D),c(z)},T=(D,z,C,_)=>{l({entityType:D,entityId:C,targetKey:z.key,hasDocument:z.hasDocument,label:_?`${_} → ${z.label}`:z.label})},w=(D,z,C,_)=>D.map(K=>{const B=(a==null?void 0:a.entityType)===z&&(a==null?void 0:a.entityId)===C&&(a==null?void 0:a.targetKey)===K.key;return i.jsxs("div",{onClick:()=>T(z,K,C,_),className:` + flex items-center gap-3 p-3 cursor-pointer transition-colors rounded-lg ml-4 + ${B?"bg-blue-100 ring-2 ring-blue-500":"hover:bg-gray-100"} + `,children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-gray-900",children:K.label}),K.hasDocument&&i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[i.jsx(Mn,{className:"w-3 h-3"}),"Vorhanden"]})]})}),B&&i.jsx(Vr,{className:"w-5 h-5 text-blue-600"})]},K.key)}),S=(D,z)=>i.jsxs("div",{className:"mb-2",children:[i.jsx("div",{className:"text-sm font-medium text-gray-700 px-3 py-1 bg-gray-50 rounded",children:D.label}),w(D.slots,z,D.id,D.label)]},D.id),M=(D,z,C,_,K=!1)=>{const B=o.has(z);return i.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>E(z),className:"w-full flex items-center gap-2 p-3 bg-gray-50 hover:bg-gray-100 transition-colors",children:[B?i.jsx(Us,{className:"w-4 h-4 text-gray-500"}):i.jsx(At,{className:"w-4 h-4 text-gray-500"}),C,i.jsx("span",{className:"font-medium text-gray-900",children:D})]}),B&&i.jsx("div",{className:"p-2",children:K?i.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):_})]})};return i.jsx(Xe,{isOpen:t,onClose:k,title:"Anhang speichern unter",size:"lg",children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"p-3 bg-gray-50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-gray-600",children:[i.jsx("span",{className:"font-medium",children:"Datei:"})," ",s]})}),g&&i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}),x&&i.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),y&&i.jsxs(i.Fragment,{children:[v&&i.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[i.jsxs("button",{onClick:()=>u("document"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${d==="document"?"bg-white text-blue-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(We,{className:"w-4 h-4"}),"Als Dokument"]}),i.jsxs("button",{onClick:()=>u("invoice"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${d==="invoice"?"bg-white text-green-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Fy,{className:"w-4 h-4"}),"Als Rechnung"]})]}),d==="document"&&i.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[M(`Kunde: ${y.customer.name}`,"customer",i.jsx(yo,{className:"w-4 h-4 text-blue-600"}),w(y.customer.slots,"customer"),y.customer.slots.length===0),M("Ausweisdokumente","identityDocuments",i.jsx(jC,{className:"w-4 h-4 text-green-600"}),y.identityDocuments.map(D=>S(D,"identityDocument")),y.identityDocuments.length===0),M("Bankkarten","bankCards",i.jsx(Ry,{className:"w-4 h-4 text-purple-600"}),y.bankCards.map(D=>S(D,"bankCard")),y.bankCards.length===0),y.contract&&M(`Vertrag: ${y.contract.contractNumber}`,"contract",i.jsx(We,{className:"w-4 h-4 text-orange-600"}),w(y.contract.slots,"contract"),y.contract.slots.length===0),!y.contract&&i.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[i.jsx(We,{className:"w-4 h-4 inline-block mr-2 text-gray-400"}),"E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um Vertragsdokumente als Ziel auswählen zu können."]})]}),d==="invoice"&&v&&i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-green-700",children:["Der Anhang wird als Rechnung für den Vertrag ",i.jsx("strong",{children:(V=y.contract)==null?void 0:V.contractNumber})," gespeichert."]})}),i.jsx(q,{label:"Rechnungsdatum",type:"date",value:h.invoiceDate,onChange:D=>m({...h,invoiceDate:D.target.value}),required:!0}),i.jsx(Fe,{label:"Rechnungstyp",value:h.invoiceType,onChange:D=>m({...h,invoiceType:D.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),i.jsx(q,{label:"Notizen (optional)",value:h.notes,onChange:D=>m({...h,notes:D.target.value}),placeholder:"Optionale Anmerkungen..."})]})]}),d==="document"&&(a==null?void 0:a.hasDocument)&&i.jsxs("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2",children:[i.jsx(Mn,{className:"w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-sm text-yellow-800",children:[i.jsx("strong",{children:"Achtung:"})," An diesem Feld ist bereits ein Dokument hinterlegt. Das vorhandene Dokument wird durch den neuen Anhang ersetzt."]})]}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:k,children:"Abbrechen"}),d==="document"?i.jsx(I,{onClick:()=>b.mutate(),disabled:!a||b.isPending||j.isPending,children:b.isPending?"Wird gespeichert...":"Speichern"}):i.jsx(I,{onClick:()=>j.mutate(),disabled:!h.invoiceDate||b.isPending||j.isPending,children:j.isPending?"Wird gespeichert...":"Als Rechnung speichern"})]})]})})}function nR({isOpen:t,onClose:e,emailId:n,onSuccess:s}){var F,R,V;const[r,a]=N.useState(null),[l,o]=N.useState(new Set(["customer"])),[c,d]=N.useState("document"),[u,h]=N.useState({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),m=ye(),{data:f,isLoading:p,error:g}=fe({queryKey:["attachment-targets",n],queryFn:()=>Be.getAttachmentTargets(n),enabled:t}),x=f==null?void 0:f.data,y=((F=x==null?void 0:x.contract)==null?void 0:F.type)==="ELECTRICITY"||((R=x==null?void 0:x.contract)==null?void 0:R.type)==="GAS",v=G({mutationFn:()=>{if(!r)throw new Error("Kein Ziel ausgewählt");return Be.saveEmailAsPdf(n,{entityType:r.entityType,entityId:r.entityId,targetKey:r.targetKey})},onSuccess:()=>{var D,z;Ue.success("E-Mail als PDF gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(D=x==null?void 0:x.customer)!=null&&D.id&&m.invalidateQueries({queryKey:["customer",x.customer.id.toString()]}),(z=x==null?void 0:x.contract)!=null&&z.id&&m.invalidateQueries({queryKey:["contract",x.contract.id.toString()]}),s==null||s(),j()},onError:D=>{Ue.error(D.message||"Fehler beim Speichern")}}),b=G({mutationFn:()=>Be.saveEmailAsInvoice(n,{invoiceDate:u.invoiceDate,invoiceType:u.invoiceType,notes:u.notes||void 0}),onSuccess:()=>{var D;Ue.success("E-Mail als Rechnung gespeichert"),m.invalidateQueries({queryKey:["attachment-targets",n]}),m.invalidateQueries({queryKey:["customers"]}),m.invalidateQueries({queryKey:["contracts"]}),(D=x==null?void 0:x.contract)!=null&&D.id&&m.invalidateQueries({queryKey:["contract",x.contract.id.toString()]}),s==null||s(),j()},onError:D=>{Ue.error(D.message||"Fehler beim Speichern der Rechnung")}}),j=()=>{a(null),d("document"),h({invoiceDate:new Date().toISOString().split("T")[0],invoiceType:"INTERIM",notes:""}),e()},k=D=>{const z=new Set(l);z.has(D)?z.delete(D):z.add(D),o(z)},E=(D,z,C,_)=>{a({entityType:D,entityId:C,targetKey:z.key,hasDocument:z.hasDocument,label:_?`${_} → ${z.label}`:z.label})},T=(D,z,C,_)=>D.map(K=>{const B=(r==null?void 0:r.entityType)===z&&(r==null?void 0:r.entityId)===C&&(r==null?void 0:r.targetKey)===K.key;return i.jsxs("div",{onClick:()=>E(z,K,C,_),className:` + flex items-center gap-3 p-3 cursor-pointer transition-colors rounded-lg ml-4 + ${B?"bg-blue-100 ring-2 ring-blue-500":"hover:bg-gray-100"} + `,children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-gray-900",children:K.label}),K.hasDocument&&i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[i.jsx(Mn,{className:"w-3 h-3"}),"Vorhanden"]})]})}),B&&i.jsx(Vr,{className:"w-5 h-5 text-blue-600"})]},K.key)}),w=(D,z)=>i.jsxs("div",{className:"mb-2",children:[i.jsx("div",{className:"text-sm font-medium text-gray-700 px-3 py-1 bg-gray-50 rounded",children:D.label}),T(D.slots,z,D.id,D.label)]},D.id),S=(D,z,C,_,K=!1)=>{const B=l.has(z);return i.jsxs("div",{className:"border border-gray-200 rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>k(z),className:"w-full flex items-center gap-2 p-3 bg-gray-50 hover:bg-gray-100 transition-colors",children:[B?i.jsx(Us,{className:"w-4 h-4 text-gray-500"}):i.jsx(At,{className:"w-4 h-4 text-gray-500"}),C,i.jsx("span",{className:"font-medium text-gray-900",children:D})]}),B&&i.jsx("div",{className:"p-2",children:K?i.jsx("p",{className:"text-sm text-gray-500 text-center py-4",children:"Keine Einträge vorhanden"}):_})]})},M=v.isPending||b.isPending;return i.jsx(Xe,{isOpen:t,onClose:j,title:"E-Mail als PDF speichern",size:"lg",children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"p-3 bg-blue-50 rounded-lg",children:i.jsx("p",{className:"text-sm text-blue-700",children:"Die E-Mail wird als PDF exportiert (inkl. Absender, Empfänger, Datum und Inhalt) und im gewählten Dokumentenfeld gespeichert."})}),p&&i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}),g&&i.jsx("div",{className:"p-4 bg-red-50 text-red-700 rounded-lg",children:"Fehler beim Laden der Dokumentziele"}),x&&i.jsxs(i.Fragment,{children:[y&&i.jsxs("div",{className:"flex gap-2 p-1 bg-gray-100 rounded-lg",children:[i.jsxs("button",{onClick:()=>d("document"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${c==="document"?"bg-white text-blue-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(We,{className:"w-4 h-4"}),"Als Dokument"]}),i.jsxs("button",{onClick:()=>d("invoice"),className:`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${c==="invoice"?"bg-white text-green-600 shadow-sm":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Fy,{className:"w-4 h-4"}),"Als Rechnung"]})]}),c==="document"&&i.jsxs("div",{className:"space-y-3 max-h-96 overflow-auto",children:[S(`Kunde: ${x.customer.name}`,"customer",i.jsx(yo,{className:"w-4 h-4 text-blue-600"}),T(x.customer.slots,"customer"),x.customer.slots.length===0),S("Ausweisdokumente","identityDocuments",i.jsx(jC,{className:"w-4 h-4 text-green-600"}),x.identityDocuments.map(D=>w(D,"identityDocument")),x.identityDocuments.length===0),S("Bankkarten","bankCards",i.jsx(Ry,{className:"w-4 h-4 text-purple-600"}),x.bankCards.map(D=>w(D,"bankCard")),x.bankCards.length===0),x.contract&&S(`Vertrag: ${x.contract.contractNumber}`,"contract",i.jsx(We,{className:"w-4 h-4 text-orange-600"}),T(x.contract.slots,"contract"),x.contract.slots.length===0),!x.contract&&i.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg text-sm text-gray-600",children:[i.jsx(We,{className:"w-4 h-4 inline-block mr-2 text-gray-400"}),"E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um Vertragsdokumente als Ziel auswählen zu können."]})]}),c==="invoice"&&y&&i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"p-3 bg-green-50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-green-700",children:["Die E-Mail wird als Rechnung für den Vertrag ",i.jsx("strong",{children:(V=x.contract)==null?void 0:V.contractNumber})," gespeichert."]})}),i.jsx(q,{label:"Rechnungsdatum",type:"date",value:u.invoiceDate,onChange:D=>h({...u,invoiceDate:D.target.value}),required:!0}),i.jsx(Fe,{label:"Rechnungstyp",value:u.invoiceType,onChange:D=>h({...u,invoiceType:D.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"}]}),i.jsx(q,{label:"Notizen (optional)",value:u.notes,onChange:D=>h({...u,notes:D.target.value}),placeholder:"Optionale Anmerkungen..."})]})]}),c==="document"&&(r==null?void 0:r.hasDocument)&&i.jsxs("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2",children:[i.jsx(Mn,{className:"w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-sm text-yellow-800",children:[i.jsx("strong",{children:"Achtung:"})," An diesem Feld ist bereits ein Dokument hinterlegt. Das vorhandene Dokument wird durch die PDF ersetzt."]})]}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:j,children:"Abbrechen"}),c==="document"?i.jsx(I,{onClick:()=>v.mutate(),disabled:!r||M,children:M?"Wird erstellt...":"Als PDF speichern"}):i.jsx(I,{onClick:()=>b.mutate(),disabled:!u.invoiceDate||M,children:M?"Wird erstellt...":"Als Rechnung speichern"})]})]})})}function DC({email:t,onReply:e,onAssignContract:n,onDeleted:s,isSentFolder:r=!1,isContractView:a=!1,isTrashView:l=!1,onRestored:o,accountId:c}){const[d,u]=N.useState(!0),[h,m]=N.useState(t.isStarred),[f,p]=N.useState(!1),[g,x]=N.useState(!1),[y,v]=N.useState(!1),[b,j]=N.useState(null),[k,E]=N.useState(!1),T=ye(),{hasPermission:w}=nt();N.useEffect(()=>{m(t.isStarred)},[t.id,t.isStarred]);const S=G({mutationFn:()=>Be.toggleStar(t.id),onMutate:()=>{m(W=>!W)},onSuccess:()=>{T.invalidateQueries({queryKey:["emails"]}),T.invalidateQueries({queryKey:["email",t.id]})},onError:()=>{m(t.isStarred)}}),M=G({mutationFn:()=>Be.unassignFromContract(t.id),onSuccess:()=>{T.invalidateQueries({queryKey:["emails"]}),T.invalidateQueries({queryKey:["email",t.id]}),t.contractId&&T.invalidateQueries({queryKey:["contract-folder-counts",t.contractId]}),Ue.success("Vertragszuordnung aufgehoben")},onError:W=>{console.error("Unassign error:",W),Ue.error(W.message||"Fehler beim Aufheben der Zuordnung")}}),F=G({mutationFn:()=>Be.delete(t.id),onSuccess:()=>{T.invalidateQueries({queryKey:["emails"]}),c&&T.invalidateQueries({queryKey:["folder-counts",c]}),t.contractId&&T.invalidateQueries({queryKey:["contract-folder-counts",t.contractId]}),Ue.success("E-Mail in Papierkorb verschoben"),p(!1),s==null||s()},onError:W=>{console.error("Delete error:",W),Ue.error(W.message||"Fehler beim Löschen der E-Mail"),p(!1)}}),R=G({mutationFn:()=>Be.restore(t.id),onSuccess:()=>{T.invalidateQueries({queryKey:["emails"]}),c&&T.invalidateQueries({queryKey:["folder-counts",c]}),t.contractId&&T.invalidateQueries({queryKey:["contract-folder-counts",t.contractId]}),Ue.success("E-Mail wiederhergestellt"),x(!1),o==null||o()},onError:W=>{console.error("Restore error:",W),Ue.error(W.message||"Fehler beim Wiederherstellen der E-Mail"),x(!1)}}),V=G({mutationFn:()=>Be.permanentDelete(t.id),onSuccess:()=>{T.invalidateQueries({queryKey:["emails"]}),c&&T.invalidateQueries({queryKey:["folder-counts",c]}),Ue.success("E-Mail endgültig gelöscht"),v(!1),s==null||s()},onError:W=>{console.error("Permanent delete error:",W),Ue.error(W.message||"Fehler beim endgültigen Löschen der E-Mail"),v(!1)}}),D=W=>new Date(W).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),z=W=>{try{return JSON.parse(W)}catch{return[]}},C=W=>{if(!W)return[];try{return JSON.parse(W)}catch{return[]}},_=z(t.toAddresses),K=t.ccAddresses?z(t.ccAddresses):[],B=C(t.attachmentNames);return i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"p-4 border-b border-gray-200 space-y-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:t.subject||"(Kein Betreff)"}),i.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:l?i.jsxs(i.Fragment,{children:[i.jsxs(I,{variant:"secondary",size:"sm",onClick:()=>x(!0),title:"Wiederherstellen",children:[i.jsx(AC,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),i.jsxs(I,{variant:"danger",size:"sm",onClick:()=>v(!0),title:"Endgültig löschen",children:[i.jsx(Ee,{className:"w-4 h-4 mr-1"}),"Endgültig löschen"]})]}):i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>S.mutate(),className:`p-2 rounded-lg hover:bg-gray-100 ${h?"text-yellow-500":"text-gray-400"}`,title:h?"Stern entfernen":"Als wichtig markieren",children:i.jsx(By,{className:`w-5 h-5 ${h?"fill-current":""}`})}),i.jsxs(I,{variant:"secondary",size:"sm",onClick:e,children:[i.jsx(z5,{className:"w-4 h-4 mr-1"}),"Antworten"]}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>E(!0),title:"E-Mail als PDF speichern",children:i.jsx(yC,{className:"w-4 h-4"})}),w("emails:delete")&&i.jsx(I,{variant:"danger",size:"sm",onClick:()=>p(!0),title:"E-Mail löschen",children:i.jsx(Ee,{className:"w-4 h-4"})})]})})]}),i.jsxs("div",{className:"text-sm space-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-gray-500 w-12",children:"Von:"}),i.jsxs("span",{className:"font-medium text-gray-900",children:[t.fromName&&`${t.fromName} `,i.jsxs("span",{className:"text-gray-600",children:["<",t.fromAddress,">"]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-gray-500 w-12",children:"An:"}),i.jsx("span",{className:"text-gray-700",children:_.join(", ")})]}),K.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-gray-500 w-12",children:"CC:"}),i.jsx("span",{className:"text-gray-700",children:K.join(", ")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-gray-500 w-12",children:"Am:"}),i.jsx("span",{className:"text-gray-700",children:D(t.receivedAt)})]})]}),i.jsx("div",{className:"flex items-center gap-2 pt-2",children:t.contract?i.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-green-50 border border-green-200 rounded-lg",children:[i.jsx(C1,{className:"w-4 h-4 text-green-600"}),i.jsxs("span",{className:"text-sm text-green-800",children:["Zugeordnet zu:"," ",i.jsx(Me,{to:`/contracts/${t.contract.id}`,className:"font-medium hover:underline",children:t.contract.contractNumber})]}),!t.isAutoAssigned&&i.jsx("button",{onClick:()=>M.mutate(),className:"ml-2 p-1 hover:bg-green-100 rounded",title:"Zuordnung aufheben",children:i.jsx(nn,{className:"w-4 h-4 text-green-600"})})]}):!a&&i.jsxs(I,{variant:"secondary",size:"sm",onClick:n,children:[i.jsx(C1,{className:"w-4 h-4 mr-1"}),"Vertrag zuordnen"]})}),B.length>0&&i.jsxs("div",{className:"pt-2",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(Of,{className:"w-4 h-4 text-gray-400"}),i.jsxs("span",{className:"text-sm text-gray-500",children:[B.length," Anhang",B.length>1?"e":""]})]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:B.map((W,ce)=>i.jsxs("div",{className:"inline-flex items-center gap-1 px-3 py-2 bg-gray-100 rounded-lg text-sm text-gray-700",children:[i.jsx("span",{className:"max-w-[200px] truncate mr-1",children:W}),i.jsx("a",{href:Be.getAttachmentUrl(t.id,W,!0),target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${W} öffnen`,children:i.jsx(Oy,{className:"w-4 h-4 text-gray-500"})}),i.jsx("a",{href:Be.getAttachmentUrl(t.id,W),download:W,className:"p-1 hover:bg-gray-200 rounded transition-colors",title:`${W} herunterladen`,children:i.jsx(qn,{className:"w-4 h-4 text-gray-500"})}),!l&&i.jsx("button",{onClick:()=>j(W),className:"p-1 hover:bg-blue-100 rounded transition-colors",title:`${W} speichern unter...`,children:i.jsx(zy,{className:"w-4 h-4 text-blue-500"})})]},ce))})]})]}),t.htmlBody&&t.textBody&&i.jsxs("div",{className:"px-4 py-2 border-b border-gray-200 flex items-center gap-2",children:[i.jsx("button",{onClick:()=>u(!0),className:`px-3 py-1 text-sm rounded ${d?"bg-blue-100 text-blue-700":"text-gray-600 hover:bg-gray-100"}`,children:"HTML"}),i.jsx("button",{onClick:()=>u(!1),className:`px-3 py-1 text-sm rounded ${d?"text-gray-600 hover:bg-gray-100":"bg-blue-100 text-blue-700"}`,children:"Text"})]}),i.jsx("div",{className:"flex-1 overflow-auto p-4",children:d&&t.htmlBody?i.jsx("div",{className:"prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:t.htmlBody}}):i.jsx("pre",{className:"whitespace-pre-wrap text-sm text-gray-700 font-sans",children:t.textBody||"Kein Inhalt"})}),f&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),i.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:()=>p(!1),disabled:F.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"danger",onClick:()=>F.mutate(),disabled:F.isPending,children:F.isPending?"Löschen...":"Löschen"})]})]})}),g&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail wiederherstellen?"}),i.jsxs("p",{className:"text-gray-600 mb-4",children:["Die E-Mail wird wieder in den ursprünglichen Ordner (",t.folder==="SENT"?"Gesendet":"Posteingang",") verschoben."]}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:()=>x(!1),disabled:R.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"primary",onClick:()=>R.mutate(),disabled:R.isPending,children:R.isPending?"Wird wiederhergestellt...":"Wiederherstellen"})]})]})}),y&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail endgültig löschen?"}),i.jsx("p",{className:"text-gray-600 mb-4",children:"Diese Aktion kann nicht rückgängig gemacht werden. Die E-Mail wird unwiderruflich gelöscht."}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:()=>v(!1),disabled:V.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"danger",onClick:()=>V.mutate(),disabled:V.isPending,children:V.isPending?"Wird gelöscht...":"Endgültig löschen"})]})]})}),b&&i.jsx(tR,{isOpen:!0,onClose:()=>j(null),emailId:t.id,attachmentFilename:b}),k&&i.jsx(nR,{isOpen:!0,onClose:()=>E(!1),emailId:t.id})]})}function MC({isOpen:t,onClose:e,account:n,replyTo:s,onSuccess:r,contractId:a}){const[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState(""),[p,g]=N.useState([]),[x,y]=N.useState(null),v=N.useRef(null);N.useEffect(()=>{if(t){if(s){o(s.fromAddress||"");const R=s.subject||"",V=/^(Re|Aw|Fwd|Wg):\s*/i.test(R);h(V?R:`Re: ${R}`);const D=new Date(s.receivedAt).toLocaleString("de-DE"),z=s.textBody?` + +--- Ursprüngliche Nachricht --- +Von: ${s.fromName||s.fromAddress} +Am: ${D} + +${s.textBody}`:"";f(z)}else o(""),h(""),f("");d(""),g([]),y(null)}},[t,s]);const b=10*1024*1024,j=25*1024*1024,k=R=>new Promise((V,D)=>{const z=new FileReader;z.readAsDataURL(R),z.onload=()=>{const _=z.result.split(",")[1];V(_)},z.onerror=D}),E=async R=>{const V=R.target.files;if(!V)return;const D=[];let z=p.reduce((C,_)=>C+_.content.length*.75,0);for(const C of Array.from(V)){if(C.size>b){y(`Datei "${C.name}" ist zu groß (max. 10 MB)`);continue}if(z+C.size>j){y("Maximale Gesamtgröße der Anhänge erreicht (25 MB)");break}try{const _=await k(C);D.push({filename:C.name,content:_,contentType:C.type||"application/octet-stream"}),z+=C.size}catch{y(`Fehler beim Lesen von "${C.name}"`)}}D.length>0&&g(C=>[...C,...D]),v.current&&(v.current.value="")},T=R=>{g(V=>V.filter((D,z)=>z!==R))},w=R=>{const V=R.length*.75;return V<1024?`${Math.round(V)} B`:V<1024*1024?`${(V/1024).toFixed(1)} KB`:`${(V/(1024*1024)).toFixed(1)} MB`},S=G({mutationFn:()=>ts.sendEmail(n.id,{to:l.split(",").map(R=>R.trim()).filter(Boolean),cc:c?c.split(",").map(R=>R.trim()).filter(Boolean):void 0,subject:u,text:m,inReplyTo:s==null?void 0:s.messageId,references:s!=null&&s.messageId?[s.messageId]:void 0,attachments:p.length>0?p:void 0,contractId:a}),onSuccess:()=>{r==null||r(),M()},onError:R=>{y(R instanceof Error?R.message:"Fehler beim Senden")}}),M=()=>{e()},F=()=>{if(!l.trim()){y("Bitte Empfänger angeben");return}if(!u.trim()){y("Bitte Betreff angeben");return}y(null),S.mutate()};return i.jsx(Xe,{isOpen:t,onClose:M,title:s?"Antworten":"Neue E-Mail",size:"lg",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Von"}),i.jsx("div",{className:"px-3 py-2 bg-gray-100 rounded-lg text-sm text-gray-700",children:n.email})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["An ",i.jsx("span",{className:"text-red-500",children:"*"})]}),i.jsx("input",{type:"text",value:l,onChange:R=>o(R.target.value),placeholder:"empfaenger@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"}),i.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Mehrere Empfänger mit Komma trennen"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"CC"}),i.jsx("input",{type:"text",value:c,onChange:R=>d(R.target.value),placeholder:"cc@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Betreff ",i.jsx("span",{className:"text-red-500",children:"*"})]}),i.jsx("input",{type:"text",value:u,onChange:R=>h(R.target.value),placeholder:"Betreff eingeben",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Nachricht"}),i.jsx("textarea",{value:m,onChange:R=>f(R.target.value),rows:10,placeholder:"Ihre Nachricht...",className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Anhänge"}),i.jsx("input",{type:"file",ref:v,onChange:E,multiple:!0,className:"hidden"}),i.jsxs("button",{type:"button",onClick:()=>{var R;return(R=v.current)==null?void 0:R.click()},className:"inline-flex items-center px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors",children:[i.jsx(Of,{className:"w-4 h-4 mr-2"}),"Datei anhängen"]}),p.length>0&&i.jsx("div",{className:"mt-2 space-y-2",children:p.map((R,V)=>i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 bg-gray-50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center min-w-0",children:[i.jsx(We,{className:"w-4 h-4 text-gray-500 mr-2 flex-shrink-0"}),i.jsx("span",{className:"text-sm text-gray-700 truncate",children:R.filename}),i.jsxs("span",{className:"ml-2 text-xs text-gray-500 flex-shrink-0",children:["(",w(R.content),")"]})]}),i.jsx("button",{type:"button",onClick:()=>T(V),className:"ml-2 p-1 text-gray-400 hover:text-red-500 transition-colors",title:"Anhang entfernen",children:i.jsx(nn,{className:"w-4 h-4"})})]},V))}),i.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Max. 10 MB pro Datei, 25 MB gesamt"})]}),x&&i.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:x}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:M,children:"Abbrechen"}),i.jsxs(I,{onClick:F,disabled:S.isPending,children:[i.jsx(Nd,{className:"w-4 h-4 mr-2"}),S.isPending?"Wird gesendet...":"Senden"]})]})]})})}function sR({isOpen:t,onClose:e,email:n,customerId:s,onSuccess:r}){const[a,l]=N.useState(""),[o,c]=N.useState(null),d=ye(),{data:u,isLoading:h}=fe({queryKey:["contracts","customer",s],queryFn:()=>He.getAll({customerId:s}),enabled:t}),f=((u==null?void 0:u.data)||[]).filter(v=>{var j,k,E,T;if(!a)return!0;const b=a.toLowerCase();return v.contractNumber.toLowerCase().includes(b)||((k=(j=v.contractCategory)==null?void 0:j.name)==null?void 0:k.toLowerCase().includes(b))||((T=(E=v.provider)==null?void 0:E.name)==null?void 0:T.toLowerCase().includes(b))}),p=G({mutationFn:v=>Be.assignToContract(n.id,v),onSuccess:(v,b)=>{d.invalidateQueries({queryKey:["emails"]}),d.invalidateQueries({queryKey:["email",n.id]}),d.invalidateQueries({queryKey:["contract-folder-counts",b]}),r==null||r(),g()}}),g=()=>{l(""),c(null),e()},x=()=>{o&&p.mutate(o)},y=v=>v?new Date(v).toLocaleDateString("de-DE"):"-";return i.jsx(Xe,{isOpen:t,onClose:g,title:"E-Mail Vertrag zuordnen",size:"lg",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[i.jsxs("p",{className:"text-sm text-gray-600",children:[i.jsx("span",{className:"font-medium",children:"Betreff:"})," ",n.subject||"(Kein Betreff)"]}),i.jsxs("p",{className:"text-sm text-gray-600",children:[i.jsx("span",{className:"font-medium",children:"Von:"})," ",n.fromAddress]})]}),i.jsxs("div",{className:"relative",children:[i.jsx(jd,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),i.jsx("input",{type:"text",value:a,onChange:v=>l(v.target.value),placeholder:"Vertrag suchen...",className:"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),i.jsx("div",{className:"border border-gray-200 rounded-lg max-h-80 overflow-auto",children:h?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):f.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[i.jsx(We,{className:"w-8 h-8 mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:"Keine Verträge gefunden"})]}):i.jsx("div",{className:"divide-y divide-gray-200",children:f.map(v=>{var b;return i.jsx("div",{onClick:()=>c(v.id),className:` + flex items-center gap-3 p-3 cursor-pointer transition-colors + ${o===v.id?"bg-blue-50 border-l-2 border-l-blue-500":"hover:bg-gray-50"} + `,children:i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"font-medium text-gray-900",children:v.contractNumber}),i.jsx("span",{className:` + px-2 py-0.5 text-xs rounded-full + ${v.status==="ACTIVE"?"bg-green-100 text-green-800":v.status==="PENDING"?"bg-yellow-100 text-yellow-800":v.status==="CANCELLED"?"bg-red-100 text-red-800":"bg-gray-100 text-gray-800"} + `,children:v.status})]}),i.jsxs("div",{className:"text-sm text-gray-600 truncate",children:[(b=v.contractCategory)==null?void 0:b.name,v.provider&&` - ${v.provider.name}`]}),i.jsxs("div",{className:"text-xs text-gray-500",children:["Start: ",y(v.startDate)]})]})},v.id)})})}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:g,children:"Abbrechen"}),i.jsx(I,{onClick:x,disabled:!o||p.isPending,children:p.isPending?"Wird zugeordnet...":"Zuordnen"})]})]})})}function TC({emails:t,selectedEmailId:e,onSelectEmail:n,onEmailRestored:s,onEmailDeleted:r,isLoading:a}){const[l,o]=N.useState(null),[c,d]=N.useState(null),u=ye(),h=E=>{if(E.folder==="SENT")try{const T=JSON.parse(E.toAddresses);if(T.length>0)return`An: ${T[0]}${T.length>1?` (+${T.length-1})`:""}`}catch{return"An: (Unbekannt)"}return E.fromName||E.fromAddress},m=G({mutationFn:E=>Be.restore(E),onSuccess:(E,T)=>{u.invalidateQueries({queryKey:["emails"]}),Ue.success("E-Mail wiederhergestellt"),o(null),d(null),s==null||s(T)},onError:E=>{console.error("Restore error:",E),Ue.error(E.message||"Fehler beim Wiederherstellen"),o(null),d(null)}}),f=G({mutationFn:E=>Be.permanentDelete(E),onSuccess:(E,T)=>{u.invalidateQueries({queryKey:["emails"]}),Ue.success("E-Mail endgültig gelöscht"),o(null),d(null),r==null||r(T)},onError:E=>{console.error("Permanent delete error:",E),Ue.error(E.message||"Fehler beim endgültigen Löschen"),o(null),d(null)}}),p=G({mutationFn:E=>Be.unassignFromContract(E),onSuccess:()=>{u.invalidateQueries({queryKey:["emails"]}),Ue.success("Vertragszuordnung aufgehoben")},onError:E=>{console.error("Unassign error:",E),Ue.error(E.message||"Fehler beim Aufheben der Zuordnung")}}),g=(E,T)=>{E.stopPropagation(),p.mutate(T)},x=(E,T)=>{E.stopPropagation(),o(T),d("restore")},y=(E,T)=>{E.stopPropagation(),o(T),d("delete")},v=E=>{E.stopPropagation(),l&&c&&(c==="restore"?m.mutate(l):f.mutate(l))},b=E=>{E.stopPropagation(),o(null),d(null)},j=E=>new Date(E).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"}),k=E=>{if(!E)return"";const T=new Date(E),w=new Date;return T.toDateString()===w.toDateString()?`Gelöscht um ${T.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"})}`:`Gelöscht am ${T.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})}`};return a?i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"})}):t.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[i.jsx(Ee,{className:"w-12 h-12 mb-2 opacity-50"}),i.jsx("p",{children:"Papierkorb ist leer"})]}):i.jsxs("div",{className:"divide-y divide-gray-200",children:[t.map(E=>i.jsxs("div",{onClick:()=>n(E),className:["flex items-start gap-3 p-3 cursor-pointer transition-colors",e===E.id?"bg-red-100":"hover:bg-gray-100 bg-gray-50/50"].join(" "),style:{borderLeft:e===E.id?"4px solid #dc2626":"4px solid transparent"},children:[i.jsx("div",{className:"flex-shrink-0 mt-1 p-1 -ml-1 text-gray-400",title:E.folder==="SENT"?"Aus Gesendet":"Aus Posteingang",children:E.folder==="SENT"?i.jsx(Nd,{className:"w-4 h-4"}):i.jsx(Sa,{className:"w-4 h-4"})}),i.jsx("button",{onClick:T=>x(T,E.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-green-100 text-gray-400 hover:text-green-600",title:"Wiederherstellen",children:i.jsx(AC,{className:"w-4 h-4"})}),i.jsx("button",{onClick:T=>y(T,E.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"Endgültig löschen",children:i.jsx(Ee,{className:"w-4 h-4"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[i.jsx("span",{className:"text-sm truncate text-gray-700",children:h(E)}),i.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:j(E.receivedAt)})]}),i.jsx("div",{className:"text-sm truncate text-gray-600",children:E.subject||"(Kein Betreff)"}),i.jsx("div",{className:"text-xs text-red-500 mt-1",children:k(E.deletedAt)}),E.contract&&i.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[i.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:E.contract.contractNumber}),(E.folder==="INBOX"||E.folder==="SENT"&&!E.isAutoAssigned)&&i.jsx("button",{onClick:T=>g(T,E.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:p.isPending,children:i.jsx(nn,{className:"w-3.5 h-3.5"})})]})]}),i.jsx(At,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},E.id)),l&&c&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:c==="restore"?"E-Mail wiederherstellen?":"E-Mail endgültig löschen?"}),i.jsx("p",{className:"text-gray-600 mb-4",children:c==="restore"?"Die E-Mail wird wieder in den ursprünglichen Ordner verschoben.":"Die E-Mail wird unwiderruflich gelöscht. Diese Aktion kann nicht rückgängig gemacht werden."}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:b,disabled:m.isPending||f.isPending,children:"Abbrechen"}),i.jsx(I,{variant:c==="restore"?"primary":"danger",onClick:v,disabled:m.isPending||f.isPending,children:m.isPending||f.isPending?"Wird ausgeführt...":c==="restore"?"Wiederherstellen":"Endgültig löschen"})]})]})})]})}function rR({customerId:t}){const[e,n]=N.useState(null),[s,r]=N.useState("INBOX"),[a,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState(null),f=ye(),{hasPermission:p}=nt(),g=p("emails:delete"),{data:x,isLoading:y}=fe({queryKey:["mailbox-accounts",t],queryFn:()=>Be.getMailboxAccounts(t)}),v=(x==null?void 0:x.data)||[];N.useEffect(()=>{v.length>0&&!e&&n(v[0].id)},[v,e]);const b=v.find(he=>he.id===e),{data:j,isLoading:k,refetch:E}=fe({queryKey:["emails","customer",t,e,s],queryFn:()=>Be.getForCustomer(t,{accountId:e||void 0,folder:s}),enabled:!!e&&s!=="TRASH"}),T=(j==null?void 0:j.data)||[],{data:w,isLoading:S}=fe({queryKey:["emails","trash",t],queryFn:()=>Be.getTrash(t),enabled:s==="TRASH"&&g}),M=(w==null?void 0:w.data)||[],{data:F}=fe({queryKey:["folder-counts",e],queryFn:()=>ts.getFolderCounts(e),enabled:!!e}),R=(F==null?void 0:F.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0,trash:0,trashUnread:0},{data:V}=fe({queryKey:["email",a==null?void 0:a.id],queryFn:()=>Be.getById(a.id),enabled:!!(a!=null&&a.id)}),D=(V==null?void 0:V.data)||a,z=G({mutationFn:he=>ts.syncEmails(he),onSuccess:()=>{f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["folder-counts",e]}),f.invalidateQueries({queryKey:["mailbox-accounts",t]})}}),C=()=>{e&&z.mutate(e)},_=he=>{l(he)},K=()=>{m(D||null),c(!0)},B=()=>{m(null),c(!0)},W=()=>{u(!0)};if(!y&&v.length===0)return i.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[i.jsx(Fs,{className:"w-16 h-16 mb-4 opacity-30"}),i.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"Keine E-Mail-Konten vorhanden"}),i.jsx("p",{className:"text-sm text-center max-w-md",children:"Erstellen Sie eine Stressfrei-Wechseln E-Mail-Adresse mit aktivierter Mailbox, um E-Mails hier empfangen und versenden zu können."})]});const ce=he=>{r(he),l(null)};return i.jsxs("div",{className:"flex flex-col h-full",style:{minHeight:"600px"},children:[i.jsxs("div",{className:"flex items-center justify-between gap-4 p-4 border-b border-gray-200 bg-gray-50",children:[v.length>1?i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Sa,{className:"w-5 h-5 text-gray-500"}),i.jsx("select",{value:e||"",onChange:he=>{n(Number(he.target.value)),l(null)},className:"px-3 py-2 border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",children:v.map(he=>i.jsx("option",{value:he.id,children:he.email},he.id))})]}):i.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-600",children:[i.jsx(Sa,{className:"w-5 h-5 text-gray-500"}),i.jsx("span",{children:b==null?void 0:b.email})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-gray-200 rounded-lg p-1",children:[i.jsxs("button",{onClick:()=>ce("INBOX"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${s==="INBOX"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Sa,{className:"w-4 h-4"}),"Posteingang",R.inbox>0&&i.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${R.inboxUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${R.inboxUnread} ungelesen / ${R.inbox} gesamt`,children:R.inboxUnread>0?`${R.inboxUnread}/${R.inbox}`:R.inbox})]}),i.jsxs("button",{onClick:()=>ce("SENT"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${s==="SENT"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Nd,{className:"w-4 h-4"}),"Gesendet",R.sent>0&&i.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${R.sentUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${R.sentUnread} ungelesen / ${R.sent} gesamt`,children:R.sentUnread>0?`${R.sentUnread}/${R.sent}`:R.sent})]}),g&&i.jsxs("button",{onClick:()=>ce("TRASH"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${s==="TRASH"?"bg-white text-red-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Ee,{className:"w-4 h-4"}),"Papierkorb",R.trash>0&&i.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${R.trashUnread>0?"bg-red-100 text-red-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${R.trashUnread} ungelesen / ${R.trash} gesamt`,children:R.trashUnread>0?`${R.trashUnread}/${R.trash}`:R.trash})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[s!=="TRASH"&&i.jsxs(I,{variant:"secondary",size:"sm",onClick:C,disabled:z.isPending||!e,children:[i.jsx(ai,{className:`w-4 h-4 mr-1 ${z.isPending?"animate-spin":""}`}),z.isPending?"Sync...":"Synchronisieren"]}),i.jsxs(I,{size:"sm",onClick:B,disabled:!b,children:[i.jsx(Ge,{className:"w-4 h-4 mr-1"}),"Neue E-Mail"]})]})]}),i.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[i.jsx("div",{className:"w-1/3 border-r border-gray-200 overflow-auto",children:s==="TRASH"?i.jsx(TC,{emails:M,selectedEmailId:a==null?void 0:a.id,onSelectEmail:_,onEmailRestored:he=>{(a==null?void 0:a.id)===he&&l(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["folder-counts",e]})},onEmailDeleted:he=>{(a==null?void 0:a.id)===he&&l(null),f.invalidateQueries({queryKey:["emails","trash"]}),f.invalidateQueries({queryKey:["folder-counts",e]})},isLoading:S}):i.jsx(eR,{emails:T,selectedEmailId:a==null?void 0:a.id,onSelectEmail:_,onEmailDeleted:he=>{(a==null?void 0:a.id)===he&&l(null),f.invalidateQueries({queryKey:["folder-counts",e]})},isLoading:k,folder:s,accountId:e})}),i.jsx("div",{className:"flex-1 overflow-auto",children:D?i.jsx(DC,{email:D,onReply:K,onAssignContract:W,onDeleted:()=>{l(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["folder-counts",e]})},isSentFolder:s==="SENT",isTrashView:s==="TRASH",onRestored:()=>{l(null),f.invalidateQueries({queryKey:["emails"]}),f.invalidateQueries({queryKey:["folder-counts",e]})},accountId:e||void 0}):i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500",children:[i.jsx(Fs,{className:"w-12 h-12 mb-2 opacity-30"}),i.jsx("p",{children:"Wählen Sie eine E-Mail aus"})]})})]}),b&&i.jsx(MC,{isOpen:o,onClose:()=>{c(!1),m(null)},account:b,replyTo:h||void 0,onSuccess:()=>{f.invalidateQueries({queryKey:["emails","customer",t,e,"SENT"]}),f.invalidateQueries({queryKey:["folder-counts",e]}),s==="SENT"&&E()}}),D&&i.jsx(sR,{isOpen:d,onClose:()=>u(!1),email:D,customerId:t,onSuccess:()=>{E()}})]})}function iR({contractId:t,customerId:e}){const[n,s]=N.useState(null),[r,a]=N.useState("INBOX"),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[m,f]=N.useState(null),p=ye(),{hasPermission:g}=nt(),x=g("emails:delete"),{data:y,isLoading:v}=fe({queryKey:["mailbox-accounts",e],queryFn:()=>Be.getMailboxAccounts(e)}),b=(y==null?void 0:y.data)||[];N.useEffect(()=>{b.length>0&&!n&&s(b[0].id)},[b,n]);const j=b.find(ee=>ee.id===n),{data:k,isLoading:E,refetch:T}=fe({queryKey:["emails","contract",t,r],queryFn:()=>Be.getForContract(t,{folder:r}),enabled:r!=="TRASH"}),w=(k==null?void 0:k.data)||[],{data:S,isLoading:M}=fe({queryKey:["emails","trash",e],queryFn:()=>Be.getTrash(e),enabled:r==="TRASH"&&x}),F=(S==null?void 0:S.data)||[],{data:R}=fe({queryKey:["contract-folder-counts",t],queryFn:()=>Be.getContractFolderCounts(t)}),V=(R==null?void 0:R.data)||{inbox:0,inboxUnread:0,sent:0,sentUnread:0},{data:D}=fe({queryKey:["folder-counts",n],queryFn:()=>ts.getFolderCounts(n),enabled:!!n&&x}),z=(D==null?void 0:D.data)||{trash:0,trashUnread:0},{data:C}=fe({queryKey:["email",l==null?void 0:l.id],queryFn:()=>Be.getById(l.id),enabled:!!(l!=null&&l.id)}),_=(C==null?void 0:C.data)||l,K=G({mutationFn:ee=>ts.syncEmails(ee),onSuccess:()=>{p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]}),n&&p.invalidateQueries({queryKey:["folder-counts",n]}),Ue.success("Synchronisation abgeschlossen")},onError:ee=>{Ue.error(ee.message||"Synchronisation fehlgeschlagen")}}),B=G({mutationFn:ee=>Be.toggleStar(ee),onSuccess:(ee,pe)=>{p.invalidateQueries({queryKey:["emails","contract",t]}),p.invalidateQueries({queryKey:["email",pe]})}}),W=G({mutationFn:({emailId:ee,isRead:pe})=>Be.markAsRead(ee,pe),onSuccess:(ee,pe)=>{p.invalidateQueries({queryKey:["emails","contract",t]}),p.invalidateQueries({queryKey:["email",pe.emailId]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]}),n&&p.invalidateQueries({queryKey:["folder-counts",n]})}}),ce=G({mutationFn:ee=>Be.unassignFromContract(ee),onSuccess:()=>{p.invalidateQueries({queryKey:["emails","contract",t]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]}),o(null),Ue.success("Zuordnung aufgehoben")},onError:ee=>{Ue.error(ee.message||"Fehler beim Aufheben der Zuordnung")}}),he=G({mutationFn:ee=>Be.delete(ee),onSuccess:(ee,pe)=>{p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]}),n&&p.invalidateQueries({queryKey:["folder-counts",n]}),Ue.success("E-Mail in Papierkorb verschoben"),f(null),(l==null?void 0:l.id)===pe&&o(null)},onError:ee=>{Ue.error(ee.message||"Fehler beim Löschen der E-Mail"),f(null)}}),Je=()=>{n&&K.mutate(n)},et=ee=>{const pe=new Date(ee),Ln=new Date;return pe.toDateString()===Ln.toDateString()?pe.toLocaleTimeString("de-DE",{hour:"2-digit",minute:"2-digit"}):pe.toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit"})},mt=(ee,pe)=>{ee.stopPropagation(),B.mutate(pe)},A=(ee,pe)=>{ee.stopPropagation(),W.mutate({emailId:pe.id,isRead:!pe.isRead})},pt=ee=>{ee.isRead||W.mutate({emailId:ee.id,isRead:!0}),o(ee)},On=()=>{h(_||null),d(!0)},wn=()=>{h(null),d(!0)},le=(ee,pe)=>{ee.stopPropagation(),(l==null?void 0:l.id)===pe&&o(null),ce.mutate(pe)},it=(ee,pe)=>{ee.stopPropagation(),f(pe)},Rt=ee=>{ee.stopPropagation(),m&&he.mutate(m)},J=ee=>{ee.stopPropagation(),f(null)},Ke=ee=>{a(ee),o(null)},ct=ee=>{if(r==="SENT")try{const pe=JSON.parse(ee.toAddresses);if(pe.length>0)return`An: ${pe[0]}${pe.length>1?` (+${pe.length-1})`:""}`}catch{return"An: (Unbekannt)"}return ee.fromName||ee.fromAddress};return!v&&b.length===0?i.jsx(Z,{title:"E-Mails",children:i.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[i.jsx(Fs,{className:"w-10 h-10 mb-2 opacity-30"}),i.jsx("p",{className:"text-sm",children:"Keine E-Mail-Konten vorhanden"}),i.jsx("p",{className:"text-xs mt-1",children:"Erstellen Sie eine E-Mail-Adresse beim Kunden mit aktivierter Mailbox"})]})}):i.jsxs(Z,{title:i.jsx("div",{className:"flex items-center gap-4",children:i.jsx("span",{children:"E-Mails"})}),actions:i.jsxs("div",{className:"flex items-center gap-2",children:[r!=="TRASH"&&i.jsxs(I,{variant:"secondary",size:"sm",onClick:Je,disabled:K.isPending||!n,children:[i.jsx(ai,{className:`w-4 h-4 mr-1 ${K.isPending?"animate-spin":""}`}),K.isPending?"Sync...":"Sync"]}),j&&i.jsxs(I,{size:"sm",onClick:wn,children:[i.jsx(Ge,{className:"w-4 h-4 mr-1"}),"Neue E-Mail"]})]}),children:[i.jsxs("div",{className:"flex items-center justify-between gap-4 pb-4 border-b border-gray-200 -mt-2",children:[b.length>1?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Sa,{className:"w-4 h-4 text-gray-500"}),i.jsx("select",{value:n||"",onChange:ee=>{s(Number(ee.target.value)),o(null)},className:"px-2 py-1.5 border border-gray-300 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm",children:b.map(ee=>i.jsx("option",{value:ee.id,children:ee.email},ee.id))})]}):i.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[i.jsx(Sa,{className:"w-4 h-4 text-gray-500"}),i.jsx("span",{children:j==null?void 0:j.email})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-gray-200 rounded-lg p-1",children:[i.jsxs("button",{onClick:()=>Ke("INBOX"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="INBOX"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Sa,{className:"w-4 h-4"}),"Posteingang",V.inbox>0&&i.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${V.inboxUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${V.inboxUnread} ungelesen / ${V.inbox} gesamt`,children:V.inboxUnread>0?`${V.inboxUnread}/${V.inbox}`:V.inbox})]}),i.jsxs("button",{onClick:()=>Ke("SENT"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="SENT"?"bg-white text-blue-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Nd,{className:"w-4 h-4"}),"Gesendet",V.sent>0&&i.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${V.sentUnread>0?"bg-blue-100 text-blue-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${V.sentUnread} ungelesen / ${V.sent} gesamt`,children:V.sentUnread>0?`${V.sentUnread}/${V.sent}`:V.sent})]}),x&&i.jsxs("button",{onClick:()=>Ke("TRASH"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${r==="TRASH"?"bg-white text-red-600 shadow-sm font-medium":"text-gray-600 hover:text-gray-900"}`,children:[i.jsx(Ee,{className:"w-4 h-4"}),"Papierkorb",z.trash>0&&i.jsx("span",{className:`ml-1 px-1.5 py-0.5 text-xs rounded-full cursor-help ${z.trashUnread>0?"bg-red-100 text-red-600 font-medium":"bg-gray-100 text-gray-500"}`,title:`${z.trashUnread} ungelesen / ${z.trash} gesamt`,children:z.trashUnread>0?`${z.trashUnread}/${z.trash}`:z.trash})]})]})]}),(r==="TRASH"?M:E)?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):(r==="TRASH"?F.length===0:w.length===0)?i.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-gray-500",children:[i.jsx(Fs,{className:"w-10 h-10 mb-2 opacity-30"}),i.jsx("p",{className:"text-sm",children:r==="INBOX"?"Keine E-Mails zugeordnet":r==="SENT"?"Keine E-Mails über diesen Vertrag gesendet":"Papierkorb ist leer"}),r==="INBOX"&&i.jsx("p",{className:"text-xs mt-1",children:"E-Mails können im E-Mail-Tab des Kunden zugeordnet werden"})]}):i.jsxs("div",{className:"flex -mx-6 -mb-6",style:{minHeight:"400px"},children:[i.jsx("div",{className:"w-1/3 border-r border-gray-200 overflow-auto",children:r==="TRASH"?i.jsx(TC,{emails:F,selectedEmailId:l==null?void 0:l.id,onSelectEmail:pt,onEmailRestored:ee=>{(l==null?void 0:l.id)===ee&&o(null),p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["folder-counts",n]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]})},onEmailDeleted:ee=>{(l==null?void 0:l.id)===ee&&o(null),p.invalidateQueries({queryKey:["emails","trash"]}),p.invalidateQueries({queryKey:["folder-counts",n]})},isLoading:M}):i.jsx("div",{className:"divide-y divide-gray-200",children:w.map(ee=>i.jsxs("div",{onClick:()=>pt(ee),className:["flex items-start gap-2 p-3 cursor-pointer transition-colors",(l==null?void 0:l.id)===ee.id?"bg-blue-100":["hover:bg-gray-100",ee.isRead?"bg-gray-50/50":"bg-white"].join(" ")].join(" "),style:{borderLeft:(l==null?void 0:l.id)===ee.id?"4px solid #2563eb":"4px solid transparent"},children:[i.jsx("button",{onClick:pe=>A(pe,ee),className:` + flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 + ${ee.isRead?"text-gray-400":"text-blue-600"} + `,title:ee.isRead?"Als ungelesen markieren":"Als gelesen markieren",children:ee.isRead?i.jsx(NC,{className:"w-4 h-4"}):i.jsx(Fs,{className:"w-4 h-4"})}),i.jsx("button",{onClick:pe=>mt(pe,ee.id),className:` + flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-gray-200 + ${ee.isStarred?"text-yellow-500":"text-gray-400"} + `,title:ee.isStarred?"Stern entfernen":"Als wichtig markieren",children:i.jsx(By,{className:`w-4 h-4 ${ee.isStarred?"fill-current":""}`})}),g("emails:delete")&&i.jsx("button",{onClick:pe=>it(pe,ee.id),className:"flex-shrink-0 mt-1 p-1 -ml-1 rounded hover:bg-red-100 text-gray-400 hover:text-red-600",title:"E-Mail löschen",children:i.jsx(Ee,{className:"w-4 h-4"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[i.jsx("span",{className:`text-sm truncate ${ee.isRead?"text-gray-700":"font-semibold text-gray-900"}`,children:ct(ee)}),i.jsx("span",{className:"text-xs text-gray-500 flex-shrink-0",children:et(ee.receivedAt)})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`text-sm truncate ${ee.isRead?"text-gray-600":"font-medium text-gray-900"}`,children:ee.subject||"(Kein Betreff)"}),ee.hasAttachments&&i.jsx(Of,{className:"w-3 h-3 text-gray-400 flex-shrink-0"})]}),ee.contract&&i.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[i.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800",children:ee.contract.contractNumber}),(r==="INBOX"||r==="SENT"&&!ee.isAutoAssigned)&&i.jsx("button",{onClick:pe=>le(pe,ee.id),className:"p-0.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded",title:"Zuordnung aufheben",disabled:ce.isPending,children:i.jsx(nn,{className:"w-3.5 h-3.5"})})]})]}),i.jsx(At,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-2"})]},ee.id))})}),i.jsx("div",{className:"flex-1 overflow-auto",children:_&&l?i.jsx(DC,{email:_,onReply:On,onAssignContract:()=>{},onDeleted:()=>{o(null),p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]}),n&&p.invalidateQueries({queryKey:["folder-counts",n]})},isSentFolder:r==="SENT",isContractView:r!=="TRASH",isTrashView:r==="TRASH",onRestored:()=>{o(null),p.invalidateQueries({queryKey:["emails"]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]}),n&&p.invalidateQueries({queryKey:["folder-counts",n]})},accountId:_==null?void 0:_.stressfreiEmailId}):i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500",children:[i.jsx(Fs,{className:"w-12 h-12 mb-2 opacity-30"}),i.jsx("p",{children:"Wählen Sie eine E-Mail aus"})]})})]}),m&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"E-Mail löschen?"}),i.jsx("p",{className:"text-gray-600 mb-4",children:"Die E-Mail wird in den Papierkorb verschoben."}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:J,disabled:he.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"danger",onClick:Rt,disabled:he.isPending,children:he.isPending?"Löschen...":"Löschen"})]})]})}),j&&i.jsx(MC,{isOpen:c,onClose:()=>{d(!1),h(null)},account:j,replyTo:u||void 0,contractId:t,onSuccess:()=>{p.invalidateQueries({queryKey:["emails","contract",t,"SENT"]}),p.invalidateQueries({queryKey:["contract-folder-counts",t]}),r==="SENT"&&T()}})]})}function aR({tabs:t,defaultTab:e}){var r,a;const[n,s]=N.useState(e||((r=t[0])==null?void 0:r.id));return i.jsxs("div",{children:[i.jsx("div",{className:"border-b border-gray-200",children:i.jsx("nav",{className:"flex -mb-px space-x-8",children:t.map(l=>i.jsx("button",{onClick:()=>s(l.id),className:`py-4 px-1 border-b-2 font-medium text-sm whitespace-nowrap ${n===l.id?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:l.label},l.id))})}),i.jsx("div",{className:"mt-4",children:(a=t.find(l=>l.id===n))==null?void 0:a.content})]})}function Jt({onUpload:t,existingFile:e,accept:n=".pdf,.jpg,.jpeg,.png",label:s="Dokument hochladen",disabled:r=!1}){const a=N.useRef(null),[l,o]=N.useState(!1),[c,d]=N.useState(!1),u=async g=>{if(g){o(!0);try{await t(g)}catch(x){console.error("Upload failed:",x),alert("Upload fehlgeschlagen")}finally{o(!1)}}},h=g=>{var y;const x=(y=g.target.files)==null?void 0:y[0];x&&u(x)},m=g=>{var y;g.preventDefault(),d(!1);const x=(y=g.dataTransfer.files)==null?void 0:y[0];x&&u(x)},f=g=>{g.preventDefault(),d(!0)},p=()=>{d(!1)};return i.jsxs("div",{className:"space-y-2",children:[e?!r&&i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>{var g;return(g=a.current)==null?void 0:g.click()},disabled:l,children:l?"Wird hochgeladen...":"Ersetzen"}):i.jsx("div",{className:`border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${c?"border-blue-500 bg-blue-50":"border-gray-300 hover:border-gray-400"} ${r?"opacity-50 cursor-not-allowed":""}`,onClick:()=>{var g;return!r&&((g=a.current)==null?void 0:g.click())},onDrop:r?void 0:m,onDragOver:r?void 0:f,onDragLeave:r?void 0:p,children:l?i.jsxs("div",{className:"text-gray-500",children:[i.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"}),"Wird hochgeladen..."]}):i.jsxs(i.Fragment,{children:[i.jsx(_g,{className:"w-6 h-6 text-gray-400 mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-gray-600",children:s}),i.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"PDF, JPG oder PNG (max. 10MB)"})]})}),i.jsx("input",{ref:a,type:"file",accept:n,onChange:h,className:"hidden",disabled:r||l})]})}function de({value:t,className:e="",size:n="sm",title:s="In Zwischenablage kopieren"}){const[r,a]=N.useState(!1),l=async c=>{c.preventDefault(),c.stopPropagation();try{await navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),1500)}catch(d){console.error("Failed to copy:",d)}},o=n==="sm"?"w-3.5 h-3.5":"w-4 h-4";return i.jsx("button",{type:"button",onClick:l,className:`inline-flex items-center justify-center p-1 rounded transition-colors ${r?"text-green-600 bg-green-50":"text-gray-400 hover:text-blue-600 hover:bg-blue-50"} ${e}`,title:r?"Kopiert!":s,children:r?i.jsx(Vr,{className:o}):i.jsx(Iy,{className:o})})}function Vg({values:t,separator:e=` +`,children:n,className:s=""}){const r=t.filter(a=>a!=null&&a!=="").map(String).join(e);return r?i.jsxs("div",{className:`relative group ${s}`,children:[n,i.jsx(de,{value:r,className:"absolute top-0 right-0 opacity-60 group-hover:opacity-100",title:"Alles kopieren"})]}):i.jsx(i.Fragment,{children:n})}function lR(){var K,B;const{id:t}=md(),e=fn(),n=ye(),{hasPermission:s}=nt(),[r]=Sf(),a=parseInt(t),l=r.get("tab")||"addresses",[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,m]=N.useState(!1),[f,p]=N.useState(!1),[g,x]=N.useState(!1),[y,v]=N.useState(!1),[b,j]=N.useState(null),[k,E]=N.useState(null),[T,w]=N.useState(null),[S,M]=N.useState(null),[F,R]=N.useState(null),{data:V,isLoading:D}=fe({queryKey:["customer",t],queryFn:()=>Zt.getById(a)}),z=G({mutationFn:()=>Zt.delete(a),onSuccess:()=>{e("/customers")}});if(D)return i.jsx("div",{className:"text-center py-8",children:"Laden..."});if(!(V!=null&&V.data))return i.jsx("div",{className:"text-center py-8 text-red-600",children:"Kunde nicht gefunden"});const C=V.data,_=[{id:"addresses",label:"Adressen",content:i.jsx(dR,{customerId:a,addresses:C.addresses||[],canEdit:s("customers:update"),onAdd:()=>c(!0),onEdit:W=>w(W)})},{id:"bankcards",label:"Bankkarten",content:i.jsx(uR,{customerId:a,bankCards:C.bankCards||[],canEdit:s("customers:update"),showInactive:y,onToggleInactive:()=>v(!y),onAdd:()=>u(!0),onEdit:W=>j(W)})},{id:"documents",label:"Ausweise",content:i.jsx(hR,{customerId:a,documents:C.identityDocuments||[],canEdit:s("customers:update"),showInactive:y,onToggleInactive:()=>v(!y),onAdd:()=>m(!0),onEdit:W=>E(W)})},{id:"meters",label:"Zähler",content:i.jsx(fR,{customerId:a,meters:C.meters||[],canEdit:s("customers:update"),showInactive:y,onToggleInactive:()=>v(!y),onAdd:()=>p(!0),onEdit:W=>M(W)})},{id:"stressfrei",label:"Stressfrei-Wechseln",content:i.jsx(xR,{customerId:a,emails:C.stressfreiEmails||[],canEdit:s("customers:update"),showInactive:y,onToggleInactive:()=>v(!y),onAdd:()=>x(!0),onEdit:W=>R(W)})},{id:"emails",label:"E-Mail-Postfach",content:i.jsx(rR,{customerId:a})},{id:"contracts",label:"Verträge",content:i.jsx(mR,{customerId:a})},...s("customers:update")?[{id:"portal",label:"Portal",content:i.jsx(gR,{customerId:a,canEdit:s("customers:update")})}]:[],...s("customers:read")?[{id:"consents",label:"Einwilligungen",content:i.jsx(bR,{customerId:a,canEdit:!1,customerEmail:C.email||void 0})}]:[]];return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold",children:C.type==="BUSINESS"&&C.companyName?C.companyName:`${C.firstName} ${C.lastName}`}),i.jsxs("p",{className:"text-gray-500 font-mono flex items-center gap-1",children:[C.customerNumber,i.jsx(de,{value:C.customerNumber})]})]}),i.jsxs("div",{className:"flex gap-2",children:[s("customers:update")&&i.jsx(Me,{to:`/customers/${t}/edit`,children:i.jsxs(I,{variant:"secondary",children:[i.jsx(rt,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),s("customers:delete")&&i.jsxs(I,{variant:"danger",onClick:()=>{confirm("Kunde wirklich löschen?")&&z.mutate()},children:[i.jsx(Ee,{className:"w-4 h-4 mr-2"}),"Löschen"]})]})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6",children:[i.jsx(Z,{title:"Stammdaten",className:"lg:col-span-2",children:i.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Typ"}),i.jsx("dd",{children:i.jsx(je,{variant:C.type==="BUSINESS"?"info":"default",children:C.type==="BUSINESS"?"Geschäftskunde":"Privatkunde"})})]}),C.salutation&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Anrede"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[C.salutation,i.jsx(de,{value:C.salutation})]})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vorname"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[C.firstName,i.jsx(de,{value:C.firstName})]})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Nachname"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[C.lastName,i.jsx(de,{value:C.lastName})]})]}),C.companyName&&i.jsxs("div",{className:"col-span-2",children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Firma"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[C.companyName,i.jsx(de,{value:C.companyName})]})]}),C.foundingDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Gründungsdatum"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[new Date(C.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),i.jsx(de,{value:new Date(C.foundingDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),C.birthDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Geburtsdatum"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[new Date(C.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"}),i.jsx(de,{value:new Date(C.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]})]}),C.birthPlace&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Geburtsort"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[C.birthPlace,i.jsx(de,{value:C.birthPlace})]})]})]})}),i.jsx(Z,{title:"Kontakt",children:i.jsxs("dl",{className:"space-y-3",children:[C.email&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"E-Mail"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[i.jsx("a",{href:`mailto:${C.email}`,className:"text-blue-600 hover:underline",children:C.email}),i.jsx(de,{value:C.email})]})]}),C.phone&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Telefon"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[i.jsx("a",{href:`tel:${C.phone}`,className:"text-blue-600 hover:underline",children:C.phone}),i.jsx(de,{value:C.phone})]})]}),C.mobile&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Mobil"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[i.jsx("a",{href:`tel:${C.mobile}`,className:"text-blue-600 hover:underline",children:C.mobile}),i.jsx(de,{value:C.mobile})]})]})]})})]}),C.type==="BUSINESS"&&i.jsx(oR,{customer:C,canEdit:s("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",t]})}),i.jsx(cR,{customer:C,canEdit:s("customers:update"),onUpdate:()=>n.invalidateQueries({queryKey:["customer",t]})}),C.notes&&i.jsx(Z,{title:"Notizen",className:"mb-6",children:i.jsx("p",{className:"whitespace-pre-wrap",children:C.notes})}),i.jsx(Z,{children:i.jsx(aR,{tabs:_,defaultTab:l})}),i.jsx(D1,{isOpen:o,onClose:()=>c(!1),customerId:a}),i.jsx(D1,{isOpen:!!T,onClose:()=>w(null),customerId:a,address:T}),i.jsx(M1,{isOpen:d,onClose:()=>u(!1),customerId:a}),i.jsx(M1,{isOpen:!!b,onClose:()=>j(null),customerId:a,bankCard:b}),i.jsx(T1,{isOpen:h,onClose:()=>m(!1),customerId:a}),i.jsx(T1,{isOpen:!!k,onClose:()=>E(null),customerId:a,document:k}),i.jsx(P1,{isOpen:f,onClose:()=>p(!1),customerId:a}),i.jsx(P1,{isOpen:!!S,onClose:()=>M(null),customerId:a,meter:S}),i.jsx(R1,{isOpen:g,onClose:()=>x(!1),customerId:a,customerEmail:(K=V==null?void 0:V.data)==null?void 0:K.email}),i.jsx(R1,{isOpen:!!F,onClose:()=>R(null),customerId:a,email:F,customerEmail:(B=V==null?void 0:V.data)==null?void 0:B.email})]})}function oR({customer:t,canEdit:e,onUpdate:n}){const s=async c=>{try{await Ct.uploadBusinessRegistration(t.id,c),n()}catch(d){console.error("Upload fehlgeschlagen:",d),alert("Upload fehlgeschlagen")}},r=async()=>{if(confirm("Gewerbeanmeldung wirklich löschen?"))try{await Ct.deleteBusinessRegistration(t.id),n()}catch(c){console.error("Löschen fehlgeschlagen:",c),alert("Löschen fehlgeschlagen")}},a=async c=>{try{await Ct.uploadCommercialRegister(t.id,c),n()}catch(d){console.error("Upload fehlgeschlagen:",d),alert("Upload fehlgeschlagen")}},l=async()=>{if(confirm("Handelsregisterauszug wirklich löschen?"))try{await Ct.deleteCommercialRegister(t.id),n()}catch(c){console.error("Löschen fehlgeschlagen:",c),alert("Löschen fehlgeschlagen")}};return!(t.taxNumber||t.commercialRegisterNumber||t.businessRegistrationPath||t.commercialRegisterPath)&&!e?null:i.jsxs(Z,{title:"Geschäftsdaten",className:"mb-6",children:[i.jsxs("dl",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t.taxNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Steuernummer"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[t.taxNumber,i.jsx(de,{value:t.taxNumber})]})]}),t.commercialRegisterNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Handelsregisternummer"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[t.commercialRegisterNumber,i.jsx(de,{value:t.commercialRegisterNumber})]})]})]}),i.jsxs("div",{className:"mt-4 pt-4 border-t grid grid-cols-1 md:grid-cols-2 gap-6",children:[i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Gewerbeanmeldung"}),t.businessRegistrationPath?i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("a",{href:`/api${t.businessRegistrationPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${t.businessRegistrationPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),e&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{onUpload:s,existingFile:t.businessRegistrationPath,accept:".pdf",label:"Ersetzen"}),i.jsxs("button",{onClick:r,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]})]}):e?i.jsx(Jt,{onUpload:s,accept:".pdf",label:"PDF hochladen"}):i.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]}),i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Handelsregisterauszug"}),t.commercialRegisterPath?i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("a",{href:`/api${t.commercialRegisterPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${t.commercialRegisterPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),e&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{onUpload:a,existingFile:t.commercialRegisterPath,accept:".pdf",label:"Ersetzen"}),i.jsxs("button",{onClick:l,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]})]}):e?i.jsx(Jt,{onUpload:a,accept:".pdf",label:"PDF hochladen"}):i.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})]})]})}function cR({customer:t,canEdit:e,onUpdate:n}){const s=async a=>{try{await Ct.uploadPrivacyPolicy(t.id,a),n()}catch(l){console.error("Upload fehlgeschlagen:",l),alert("Upload fehlgeschlagen")}},r=async()=>{if(confirm("Datenschutzerklärung wirklich löschen?"))try{await Ct.deletePrivacyPolicy(t.id),n()}catch(a){console.error("Löschen fehlgeschlagen:",a),alert("Löschen fehlgeschlagen")}};return!t.privacyPolicyPath&&!e?null:i.jsx(Z,{title:"Dokumente",className:"mb-6",children:i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-2",children:"Datenschutzerklärung"}),t.privacyPolicyPath?i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("a",{href:`/api${t.privacyPolicyPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${t.privacyPolicyPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),e&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{onUpload:s,existingFile:t.privacyPolicyPath,accept:".pdf",label:"Ersetzen"}),i.jsxs("button",{onClick:r,className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]})]}):e?i.jsx(Jt,{onUpload:s,accept:".pdf",label:"PDF hochladen"}):i.jsx("p",{className:"text-sm text-gray-400",children:"Nicht vorhanden"})]})})}function dR({customerId:t,addresses:e,canEdit:n,onAdd:s,onEdit:r}){const a=ye(),l=G({mutationFn:$g.delete,onSuccess:()=>a.invalidateQueries({queryKey:["customer",t.toString()]})});return i.jsxs("div",{children:[n&&i.jsx("div",{className:"mb-4",children:i.jsxs(I,{size:"sm",onClick:s,children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Adresse hinzufügen"]})}),e.length>0?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:e.map(o=>i.jsxs("div",{className:"border rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(I5,{className:"w-4 h-4 text-gray-400"}),i.jsx(je,{variant:o.type==="BILLING"?"info":"default",children:o.type==="BILLING"?"Rechnung":"Liefer-/Meldeadresse"}),o.isDefault&&i.jsx(je,{variant:"success",children:"Standard"})]}),n&&i.jsxs("div",{className:"flex gap-1",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>r(o),title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&l.mutate(o.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]}),i.jsxs(Vg,{values:[`${o.street} ${o.houseNumber}`,`${o.postalCode} ${o.city}`,o.country],children:[i.jsxs("p",{children:[o.street," ",o.houseNumber]}),i.jsxs("p",{children:[o.postalCode," ",o.city]}),i.jsx("p",{className:"text-gray-500",children:o.country})]})]},o.id))}):i.jsx("p",{className:"text-gray-500",children:"Keine Adressen vorhanden."})]})}function uR({customerId:t,bankCards:e,canEdit:n,showInactive:s,onToggleInactive:r,onAdd:a,onEdit:l}){const o=ye(),c=G({mutationFn:({id:f,data:p})=>ch.update(f,p),onSuccess:()=>o.invalidateQueries({queryKey:["customer",t.toString()]})}),d=G({mutationFn:ch.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",t.toString()]})}),u=async(f,p)=>{try{await Ct.uploadBankCardDocument(f,p),o.invalidateQueries({queryKey:["customer",t.toString()]})}catch(g){console.error("Upload fehlgeschlagen:",g),alert("Upload fehlgeschlagen")}},h=async f=>{if(confirm("Dokument wirklich löschen?"))try{await Ct.deleteBankCardDocument(f),o.invalidateQueries({queryKey:["customer",t.toString()]})}catch(p){console.error("Löschen fehlgeschlagen:",p),alert("Löschen fehlgeschlagen")}},m=s?e:e.filter(f=>f.isActive);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&i.jsxs(I,{size:"sm",onClick:a,children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Bankkarte hinzufügen"]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:r,className:"rounded"}),"Inaktive anzeigen"]})]}),m.length>0?i.jsx("div",{className:"space-y-4",children:m.map(f=>i.jsxs("div",{className:`border rounded-lg p-4 ${f.isActive?"":"opacity-50 bg-gray-50"}`,children:[i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(Ry,{className:"w-4 h-4 text-gray-400"}),!f.isActive&&i.jsx(je,{variant:"danger",children:"Inaktiv"}),f.expiryDate&&new Date(f.expiryDate)l(f),title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),f.isActive?i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte deaktivieren?")&&c.mutate({id:f.id,data:{isActive:!1}})},title:"Deaktivieren",children:i.jsx(on,{className:"w-4 h-4"})}):i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wieder aktivieren?")&&c.mutate({id:f.id,data:{isActive:!0}})},title:"Aktivieren",children:i.jsx(Oe,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Bankkarte wirklich löschen?")&&d.mutate(f.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]}),i.jsxs("p",{className:"font-medium flex items-center gap-1",children:[f.accountHolder,i.jsx(de,{value:f.accountHolder})]}),i.jsxs("p",{className:"font-mono flex items-center gap-1",children:[f.iban,i.jsx(de,{value:f.iban})]}),f.bic&&i.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["BIC: ",f.bic,i.jsx(de,{value:f.bic})]}),f.bankName&&i.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:[f.bankName,i.jsx(de,{value:f.bankName})]}),f.expiryDate&&i.jsxs("p",{className:"text-sm text-gray-500",children:["Gültig bis: ",new Date(f.expiryDate).toLocaleDateString("de-DE")]}),i.jsx("div",{className:"mt-3 pt-3 border-t",children:f.documentPath?i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("a",{href:`/api${f.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${f.documentPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),n&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{onUpload:p=>u(f.id,p),existingFile:f.documentPath,accept:".pdf",label:"Ersetzen",disabled:!f.isActive}),i.jsxs("button",{onClick:()=>h(f.id),className:"text-red-600 hover:underline text-sm flex items-center gap-1",title:"Dokument löschen",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&f.isActive&&i.jsx(Jt,{onUpload:p=>u(f.id,p),accept:".pdf",label:"PDF hochladen"})})]},f.id))}):i.jsx("p",{className:"text-gray-500",children:"Keine Bankkarten vorhanden."})]})}function hR({customerId:t,documents:e,canEdit:n,showInactive:s,onToggleInactive:r,onAdd:a,onEdit:l}){const o=ye(),c=G({mutationFn:({id:p,data:g})=>dh.update(p,g),onSuccess:()=>o.invalidateQueries({queryKey:["customer",t.toString()]})}),d=G({mutationFn:dh.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",t.toString()]})}),u=async(p,g)=>{try{await Ct.uploadIdentityDocument(p,g),o.invalidateQueries({queryKey:["customer",t.toString()]})}catch(x){console.error("Upload fehlgeschlagen:",x),alert("Upload fehlgeschlagen")}},h=async p=>{if(confirm("Dokument wirklich löschen?"))try{await Ct.deleteIdentityDocument(p),o.invalidateQueries({queryKey:["customer",t.toString()]})}catch(g){console.error("Löschen fehlgeschlagen:",g),alert("Löschen fehlgeschlagen")}},m=s?e:e.filter(p=>p.isActive),f={ID_CARD:"Personalausweis",PASSPORT:"Reisepass",DRIVERS_LICENSE:"Führerschein",OTHER:"Sonstiges"};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&i.jsxs(I,{size:"sm",onClick:a,children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Ausweis hinzufügen"]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:r,className:"rounded"}),"Inaktive anzeigen"]})]}),m.length>0?i.jsx("div",{className:"space-y-4",children:m.map(p=>i.jsxs("div",{className:`border rounded-lg p-4 ${p.isActive?"":"opacity-50 bg-gray-50"}`,children:[i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(We,{className:"w-4 h-4 text-gray-400"}),i.jsx(je,{children:f[p.type]}),!p.isActive&&i.jsx(je,{variant:"danger",children:"Inaktiv"}),p.expiryDate&&new Date(p.expiryDate)l(p),title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),p.isActive?i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis deaktivieren?")&&c.mutate({id:p.id,data:{isActive:!1}})},title:"Deaktivieren",children:i.jsx(on,{className:"w-4 h-4"})}):i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wieder aktivieren?")&&c.mutate({id:p.id,data:{isActive:!0}})},title:"Aktivieren",children:i.jsx(Oe,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Ausweis wirklich löschen?")&&d.mutate(p.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]}),i.jsxs("p",{className:"font-mono flex items-center gap-1",children:[p.documentNumber,i.jsx(de,{value:p.documentNumber})]}),p.issuingAuthority&&i.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Ausgestellt von: ",p.issuingAuthority,i.jsx(de,{value:p.issuingAuthority})]}),p.expiryDate&&i.jsxs("p",{className:"text-sm text-gray-500",children:["Gültig bis: ",new Date(p.expiryDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})]}),p.type==="DRIVERS_LICENSE"&&p.licenseClasses&&i.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Klassen: ",p.licenseClasses,i.jsx(de,{value:p.licenseClasses})]}),p.type==="DRIVERS_LICENSE"&&p.licenseIssueDate&&i.jsxs("p",{className:"text-sm text-gray-500",children:["Klasse B seit: ",new Date(p.licenseIssueDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})]}),i.jsx("div",{className:"mt-3 pt-3 border-t",children:p.documentPath?i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("a",{href:`/api${p.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${p.documentPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),n&&i.jsxs(i.Fragment,{children:[i.jsx(Jt,{onUpload:g=>u(p.id,g),existingFile:p.documentPath,accept:".pdf",label:"Ersetzen",disabled:!p.isActive}),i.jsxs("button",{onClick:()=>h(p.id),className:"text-red-600 hover:underline text-sm flex items-center gap-1",title:"Dokument löschen",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]})]}):n&&p.isActive&&i.jsx(Jt,{onUpload:g=>u(p.id,g),accept:".pdf",label:"PDF hochladen"})})]},p.id))}):i.jsx("p",{className:"text-gray-500",children:"Keine Ausweise vorhanden."})]})}function fR({customerId:t,meters:e,canEdit:n,showInactive:s,onToggleInactive:r,onAdd:a,onEdit:l}){const[o,c]=N.useState(null),[d,u]=N.useState(null),[h,m]=N.useState(null),f=ye(),p=G({mutationFn:({id:b,data:j})=>ar.update(b,j),onSuccess:()=>f.invalidateQueries({queryKey:["customer",t.toString()]})}),g=G({mutationFn:ar.delete,onSuccess:()=>f.invalidateQueries({queryKey:["customer",t.toString()]})}),x=G({mutationFn:({meterId:b,readingId:j})=>ar.deleteReading(b,j),onSuccess:()=>f.invalidateQueries({queryKey:["customer",t.toString()]})}),y=s?e:e.filter(b=>b.isActive),v=b=>b?[...b].sort((j,k)=>new Date(k.readingDate).getTime()-new Date(j.readingDate).getTime()):[];return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&i.jsxs(I,{size:"sm",onClick:a,children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Zähler hinzufügen"]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:r,className:"rounded"}),"Inaktive anzeigen"]})]}),y.length>0?i.jsx("div",{className:"space-y-4",children:y.map(b=>{const j=v(b.readings),k=d===b.id;return i.jsxs("div",{className:`border rounded-lg p-4 ${b.isActive?"":"opacity-50 bg-gray-50"}`,children:[i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx(bC,{className:"w-4 h-4 text-gray-400"}),i.jsx(je,{variant:b.type==="ELECTRICITY"?"warning":"info",children:b.type==="ELECTRICITY"?"Strom":"Gas"}),!b.isActive&&i.jsx(je,{variant:"danger",children:"Inaktiv"})]}),n&&i.jsxs("div",{className:"flex gap-1",children:[b.isActive&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c({meterId:b.id,meterType:b.type}),title:"Zählerstand hinzufügen",children:i.jsx(Ge,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>l(b),title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),b.isActive?i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler deaktivieren?")&&p.mutate({id:b.id,data:{isActive:!1}})},title:"Deaktivieren",children:i.jsx(on,{className:"w-4 h-4"})}):i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wieder aktivieren?")&&p.mutate({id:b.id,data:{isActive:!0}})},title:"Aktivieren",children:i.jsx(Oe,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Zähler wirklich löschen? Alle Zählerstände werden ebenfalls gelöscht.")&&g.mutate(b.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]}),i.jsxs("p",{className:"font-mono text-lg flex items-center gap-1",children:[b.meterNumber,i.jsx(de,{value:b.meterNumber})]}),b.location&&i.jsxs("p",{className:"text-sm text-gray-500 flex items-center gap-1",children:["Standort: ",b.location,i.jsx(de,{value:b.location})]}),j.length>0&&i.jsxs("div",{className:"mt-3 pt-3 border-t",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("p",{className:"text-sm font-medium",children:"Zählerstände:"}),j.length>3&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>u(k?null:b.id),children:k?"Weniger anzeigen":`Alle ${j.length} anzeigen`})]}),i.jsx("div",{className:"space-y-1",children:(k?j:j.slice(0,3)).map(E=>i.jsxs("div",{className:"flex justify-between items-center text-sm group",children:[i.jsxs("span",{className:"text-gray-500 flex items-center gap-1",children:[new Date(E.readingDate).toLocaleDateString("de-DE"),i.jsx(de,{value:new Date(E.readingDate).toLocaleDateString("de-DE")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"font-mono flex items-center gap-1",children:[E.value.toLocaleString("de-DE")," ",E.unit,i.jsx(de,{value:E.value.toString(),title:"Nur Wert kopieren"}),i.jsx(de,{value:`${E.value.toLocaleString("de-DE")} ${E.unit}`,title:"Mit Einheit kopieren"})]}),n&&i.jsxs("div",{className:"opacity-0 group-hover:opacity-100 flex gap-1",children:[i.jsx("button",{onClick:()=>m({meterId:b.id,meterType:b.type,reading:E}),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:i.jsx(rt,{className:"w-3 h-3"})}),i.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&x.mutate({meterId:b.id,readingId:E.id})},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:i.jsx(Ee,{className:"w-3 h-3"})})]})]})]},E.id))})]})]},b.id)})}):i.jsx("p",{className:"text-gray-500",children:"Keine Zähler vorhanden."}),o&&i.jsx(I1,{isOpen:!0,onClose:()=>c(null),meterId:o.meterId,meterType:o.meterType,customerId:t}),h&&i.jsx(I1,{isOpen:!0,onClose:()=>m(null),meterId:h.meterId,meterType:h.meterType,customerId:t,reading:h.reading})]})}function mR({customerId:t}){const{hasPermission:e}=nt(),n=fn(),s=ye(),[r,a]=N.useState(new Set),[l,o]=N.useState(!1),{data:c,isLoading:d}=fe({queryKey:["contract-tree",t],queryFn:()=>He.getTreeForCustomer(t)}),u=(c==null?void 0:c.data)||[],h=G({mutationFn:He.delete,onSuccess:()=>{s.invalidateQueries({queryKey:["customer",t.toString()]}),s.invalidateQueries({queryKey:["customers"]}),s.invalidateQueries({queryKey:["contracts"]}),s.invalidateQueries({queryKey:["contract-tree",t]})},onError:v=>{alert((v==null?void 0:v.message)||"Fehler beim Löschen des Vertrags")}}),m={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},f={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},p=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}],g=v=>{a(b=>{const j=new Set(b);return j.has(v)?j.delete(v):j.add(v),j})},x=(v,b)=>v.map(j=>i.jsx("div",{children:y(j,b)},j.contract.id)),y=(v,b=0)=>{var S,M,F,R,V,D,z;const{contract:j,predecessors:k,hasHistory:E}=v,T=r.has(j.id),w=b>0;return i.jsxs("div",{children:[i.jsxs("div",{className:` + border rounded-lg p-4 transition-colors + ${w?"ml-6 border-l-4 border-l-gray-300 bg-gray-50":"hover:bg-gray-50"} + `,children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[!w&&E?i.jsx("button",{onClick:()=>g(j.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:T?"Einklappen":"Vorgänger anzeigen",children:T?i.jsx(Us,{className:"w-4 h-4 text-gray-500"}):i.jsx(At,{className:"w-4 h-4 text-gray-500"})}):w?null:i.jsx("div",{className:"w-6"}),i.jsxs("span",{className:"font-mono flex items-center gap-1",children:[j.contractNumber,i.jsx(de,{value:j.contractNumber})]}),i.jsx(je,{children:m[j.type]||j.type}),i.jsx(je,{variant:f[j.status]||"default",children:j.status}),b===0&&!w&&i.jsx("button",{onClick:C=>{C.stopPropagation(),o(!0)},className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:i.jsx(bd,{className:"w-4 h-4"})}),w&&i.jsx("span",{className:"text-xs text-gray-500 ml-2",children:"(Vorgänger)"})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${j.id}`,{state:{from:"customer",customerId:t.toString()}}),title:"Ansehen",children:i.jsx(Oe,{className:"w-4 h-4"})}),e("contracts:update")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${j.id}/edit`),title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),e("contracts:delete")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&h.mutate(j.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]}),(j.providerName||((S=j.provider)==null?void 0:S.name))&&i.jsxs("p",{className:`flex items-center gap-1 ${w?"ml-6":""}`,children:[j.providerName||((M=j.provider)==null?void 0:M.name),(j.tariffName||((F=j.tariff)==null?void 0:F.name))&&` - ${j.tariffName||((R=j.tariff)==null?void 0:R.name)}`,i.jsx(de,{value:(j.providerName||((V=j.provider)==null?void 0:V.name)||"")+(j.tariffName||(D=j.tariff)!=null&&D.name?` - ${j.tariffName||((z=j.tariff)==null?void 0:z.name)}`:"")})]}),j.startDate&&i.jsxs("p",{className:`text-sm text-gray-500 ${w?"ml-6":""}`,children:["Beginn: ",new Date(j.startDate).toLocaleDateString("de-DE"),j.endDate&&` | Ende: ${new Date(j.endDate).toLocaleDateString("de-DE")}`]})]}),(b===0&&T||b>0)&&k.length>0&&i.jsx("div",{className:"mt-2",children:x(k,b+1)})]},j.id)};return d?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"})}):i.jsxs("div",{children:[e("contracts:create")&&i.jsx("div",{className:"mb-4",children:i.jsx(Me,{to:`/contracts/new?customerId=${t}`,children:i.jsxs(I,{size:"sm",children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Vertrag anlegen"]})})}),u.length>0?i.jsx("div",{className:"space-y-4",children:u.map(v=>y(v,0))}):i.jsx("p",{className:"text-gray-500",children:"Keine Verträge vorhanden."}),l&&i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:()=>o(!1)}),i.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),i.jsx("button",{onClick:()=>o(!1),className:"text-gray-400 hover:text-gray-600",children:i.jsx(nn,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"space-y-2",children:p.map(({status:v,label:b,description:j,color:k})=>i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:`font-medium text-sm min-w-[90px] ${k}`,children:b}),i.jsx("span",{className:"text-sm text-gray-600",children:j})]},v))})]})]})]})}function pR({customerId:t}){const[e,n]=N.useState(!1),[s,r]=N.useState(null),[a,l]=N.useState(!1),o=async()=>{var c;if(e){n(!1);return}l(!0);try{const d=await Zt.getPortalPassword(t);r(((c=d.data)==null?void 0:c.password)||null),n(!0)}catch(d){console.error("Fehler beim Laden des Passworts:",d),alert("Fehler beim Laden des Passworts")}finally{l(!1)}};return i.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[i.jsx("p",{className:"text-xs text-green-600",children:"Passwort ist gesetzt"}),i.jsx("button",{type:"button",onClick:o,className:"text-xs text-blue-600 hover:underline flex items-center gap-1",disabled:a,children:a?"Laden...":e?i.jsxs(i.Fragment,{children:[i.jsx(on,{className:"w-3 h-3"}),"Verbergen"]}):i.jsxs(i.Fragment,{children:[i.jsx(Oe,{className:"w-3 h-3"}),"Anzeigen"]})}),e&&s&&i.jsxs("span",{className:"text-xs font-mono bg-gray-100 px-2 py-1 rounded flex items-center gap-1",children:[s,i.jsx(de,{value:s})]}),e&&!s&&i.jsx("span",{className:"text-xs text-gray-500",children:"(Passwort nicht verfügbar)"})]})}function gR({customerId:t,canEdit:e}){const n=ye(),[s,r]=N.useState(!1),[a,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState([]),[h,m]=N.useState(!1),{data:f,isLoading:p}=fe({queryKey:["customer-portal",t],queryFn:()=>Zt.getPortalSettings(t)}),{data:g,isLoading:x}=fe({queryKey:["customer-representatives",t],queryFn:()=>Zt.getRepresentatives(t)}),y=G({mutationFn:w=>Zt.updatePortalSettings(t,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-portal",t]})}}),v=G({mutationFn:w=>Zt.setPortalPassword(t,w),onSuccess:()=>{l(""),n.invalidateQueries({queryKey:["customer-portal",t]}),alert("Passwort wurde gesetzt")},onError:w=>{alert(w.message)}}),b=G({mutationFn:w=>Zt.addRepresentative(t,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",t]}),c(""),u([])},onError:w=>{alert(w.message)}}),j=G({mutationFn:w=>Zt.removeRepresentative(t,w),onSuccess:()=>{n.invalidateQueries({queryKey:["customer-representatives",t]})}}),k=async()=>{if(!(o.length<2)){m(!0);try{const w=await Zt.searchForRepresentative(t,o);u(w.data||[])}catch(w){console.error("Suche fehlgeschlagen:",w)}finally{m(!1)}}};if(p||x)return i.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."});const E=f==null?void 0:f.data,T=(g==null?void 0:g.data)||[];return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"border rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[i.jsx(Ly,{className:"w-5 h-5 text-gray-400"}),i.jsx("h3",{className:"font-medium",children:"Portal-Zugang"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsxs("label",{className:"flex items-center gap-3",children:[i.jsx("input",{type:"checkbox",checked:(E==null?void 0:E.portalEnabled)||!1,onChange:w=>y.mutate({portalEnabled:w.target.checked}),className:"rounded w-5 h-5",disabled:!e}),i.jsx("span",{children:"Portal aktiviert"}),(E==null?void 0:E.portalEnabled)&&i.jsx(je,{variant:"success",children:"Aktiv"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Portal E-Mail"}),i.jsx("div",{className:"flex gap-2",children:i.jsx(q,{value:(E==null?void 0:E.portalEmail)||"",onChange:w=>y.mutate({portalEmail:w.target.value||null}),placeholder:"portal@example.com",disabled:!e||!(E!=null&&E.portalEnabled),className:"flex-1"})}),i.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Diese E-Mail wird für den Login ins Kundenportal verwendet."})]}),(E==null?void 0:E.portalEnabled)&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:E!=null&&E.hasPassword?"Neues Passwort setzen":"Passwort setzen"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(q,{type:s?"text":"password",value:a,onChange:w=>l(w.target.value),placeholder:"Mindestens 6 Zeichen",disabled:!e}),i.jsx("button",{type:"button",onClick:()=>r(!s),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400",children:s?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]}),i.jsx(I,{onClick:()=>v.mutate(a),disabled:!e||a.length<6||v.isPending,children:v.isPending?"Speichern...":"Setzen"})]}),(E==null?void 0:E.hasPassword)&&i.jsx(pR,{customerId:t})]}),(E==null?void 0:E.portalLastLogin)&&i.jsxs("p",{className:"text-sm text-gray-500",children:["Letzte Anmeldung: ",new Date(E.portalLastLogin).toLocaleString("de-DE")]})]})]}),i.jsxs("div",{className:"border rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[i.jsx(U5,{className:"w-5 h-5 text-gray-400"}),i.jsx("h3",{className:"font-medium",children:"Vertreter (können Verträge einsehen)"})]}),i.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie anderen Kunden erlauben, die Verträge dieses Kunden einzusehen. Beispiel: Der Sohn kann die Verträge seiner Mutter einsehen."}),e&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsx(q,{value:o,onChange:w=>c(w.target.value),placeholder:"Kunden suchen (Name, Kundennummer)...",onKeyDown:w=>w.key==="Enter"&&k(),className:"flex-1"}),i.jsx(I,{variant:"secondary",onClick:k,disabled:o.length<2||h,children:i.jsx(jd,{className:"w-4 h-4"})})]}),i.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Nur Kunden mit aktiviertem Portal können als Vertreter hinzugefügt werden."}),d.length>0&&i.jsx("div",{className:"mt-2 border rounded-lg divide-y",children:d.map(w=>i.jsxs("div",{className:"flex items-center justify-between p-3 hover:bg-gray-50",children:[i.jsxs("div",{children:[i.jsx("p",{className:"font-medium",children:w.companyName||`${w.firstName} ${w.lastName}`}),i.jsx("p",{className:"text-sm text-gray-500",children:w.customerNumber})]}),i.jsxs(I,{size:"sm",onClick:()=>b.mutate(w.id),disabled:b.isPending,children:[i.jsx(Ge,{className:"w-4 h-4 mr-1"}),"Hinzufügen"]})]},w.id))})]}),T.length>0?i.jsx("div",{className:"space-y-2",children:T.map(w=>{var S,M,F,R;return i.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg",children:[i.jsxs("div",{children:[i.jsx("p",{className:"font-medium",children:((S=w.representative)==null?void 0:S.companyName)||`${(M=w.representative)==null?void 0:M.firstName} ${(F=w.representative)==null?void 0:F.lastName}`}),i.jsx("p",{className:"text-sm text-gray-500",children:(R=w.representative)==null?void 0:R.customerNumber})]}),e&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertreter wirklich entfernen?")&&j.mutate(w.representativeId)},children:i.jsx(nn,{className:"w-4 h-4 text-red-500"})})]},w.id)})}):i.jsx("p",{className:"text-gray-500 text-sm",children:"Keine Vertreter konfiguriert."})]})]})}function D1({isOpen:t,onClose:e,customerId:n,address:s}){const r=ye(),a=!!s,l=()=>({type:(s==null?void 0:s.type)||"DELIVERY_RESIDENCE",street:(s==null?void 0:s.street)||"",houseNumber:(s==null?void 0:s.houseNumber)||"",postalCode:(s==null?void 0:s.postalCode)||"",city:(s==null?void 0:s.city)||"",country:(s==null?void 0:s.country)||"Deutschland",isDefault:(s==null?void 0:s.isDefault)||!1}),[o,c]=N.useState(l),d=G({mutationFn:f=>$g.create(n,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e(),c({type:"DELIVERY_RESIDENCE",street:"",houseNumber:"",postalCode:"",city:"",country:"Deutschland",isDefault:!1})}}),u=G({mutationFn:f=>$g.update(s.id,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e()}}),h=f=>{f.preventDefault(),a?u.mutate(o):d.mutate(o)},m=d.isPending||u.isPending;return a&&o.street!==s.street&&c(l()),i.jsx(Xe,{isOpen:t,onClose:e,title:a?"Adresse bearbeiten":"Adresse hinzufügen",children:i.jsxs("form",{onSubmit:h,className:"space-y-4",children:[i.jsx(Fe,{label:"Adresstyp",value:o.type,onChange:f=>c({...o,type:f.target.value}),options:[{value:"DELIVERY_RESIDENCE",label:"Liefer-/Meldeadresse"},{value:"BILLING",label:"Rechnungsadresse"}]}),i.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[i.jsx("div",{className:"col-span-2",children:i.jsx(q,{label:"Straße",value:o.street,onChange:f=>c({...o,street:f.target.value}),required:!0})}),i.jsx(q,{label:"Hausnr.",value:o.houseNumber,onChange:f=>c({...o,houseNumber:f.target.value}),required:!0})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[i.jsx(q,{label:"PLZ",value:o.postalCode,onChange:f=>c({...o,postalCode:f.target.value}),required:!0}),i.jsx("div",{className:"col-span-2",children:i.jsx(q,{label:"Ort",value:o.city,onChange:f=>c({...o,city:f.target.value}),required:!0})})]}),i.jsx(q,{label:"Land",value:o.country,onChange:f=>c({...o,country:f.target.value})}),i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:o.isDefault,onChange:f=>c({...o,isDefault:f.target.checked}),className:"rounded"}),"Als Standard setzen"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:m,children:m?"Speichern...":"Speichern"})]})]})})}function M1({isOpen:t,onClose:e,customerId:n,bankCard:s}){const r=ye(),a=!!s,l=()=>({accountHolder:(s==null?void 0:s.accountHolder)||"",iban:(s==null?void 0:s.iban)||"",bic:(s==null?void 0:s.bic)||"",bankName:(s==null?void 0:s.bankName)||"",expiryDate:s!=null&&s.expiryDate?new Date(s.expiryDate).toISOString().split("T")[0]:"",isActive:(s==null?void 0:s.isActive)??!0}),[o,c]=N.useState(l);N.useState(()=>{c(l())});const d=G({mutationFn:f=>ch.create(n,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e(),c({accountHolder:"",iban:"",bic:"",bankName:"",expiryDate:"",isActive:!0})}}),u=G({mutationFn:f=>ch.update(s.id,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e()}}),h=f=>{f.preventDefault();const p={...o,expiryDate:o.expiryDate?new Date(o.expiryDate):void 0};a?u.mutate(p):d.mutate(p)},m=d.isPending||u.isPending;return a&&o.iban!==s.iban&&c(l()),i.jsx(Xe,{isOpen:t,onClose:e,title:a?"Bankkarte bearbeiten":"Bankkarte hinzufügen",children:i.jsxs("form",{onSubmit:h,className:"space-y-4",children:[i.jsx(q,{label:"Kontoinhaber",value:o.accountHolder,onChange:f=>c({...o,accountHolder:f.target.value}),required:!0}),i.jsx(q,{label:"IBAN",value:o.iban,onChange:f=>c({...o,iban:f.target.value}),required:!0}),i.jsx(q,{label:"BIC",value:o.bic,onChange:f=>c({...o,bic:f.target.value})}),i.jsx(q,{label:"Bank",value:o.bankName,onChange:f=>c({...o,bankName:f.target.value})}),i.jsx(q,{label:"Ablaufdatum",type:"date",value:o.expiryDate,onChange:f=>c({...o,expiryDate:f.target.value}),onClear:()=>c({...o,expiryDate:""})}),a&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:o.isActive,onChange:f=>c({...o,isActive:f.target.checked}),className:"rounded"}),"Aktiv"]}),!a&&i.jsx("p",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded",children:"Dokument-Upload ist nach dem Speichern in der Übersicht möglich."}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:m,children:m?"Speichern...":"Speichern"})]})]})})}function T1({isOpen:t,onClose:e,customerId:n,document:s}){const r=ye(),a=!!s,l=()=>({type:(s==null?void 0:s.type)||"ID_CARD",documentNumber:(s==null?void 0:s.documentNumber)||"",issuingAuthority:(s==null?void 0:s.issuingAuthority)||"",issueDate:s!=null&&s.issueDate?new Date(s.issueDate).toISOString().split("T")[0]:"",expiryDate:s!=null&&s.expiryDate?new Date(s.expiryDate).toISOString().split("T")[0]:"",isActive:(s==null?void 0:s.isActive)??!0,licenseClasses:(s==null?void 0:s.licenseClasses)||"",licenseIssueDate:s!=null&&s.licenseIssueDate?new Date(s.licenseIssueDate).toISOString().split("T")[0]:""}),[o,c]=N.useState(l),d=G({mutationFn:f=>dh.create(n,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e(),c({type:"ID_CARD",documentNumber:"",issuingAuthority:"",issueDate:"",expiryDate:"",isActive:!0,licenseClasses:"",licenseIssueDate:""})}}),u=G({mutationFn:f=>dh.update(s.id,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e()}}),h=f=>{f.preventDefault();const p={...o,issueDate:o.issueDate?new Date(o.issueDate):void 0,expiryDate:o.expiryDate?new Date(o.expiryDate):void 0};o.type==="DRIVERS_LICENSE"?(p.licenseClasses=o.licenseClasses||void 0,p.licenseIssueDate=o.licenseIssueDate?new Date(o.licenseIssueDate):void 0):(delete p.licenseClasses,delete p.licenseIssueDate),a?u.mutate(p):d.mutate(p)},m=d.isPending||u.isPending;return a&&o.documentNumber!==s.documentNumber&&c(l()),i.jsx(Xe,{isOpen:t,onClose:e,title:a?"Ausweis bearbeiten":"Ausweis hinzufügen",children:i.jsxs("form",{onSubmit:h,className:"space-y-4",children:[i.jsx(Fe,{label:"Ausweistyp",value:o.type,onChange:f=>c({...o,type:f.target.value}),options:[{value:"ID_CARD",label:"Personalausweis"},{value:"PASSPORT",label:"Reisepass"},{value:"DRIVERS_LICENSE",label:"Führerschein"},{value:"OTHER",label:"Sonstiges"}]}),i.jsx(q,{label:"Ausweisnummer",value:o.documentNumber,onChange:f=>c({...o,documentNumber:f.target.value}),required:!0}),i.jsx(q,{label:"Ausstellende Behörde",value:o.issuingAuthority,onChange:f=>c({...o,issuingAuthority:f.target.value})}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(q,{label:"Ausstellungsdatum",type:"date",value:o.issueDate,onChange:f=>c({...o,issueDate:f.target.value}),onClear:()=>c({...o,issueDate:""})}),i.jsx(q,{label:"Ablaufdatum",type:"date",value:o.expiryDate,onChange:f=>c({...o,expiryDate:f.target.value}),onClear:()=>c({...o,expiryDate:""})})]}),o.type==="DRIVERS_LICENSE"&&i.jsxs(i.Fragment,{children:[i.jsx(q,{label:"Führerscheinklassen",value:o.licenseClasses,onChange:f=>c({...o,licenseClasses:f.target.value}),placeholder:"z.B. B, BE, AM, L"}),i.jsx(q,{label:"Erwerb Klasse B (Pkw)",type:"date",value:o.licenseIssueDate,onChange:f=>c({...o,licenseIssueDate:f.target.value}),onClear:()=>c({...o,licenseIssueDate:""})})]}),a&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:o.isActive,onChange:f=>c({...o,isActive:f.target.checked}),className:"rounded"}),"Aktiv"]}),!a&&i.jsx("p",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded",children:"Dokument-Upload ist nach dem Speichern in der Übersicht möglich."}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:m,children:m?"Speichern...":"Speichern"})]})]})})}function P1({isOpen:t,onClose:e,customerId:n,meter:s}){const r=ye(),a=!!s,l=()=>({meterNumber:(s==null?void 0:s.meterNumber)||"",type:(s==null?void 0:s.type)||"ELECTRICITY",location:(s==null?void 0:s.location)||"",isActive:(s==null?void 0:s.isActive)??!0}),[o,c]=N.useState(l),d=G({mutationFn:f=>ar.create(n,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e(),c({meterNumber:"",type:"ELECTRICITY",location:"",isActive:!0})}}),u=G({mutationFn:f=>ar.update(s.id,f),onSuccess:()=>{r.invalidateQueries({queryKey:["customer",n.toString()]}),e()}}),h=f=>{f.preventDefault(),a?u.mutate(o):d.mutate(o)},m=d.isPending||u.isPending;return a&&o.meterNumber!==s.meterNumber&&c(l()),i.jsx(Xe,{isOpen:t,onClose:e,title:a?"Zähler bearbeiten":"Zähler hinzufügen",children:i.jsxs("form",{onSubmit:h,className:"space-y-4",children:[i.jsx(q,{label:"Zählernummer",value:o.meterNumber,onChange:f=>c({...o,meterNumber:f.target.value}),required:!0}),i.jsx(Fe,{label:"Zählertyp",value:o.type,onChange:f=>c({...o,type:f.target.value}),options:[{value:"ELECTRICITY",label:"Strom"},{value:"GAS",label:"Gas"}]}),i.jsx(q,{label:"Standort",value:o.location,onChange:f=>c({...o,location:f.target.value}),placeholder:"z.B. Keller, Wohnung"}),a&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:o.isActive,onChange:f=>c({...o,isActive:f.target.checked}),className:"rounded"}),"Aktiv"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:m,children:m?"Speichern...":"Speichern"})]})]})})}function I1({isOpen:t,onClose:e,meterId:n,meterType:s,customerId:r,reading:a}){const l=ye(),o=!!a,c=s==="ELECTRICITY"?"kWh":"m³",d=()=>{var x;return{readingDate:a!=null&&a.readingDate?new Date(a.readingDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],value:((x=a==null?void 0:a.value)==null?void 0:x.toString())||"",notes:(a==null?void 0:a.notes)||""}},[u,h]=N.useState(d),m=G({mutationFn:x=>ar.addReading(n,x),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",r.toString()]}),e()}}),f=G({mutationFn:x=>ar.updateReading(n,a.id,x),onSuccess:()=>{l.invalidateQueries({queryKey:["customer",r.toString()]}),e()}}),p=x=>{x.preventDefault();const y={readingDate:new Date(u.readingDate),value:parseFloat(u.value),unit:c,notes:u.notes||void 0};o?f.mutate(y):m.mutate(y)},g=m.isPending||f.isPending;return o&&u.value!==a.value.toString()&&h(d()),i.jsx(Xe,{isOpen:t,onClose:e,title:o?"Zählerstand bearbeiten":"Zählerstand erfassen",children:i.jsxs("form",{onSubmit:p,className:"space-y-4",children:[i.jsx(q,{label:"Ablesedatum",type:"date",value:u.readingDate,onChange:x=>h({...u,readingDate:x.target.value}),required:!0}),i.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[i.jsx("div",{className:"col-span-2",children:i.jsx(q,{label:"Zählerstand",type:"number",step:"0.01",value:u.value,onChange:x=>h({...u,value:x.target.value}),required:!0})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Einheit"}),i.jsx("div",{className:"h-10 flex items-center px-3 bg-gray-100 border border-gray-300 rounded-md text-gray-700",children:c})]})]}),i.jsx(q,{label:"Notizen",value:u.notes,onChange:x=>h({...u,notes:x.target.value}),placeholder:"Optionale Notizen..."}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:g,children:g?"Speichern...":"Speichern"})]})]})})}const Lm="@stressfrei-wechseln.de";function xR({customerId:t,emails:e,canEdit:n,showInactive:s,onToggleInactive:r,onAdd:a,onEdit:l}){const o=ye(),c=G({mutationFn:({id:h,data:m})=>ts.update(h,m),onSuccess:()=>o.invalidateQueries({queryKey:["customer",t.toString()]})}),d=G({mutationFn:ts.delete,onSuccess:()=>o.invalidateQueries({queryKey:["customer",t.toString()]})}),u=s?e:e.filter(h=>h.isActive);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[n&&i.jsxs(I,{size:"sm",onClick:a,children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Adresse hinzufügen"]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:r,className:"rounded"}),"Inaktive anzeigen"]})]}),i.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[i.jsx("strong",{children:"Hinweis:"})," Hier werden E-Mail-Weiterleitungsadressen verwaltet, die für die Registrierung bei Anbietern verwendet werden. E-Mails an diese Adressen werden sowohl an den Kunden als auch an Sie weitergeleitet."]}),u.length>0?i.jsx("div",{className:"space-y-3",children:u.map(h=>i.jsx("div",{className:`border rounded-lg p-4 ${h.isActive?"":"opacity-50 bg-gray-50"}`,children:i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Fs,{className:"w-4 h-4 text-gray-400"}),i.jsx("span",{className:"font-mono text-sm",children:h.email}),i.jsx(de,{value:h.email}),!h.isActive&&i.jsx(je,{variant:"danger",children:"Inaktiv"})]}),h.notes&&i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-gray-500",children:[i.jsx(We,{className:"w-4 h-4 flex-shrink-0"}),i.jsx("span",{children:h.notes})]})]}),n&&i.jsxs("div",{className:"flex gap-1",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>l(h),title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),h.isActive?i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse deaktivieren?")&&c.mutate({id:h.id,data:{isActive:!1}})},title:"Deaktivieren",children:i.jsx(on,{className:"w-4 h-4"})}):i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wieder aktivieren?")&&c.mutate({id:h.id,data:{isActive:!0}})},title:"Aktivieren",children:i.jsx(Oe,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Adresse wirklich löschen?")&&d.mutate(h.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]})},h.id))}):i.jsx("p",{className:"text-gray-500",children:"Keine Stressfrei-Wechseln Adressen vorhanden."})]})}function yR({credentials:t,onHide:e,onResetPassword:n,isResettingPassword:s}){const[r,a]=N.useState(null),l=async(u,h)=>{try{await navigator.clipboard.writeText(u),a(h),setTimeout(()=>a(null),2e3)}catch{const m=document.createElement("textarea");m.value=u,document.body.appendChild(m),m.select(),document.execCommand("copy"),document.body.removeChild(m),a(h),setTimeout(()=>a(null),2e3)}},o=({text:u,fieldName:h})=>i.jsx("button",{type:"button",onClick:()=>l(u,h),className:"p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors",title:"In Zwischenablage kopieren",children:r===h?i.jsx(Vr,{className:"w-4 h-4 text-green-600"}):i.jsx(Iy,{className:"w-4 h-4"})}),c=t.imap?`${t.imap.server}:${t.imap.port}`:"",d=t.smtp?`${t.smtp.server}:${t.smtp.port}`:"";return i.jsxs("div",{className:"bg-gray-50 border border-gray-200 rounded-lg p-4 space-y-3",children:[i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wide",children:"Zugangsdaten"}),i.jsx("button",{type:"button",onClick:e,className:"text-gray-400 hover:text-gray-600 p-1 hover:bg-gray-200 rounded",title:"Zugangsdaten ausblenden",children:i.jsx(on,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[i.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Benutzername"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1 break-all",children:t.email}),i.jsx(o,{text:t.email,fieldName:"email"})]})]}),i.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[i.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Passwort"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1 break-all",children:t.password}),i.jsx(o,{text:t.password,fieldName:"password"})]}),i.jsx("button",{type:"button",onClick:n,disabled:s,className:"mt-2 text-xs text-blue-600 hover:text-blue-800 disabled:opacity-50",children:s?"Generiere...":"Neu generieren"})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.imap&&i.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[i.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"IMAP (Empfang)"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1",children:c}),i.jsx(o,{text:c,fieldName:"imap"})]}),i.jsx("span",{className:"text-xs text-gray-400 mt-1 block",children:t.imap.encryption})]}),t.smtp&&i.jsxs("div",{className:"bg-white rounded-lg p-3 border border-gray-100",children:[i.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"SMTP (Versand)"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("code",{className:"text-sm text-gray-900 font-mono flex-1",children:d}),i.jsx(o,{text:d,fieldName:"smtp"})]}),i.jsx("span",{className:"text-xs text-gray-400 mt-1 block",children:t.smtp.encryption})]})]})]})}function R1({isOpen:t,onClose:e,customerId:n,email:s,customerEmail:r}){const[a,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,m]=N.useState(!1),[f,p]=N.useState(null),[g,x]=N.useState("idle"),[y,v]=N.useState(!1),[b,j]=N.useState(!1),[k,E]=N.useState(!1),[T,w]=N.useState(!1),[S,M]=N.useState(null),[F,R]=N.useState(!1),[V,D]=N.useState(!1),z=ye(),C=!!s,{data:_}=fe({queryKey:["email-provider-configs"],queryFn:()=>wr.getConfigs(),enabled:t}),K=((_==null?void 0:_.data)||[]).some(le=>le.isActive&&le.isDefault),B=le=>{if(!le)return"";const it=le.indexOf("@");return it>0?le.substring(0,it):le},W=async le=>{var it;if(!(!K||!le)){x("checking");try{const Rt=await wr.checkEmailExists(le);x((it=Rt.data)!=null&&it.exists?"exists":"not_exists")}catch{x("error")}}},ce=async()=>{var le,it;if(!(!r||!a)){v(!0),p(null);try{const Rt=await wr.provisionEmail(a,r);(le=Rt.data)!=null&&le.success?x("exists"):p(((it=Rt.data)==null?void 0:it.error)||"Provisionierung fehlgeschlagen")}catch(Rt){p(Rt instanceof Error?Rt.message:"Fehler bei der Provisionierung")}finally{v(!1)}}},he=async()=>{if(s){j(!0),p(null);try{const le=await ts.enableMailbox(s.id);le.success?(E(!0),z.invalidateQueries({queryKey:["customer",n.toString()]}),z.invalidateQueries({queryKey:["mailbox-accounts",n]})):p(le.error||"Mailbox-Aktivierung fehlgeschlagen")}catch(le){p(le instanceof Error?le.message:"Fehler bei der Mailbox-Aktivierung")}finally{j(!1)}}},Je=async()=>{if(s)try{const le=await ts.syncMailboxStatus(s.id);le.success&&le.data&&(E(le.data.hasMailbox),le.data.wasUpdated&&z.invalidateQueries({queryKey:["customer",n.toString()]}))}catch(le){console.error("Fehler beim Synchronisieren des Mailbox-Status:",le)}},et=async()=>{if(s){R(!0);try{const le=await ts.getMailboxCredentials(s.id);le.success&&le.data&&(M(le.data),w(!0))}catch(le){console.error("Fehler beim Laden der Zugangsdaten:",le)}finally{R(!1)}}},mt=async()=>{if(s&&confirm("Neues Passwort generieren? Das alte Passwort wird ungültig.")){D(!0);try{const le=await ts.resetPassword(s.id);le.success&&le.data?(S&&M({...S,password:le.data.password}),alert("Passwort wurde erfolgreich zurückgesetzt.")):alert(le.error||"Fehler beim Zurücksetzen des Passworts")}catch(le){console.error("Fehler beim Zurücksetzen des Passworts:",le),alert(le instanceof Error?le.message:"Fehler beim Zurücksetzen des Passworts")}finally{D(!1)}}};N.useEffect(()=>{if(t){if(s){const le=B(s.email);l(le),c(s.notes||""),x("idle"),E(s.hasMailbox||!1),K&&(W(le),Je())}else l(""),c(""),u(!1),m(!1),x("idle"),E(!1);p(null),w(!1),M(null)}},[t,s,K]);const A=G({mutationFn:async le=>ts.create(n,{email:le.email,notes:le.notes,provisionAtProvider:le.provision,createMailbox:le.createMailbox}),onSuccess:()=>{z.invalidateQueries({queryKey:["customer",n.toString()]}),z.invalidateQueries({queryKey:["mailbox-accounts",n]}),l(""),c(""),u(!1),m(!1),e()},onError:le=>{p(le instanceof Error?le.message:"Fehler bei der Provisionierung")}}),pt=G({mutationFn:le=>ts.update(s.id,le),onSuccess:()=>{z.invalidateQueries({queryKey:["customer",n.toString()]}),e()}}),On=le=>{le.preventDefault(),p(null);const it=a+Lm;C?pt.mutate({email:it,notes:o||void 0}):A.mutate({email:it,notes:o||void 0,provision:d,createMailbox:d&&h})},wn=A.isPending||pt.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:C?"Adresse bearbeiten":"Adresse hinzufügen",children:i.jsxs("form",{onSubmit:On,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"E-Mail-Adresse"}),i.jsxs("div",{className:"flex",children:[i.jsx("input",{type:"text",value:a,onChange:le=>l(le.target.value.toLowerCase().replace(/[^a-z0-9._-]/g,"")),placeholder:"kunde-freenet",required:!0,className:"block w-full px-3 py-2 border border-gray-300 rounded-l-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),i.jsx("span",{className:"inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 bg-gray-100 text-gray-600 rounded-r-lg text-sm",children:Lm})]}),i.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Vollständige Adresse: ",i.jsxs("span",{className:"font-mono",children:[a||"...",Lm]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Notizen (optional)"}),i.jsx("textarea",{value:o,onChange:le=>c(le.target.value),rows:3,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"z.B. für Freenet-Konten, für Klarmobil..."})]}),K&&r&&i.jsx("div",{className:"bg-blue-50 p-3 rounded-lg",children:C?i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm font-medium text-gray-700",children:"E-Mail-Provider Status"}),g==="checking"&&i.jsx("span",{className:"text-xs text-gray-500",children:"Prüfe..."}),g==="exists"&&i.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[i.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),"Beim Provider vorhanden"]}),g==="not_exists"&&i.jsx("span",{className:"text-xs text-orange-600",children:"Nicht beim Provider angelegt"}),g==="error"&&i.jsx("span",{className:"text-xs text-red-600",children:"Status konnte nicht geprüft werden"})]}),g==="not_exists"&&i.jsxs("div",{className:"pt-2 border-t border-blue-100",children:[i.jsxs("p",{className:"text-xs text-gray-500 mb-2",children:["Die E-Mail-Weiterleitung ist noch nicht auf dem Server eingerichtet. Weiterleitungsziel: ",r]}),i.jsx(I,{type:"button",size:"sm",onClick:ce,disabled:y,children:y?"Wird angelegt...":"Jetzt beim Provider anlegen"})]}),g==="error"&&i.jsx(I,{type:"button",size:"sm",variant:"secondary",onClick:()=>W(a),children:"Erneut prüfen"}),g==="exists"&&i.jsxs("div",{className:"pt-3 mt-3 border-t border-blue-100",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Mailbox (IMAP/SMTP)"}),k?i.jsxs("span",{className:"text-xs text-green-600 flex items-center gap-1",children:[i.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z",clipRule:"evenodd"})}),"Mailbox aktiv"]}):i.jsx("span",{className:"text-xs text-orange-600",children:"Keine Mailbox"})]}),!k&&i.jsxs("div",{className:"mt-2",children:[i.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"Aktiviere eine echte Mailbox um E-Mails direkt im CRM zu empfangen und zu versenden."}),i.jsx(I,{type:"button",size:"sm",onClick:he,disabled:b,children:b?"Wird aktiviert...":"Mailbox aktivieren"})]}),k&&i.jsx("div",{className:"mt-3",children:T?S&&i.jsx(yR,{credentials:S,onHide:()=>w(!1),onResetPassword:mt,isResettingPassword:V}):i.jsx(I,{type:"button",size:"sm",variant:"secondary",onClick:et,disabled:F,children:F?"Laden...":i.jsxs(i.Fragment,{children:[i.jsx(Oe,{className:"w-4 h-4 mr-1"}),"Zugangsdaten anzeigen"]})})})]})]}):i.jsxs("div",{className:"space-y-3",children:[i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d,onChange:le=>{u(le.target.checked),le.target.checked||m(!1)},className:"mt-1 rounded border-gray-300"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Beim E-Mail-Provider anlegen"}),i.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Die E-Mail-Weiterleitung wird automatisch auf dem konfigurierten Server erstellt. Weiterleitungsziel: ",r]})]})]}),d&&i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer ml-6",children:[i.jsx("input",{type:"checkbox",checked:h,onChange:le=>m(le.target.checked),className:"mt-1 rounded border-gray-300"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Echte Mailbox erstellen (IMAP/SMTP-Zugang)"}),i.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Ermöglicht E-Mails direkt im CRM zu empfangen und zu versenden."})]})]})]})}),f&&i.jsx("div",{className:"bg-red-50 p-3 rounded-lg text-red-700 text-sm",children:f}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:wn||!a,children:wn?"Speichern...":"Speichern"})]})]})})}const vR={DATA_PROCESSING:{label:"Datenverarbeitung",description:"Grundlegende Verarbeitung personenbezogener Daten zur Vertragserfüllung"},MARKETING_EMAIL:{label:"E-Mail-Marketing",description:"Zusendung von Werbung und Angeboten per E-Mail"},MARKETING_PHONE:{label:"Telefonmarketing",description:"Kontaktaufnahme zu Werbezwecken per Telefon"},DATA_SHARING_PARTNER:{label:"Datenweitergabe",description:"Weitergabe von Daten an Partnerunternehmen"}};function bR({customerId:t,canEdit:e,customerEmail:n}){const s=ye(),{user:r}=nt(),[a,l]=N.useState(!1),[o,c]=N.useState(!1),{data:d,isLoading:u}=fe({queryKey:["customer-consents",t],queryFn:()=>Mr.getCustomerConsents(t)}),h=G({mutationFn:j=>Mr.sendConsentLink(t,j),onSuccess:(j,k)=>{var T;const E=(T=j.data)==null?void 0:T.url;if(E){if(k==="copy")navigator.clipboard.writeText(E),c(!0),setTimeout(()=>c(!1),2e3);else if(k==="email")alert("Consent-Link wurde per E-Mail gesendet.");else if(k==="whatsapp"){const w=encodeURIComponent(`Bitte stimmen Sie unserer Datenschutzerklärung zu: ${E}`);window.open(`https://wa.me/?text=${w}`,"_blank")}else if(k==="telegram"){const w=encodeURIComponent(`Bitte stimmen Sie unserer Datenschutzerklärung zu: ${E}`);window.open(`https://t.me/share/url?url=${encodeURIComponent(E)}&text=${w}`,"_blank")}else if(k==="signal"){const w=encodeURIComponent(`Bitte stimmen Sie unserer Datenschutzerklärung zu: ${E}`);window.open(`signal://send?text=${w}`,"_blank")}l(!1)}}}),m=G({mutationFn:({consentType:j,status:k,source:E})=>Mr.updateConsent(t,j,{status:k,source:E}),onSuccess:()=>{s.invalidateQueries({queryKey:["customer-consents",t]})}}),f=j=>{const k=j.status==="GRANTED"?"WITHDRAWN":"GRANTED";m.mutate({consentType:j.consentType,status:k,source:"crm-backend"})},p=j=>{switch(j){case"GRANTED":return i.jsx(SC,{className:"w-5 h-5 text-green-500"});case"WITHDRAWN":return i.jsx(CC,{className:"w-5 h-5 text-red-500"});case"PENDING":return i.jsx(hh,{className:"w-5 h-5 text-yellow-500"});default:return i.jsx(lr,{className:"w-5 h-5 text-gray-400"})}},g=j=>{switch(j){case"GRANTED":return i.jsx(je,{variant:"success",children:"Erteilt"});case"WITHDRAWN":return i.jsx(je,{variant:"danger",children:"Widerrufen"});case"PENDING":return i.jsx(je,{variant:"warning",children:"Ausstehend"});default:return i.jsx(je,{children:j})}},x=j=>j?new Date(j).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}):"-";if(u)return i.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."});const y=(d==null?void 0:d.data)||[],v=r,b=[{key:"email",label:"Per E-Mail",icon:"✉️",available:!!n},{key:"whatsapp",label:"Per WhatsApp",icon:"💬",available:!!(v!=null&&v.whatsappNumber)},{key:"telegram",label:"Per Telegram",icon:"📨",available:!!(v!=null&&v.telegramUsername)},{key:"signal",label:"Per Signal",icon:"📱",available:!!(v!=null&&v.signalNumber)},{key:"copy",label:"Link kopieren",icon:"🔗",available:!0}];return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(lr,{className:"w-5 h-5 text-gray-400"}),i.jsx("h3",{className:"font-medium",children:"DSGVO-Einwilligungen"})]}),i.jsxs("div",{className:"relative",children:[i.jsxs(I,{variant:"secondary",size:"sm",onClick:()=>l(!a),children:[i.jsx(Fs,{className:"w-4 h-4 mr-2"}),"Datenschutz senden",i.jsx(Us,{className:"w-3 h-3 ml-1"})]}),a&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>l(!1)}),i.jsxs("div",{className:"absolute right-0 mt-1 w-56 bg-white border rounded-lg shadow-lg z-20 py-1",children:[b.filter(j=>j.available).map(j=>i.jsxs("button",{className:"w-full text-left px-4 py-2 text-sm hover:bg-gray-50 flex items-center gap-2",onClick:()=>h.mutate(j.key),disabled:h.isPending,children:[i.jsx("span",{children:j.icon}),i.jsx("span",{children:j.label}),j.key==="copy"&&o&&i.jsx(Vr,{className:"w-4 h-4 text-green-500 ml-auto"})]},j.key)),b.filter(j=>j.available).length===1&&i.jsx("p",{className:"px-4 py-2 text-xs text-gray-400",children:"Weitere Kanäle in Benutzereinstellungen konfigurieren"})]})]})]})]}),i.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Einwilligungen können nur vom Kunden selbst erteilt oder widerrufen werden (Kundenportal oder Datenschutz-Link)."}),i.jsx("div",{className:"space-y-4",children:y.map(j=>{const k=vR[j.consentType]||{label:j.consentType,description:""};return i.jsx("div",{className:"border rounded-lg p-4",children:i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-start gap-3",children:[p(j.status),i.jsxs("div",{children:[i.jsx("h4",{className:"font-medium",children:k.label}),i.jsx("p",{className:"text-sm text-gray-500",children:k.description}),i.jsxs("div",{className:"mt-2 flex items-center gap-4 text-xs text-gray-500",children:[j.grantedAt&&i.jsxs("span",{children:["Erteilt am: ",x(j.grantedAt)]}),j.withdrawnAt&&i.jsxs("span",{children:["Widerrufen am: ",x(j.withdrawnAt)]}),j.source&&i.jsxs("span",{children:["Quelle: ",j.source]})]})]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[g(j.status),e&&i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:j.status==="GRANTED",onChange:()=>f(j),disabled:m.isPending,className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"})]})]})]})},j.consentType)})}),y.length===0&&i.jsx("p",{className:"text-gray-500 text-center py-4",children:"Keine Einwilligungen konfiguriert."})]})}var wd=t=>t.type==="checkbox",oa=t=>t instanceof Date,Bn=t=>t==null;const PC=t=>typeof t=="object";var $t=t=>!Bn(t)&&!Array.isArray(t)&&PC(t)&&!oa(t),jR=t=>$t(t)&&t.target?wd(t.target)?t.target.checked:t.target.value:t,NR=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,wR=(t,e)=>t.has(NR(e)),kR=t=>{const e=t.constructor&&t.constructor.prototype;return $t(e)&&e.hasOwnProperty("isPrototypeOf")},Vy=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Vt(t){if(t instanceof Date)return new Date(t);const e=typeof FileList<"u"&&t instanceof FileList;if(Vy&&(t instanceof Blob||e))return t;const n=Array.isArray(t);if(!n&&!($t(t)&&kR(t)))return t;const s=n?[]:Object.create(Object.getPrototypeOf(t));for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(s[r]=Vt(t[r]));return s}var Lf=t=>/^\w*$/.test(t),gt=t=>t===void 0,Ky=t=>Array.isArray(t)?t.filter(Boolean):[],Uy=t=>Ky(t.replace(/["|']|\]/g,"").split(/\.|\[/)),be=(t,e,n)=>{if(!e||!$t(t))return n;const s=(Lf(e)?[e]:Uy(e)).reduce((r,a)=>Bn(r)?r:r[a],t);return gt(s)||s===t?gt(t[e])?n:t[e]:s},Ys=t=>typeof t=="boolean",Rs=t=>typeof t=="function",dt=(t,e,n)=>{let s=-1;const r=Lf(e)?[e]:Uy(e),a=r.length,l=a-1;for(;++s{const r={defaultValues:e._defaultValues};for(const a in t)Object.defineProperty(r,a,{get:()=>{const l=a;return e._proxyFormState[l]!==Os.all&&(e._proxyFormState[l]=!s||Os.all),t[l]}});return r};const ER=typeof window<"u"?ut.useLayoutEffect:ut.useEffect;var ns=t=>typeof t=="string",AR=(t,e,n,s,r)=>ns(t)?(s&&e.watch.add(t),be(n,t,r)):Array.isArray(t)?t.map(a=>(s&&e.watch.add(a),be(n,a))):(s&&(e.watchAll=!0),n),Kg=t=>Bn(t)||!PC(t);function li(t,e,n=new WeakSet){if(Kg(t)||Kg(e))return Object.is(t,e);if(oa(t)&&oa(e))return Object.is(t.getTime(),e.getTime());const s=Object.keys(t),r=Object.keys(e);if(s.length!==r.length)return!1;if(n.has(t)||n.has(e))return!0;n.add(t),n.add(e);for(const a of s){const l=t[a];if(!r.includes(a))return!1;if(a!=="ref"){const o=e[a];if(oa(l)&&oa(o)||$t(l)&&$t(o)||Array.isArray(l)&&Array.isArray(o)?!li(l,o,n):!Object.is(l,o))return!1}}return!0}const DR=ut.createContext(null);DR.displayName="HookFormContext";var MR=(t,e,n,s,r)=>e?{...n[t],types:{...n[t]&&n[t].types?n[t].types:{},[s]:r||!0}}:{},rc=t=>Array.isArray(t)?t:[t],L1=()=>{let t=[];return{get observers(){return t},next:r=>{for(const a of t)a.next&&a.next(r)},subscribe:r=>(t.push(r),{unsubscribe:()=>{t=t.filter(a=>a!==r)}}),unsubscribe:()=>{t=[]}}};function IC(t,e){const n={};for(const s in t)if(t.hasOwnProperty(s)){const r=t[s],a=e[s];if(r&&$t(r)&&a){const l=IC(r,a);$t(l)&&(n[s]=l)}else t[s]&&(n[s]=a)}return n}var Cn=t=>$t(t)&&!Object.keys(t).length,qy=t=>t.type==="file",fh=t=>{if(!Vy)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},RC=t=>t.type==="select-multiple",Hy=t=>t.type==="radio",TR=t=>Hy(t)||wd(t),Fm=t=>fh(t)&&t.isConnected;function PR(t,e){const n=e.slice(0,-1).length;let s=0;for(;s{for(const e in t)if(Rs(t[e]))return!0;return!1};function OC(t){return Array.isArray(t)||$t(t)&&!RR(t)}function Ug(t,e={}){for(const n in t){const s=t[n];OC(s)?(e[n]=Array.isArray(s)?[]:{},Ug(s,e[n])):gt(s)||(e[n]=!0)}return e}function rl(t,e,n){n||(n=Ug(e));for(const s in t){const r=t[s];if(OC(r))gt(e)||Kg(n[s])?n[s]=Ug(r,Array.isArray(r)?[]:{}):rl(r,Bn(e)?{}:e[s],n[s]);else{const a=e[s];n[s]=!li(r,a)}}return n}const F1={value:!1,isValid:!1},z1={value:!0,isValid:!0};var LC=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!gt(t[0].attributes.value)?gt(t[0].value)||t[0].value===""?z1:{value:t[0].value,isValid:!0}:z1:F1}return F1},FC=(t,{valueAsNumber:e,valueAsDate:n,setValueAs:s})=>gt(t)?t:e?t===""?NaN:t&&+t:n&&ns(t)?new Date(t):s?s(t):t;const $1={isValid:!1,value:null};var zC=t=>Array.isArray(t)?t.reduce((e,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:e,$1):$1;function B1(t){const e=t.ref;return qy(e)?e.files:Hy(e)?zC(t.refs).value:RC(e)?[...e.selectedOptions].map(({value:n})=>n):wd(e)?LC(t.refs).value:FC(gt(e.value)?t.ref.value:e.value,t)}var OR=(t,e,n,s)=>{const r={};for(const a of t){const l=be(e,a);l&&dt(r,a,l._f)}return{criteriaMode:n,names:[...t],fields:r,shouldUseNativeValidation:s}},mh=t=>t instanceof RegExp,Io=t=>gt(t)?t:mh(t)?t.source:$t(t)?mh(t.value)?t.value.source:t.value:t,_1=t=>({isOnSubmit:!t||t===Os.onSubmit,isOnBlur:t===Os.onBlur,isOnChange:t===Os.onChange,isOnAll:t===Os.all,isOnTouch:t===Os.onTouched});const V1="AsyncFunction";var LR=t=>!!t&&!!t.validate&&!!(Rs(t.validate)&&t.validate.constructor.name===V1||$t(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===V1)),FR=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),K1=(t,e,n)=>!n&&(e.watchAll||e.watch.has(t)||[...e.watch].some(s=>t.startsWith(s)&&/^\.\w+/.test(t.slice(s.length))));const ic=(t,e,n,s)=>{for(const r of n||Object.keys(t)){const a=be(t,r);if(a){const{_f:l,...o}=a;if(l){if(l.refs&&l.refs[0]&&e(l.refs[0],r)&&!s)return!0;if(l.ref&&e(l.ref,l.name)&&!s)return!0;if(ic(o,e))break}else if($t(o)&&ic(o,e))break}}};function U1(t,e,n){const s=be(t,n);if(s||Lf(n))return{error:s,name:n};const r=n.split(".");for(;r.length;){const a=r.join("."),l=be(e,a),o=be(t,a);if(l&&!Array.isArray(l)&&n!==a)return{name:n};if(o&&o.type)return{name:a,error:o};if(o&&o.root&&o.root.type)return{name:`${a}.root`,error:o.root};r.pop()}return{name:n}}var zR=(t,e,n,s)=>{n(t);const{name:r,...a}=t;return Cn(a)||Object.keys(a).length>=Object.keys(e).length||Object.keys(a).find(l=>e[l]===(!s||Os.all))},$R=(t,e,n)=>!t||!e||t===e||rc(t).some(s=>s&&(n?s===e:s.startsWith(e)||e.startsWith(s))),BR=(t,e,n,s,r)=>r.isOnAll?!1:!n&&r.isOnTouch?!(e||t):(n?s.isOnBlur:r.isOnBlur)?!t:(n?s.isOnChange:r.isOnChange)?t:!0,_R=(t,e)=>!Ky(be(t,e)).length&&Lt(t,e),VR=(t,e,n)=>{const s=rc(be(t,n));return dt(s,"root",e[n]),dt(t,n,s),t};function q1(t,e,n="validate"){if(ns(t)||Array.isArray(t)&&t.every(ns)||Ys(t)&&!t)return{type:n,message:ns(t)?t:"",ref:e}}var el=t=>$t(t)&&!mh(t)?t:{value:t,message:""},H1=async(t,e,n,s,r,a)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:f,validate:p,name:g,valueAsNumber:x,mount:y}=t._f,v=be(n,g);if(!y||e.has(g))return{};const b=o?o[0]:l,j=R=>{r&&b.reportValidity&&(b.setCustomValidity(Ys(R)?"":R||""),b.reportValidity())},k={},E=Hy(l),T=wd(l),w=E||T,S=(x||qy(l))&>(l.value)&>(v)||fh(l)&&l.value===""||v===""||Array.isArray(v)&&!v.length,M=MR.bind(null,g,s,k),F=(R,V,D,z=mr.maxLength,C=mr.minLength)=>{const _=R?V:D;k[g]={type:R?z:C,message:_,ref:l,...M(R?z:C,_)}};if(a?!Array.isArray(v)||!v.length:c&&(!w&&(S||Bn(v))||Ys(v)&&!v||T&&!LC(o).isValid||E&&!zC(o).isValid)){const{value:R,message:V}=ns(c)?{value:!!c,message:c}:el(c);if(R&&(k[g]={type:mr.required,message:V,ref:b,...M(mr.required,V)},!s))return j(V),k}if(!S&&(!Bn(h)||!Bn(m))){let R,V;const D=el(m),z=el(h);if(!Bn(v)&&!isNaN(v)){const C=l.valueAsNumber||v&&+v;Bn(D.value)||(R=C>D.value),Bn(z.value)||(V=Cnew Date(new Date().toDateString()+" "+W),K=l.type=="time",B=l.type=="week";ns(D.value)&&v&&(R=K?_(v)>_(D.value):B?v>D.value:C>new Date(D.value)),ns(z.value)&&v&&(V=K?_(v)<_(z.value):B?v+R.value,z=!Bn(V.value)&&v.length<+V.value;if((D||z)&&(F(D,R.message,V.message),!s))return j(k[g].message),k}if(f&&!S&&ns(v)){const{value:R,message:V}=el(f);if(mh(R)&&!v.match(R)&&(k[g]={type:mr.pattern,message:V,ref:l,...M(mr.pattern,V)},!s))return j(V),k}if(p){if(Rs(p)){const R=await p(v,n),V=q1(R,b);if(V&&(k[g]={...V,...M(mr.validate,V.message)},!s))return j(V.message),k}else if($t(p)){let R={};for(const V in p){if(!Cn(R)&&!s)break;const D=q1(await p[V](v,n),b,V);D&&(R={...D,...M(V,D.message)},j(D.message),s&&(k[g]=R))}if(!Cn(R)&&(k[g]={ref:b,...R},!s))return k}}return j(!0),k};const KR={mode:Os.onSubmit,reValidateMode:Os.onChange,shouldFocusError:!0};function UR(t={}){let e={...KR,...t},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:Rs(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},s={},r=$t(e.defaultValues)||$t(e.values)?Vt(e.defaultValues||e.values)||{}:{},a=e.shouldUnregister?{}:Vt(r),l={action:!1,mount:!1,watch:!1,keepIsValid:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},h={...u};let m={...h};const f={array:L1(),state:L1()},p=e.criteriaMode===Os.all,g=L=>U=>{clearTimeout(d),d=setTimeout(L,U)},x=async L=>{if(!l.keepIsValid&&!e.disabled&&(h.isValid||m.isValid||L)){let U;e.resolver?(U=Cn((await w()).errors),y()):U=await M(s,!0),U!==n.isValid&&f.state.next({isValid:U})}},y=(L,U)=>{!e.disabled&&(h.isValidating||h.validatingFields||m.isValidating||m.validatingFields)&&((L||Array.from(o.mount)).forEach(Q=>{Q&&(U?dt(n.validatingFields,Q,U):Lt(n.validatingFields,Q))}),f.state.next({validatingFields:n.validatingFields,isValidating:!Cn(n.validatingFields)}))},v=(L,U=[],Q,ue,ie=!0,se=!0)=>{if(ue&&Q&&!e.disabled){if(l.action=!0,se&&Array.isArray(be(s,L))){const Ne=Q(be(s,L),ue.argA,ue.argB);ie&&dt(s,L,Ne)}if(se&&Array.isArray(be(n.errors,L))){const Ne=Q(be(n.errors,L),ue.argA,ue.argB);ie&&dt(n.errors,L,Ne),_R(n.errors,L)}if((h.touchedFields||m.touchedFields)&&se&&Array.isArray(be(n.touchedFields,L))){const Ne=Q(be(n.touchedFields,L),ue.argA,ue.argB);ie&&dt(n.touchedFields,L,Ne)}(h.dirtyFields||m.dirtyFields)&&(n.dirtyFields=rl(r,a)),f.state.next({name:L,isDirty:R(L,U),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else dt(a,L,U)},b=(L,U)=>{dt(n.errors,L,U),f.state.next({errors:n.errors})},j=L=>{n.errors=L,f.state.next({errors:n.errors,isValid:!1})},k=(L,U,Q,ue)=>{const ie=be(s,L);if(ie){const se=be(a,L,gt(Q)?be(r,L):Q);gt(se)||ue&&ue.defaultChecked||U?dt(a,L,U?se:B1(ie._f)):z(L,se),l.mount&&!l.action&&x()}},E=(L,U,Q,ue,ie)=>{let se=!1,Ne=!1;const qe={name:L};if(!e.disabled){if(!Q||ue){(h.isDirty||m.isDirty)&&(Ne=n.isDirty,n.isDirty=qe.isDirty=R(),se=Ne!==qe.isDirty);const _e=li(be(r,L),U);Ne=!!be(n.dirtyFields,L),_e?Lt(n.dirtyFields,L):dt(n.dirtyFields,L,!0),qe.dirtyFields=n.dirtyFields,se=se||(h.dirtyFields||m.dirtyFields)&&Ne!==!_e}if(Q){const _e=be(n.touchedFields,L);_e||(dt(n.touchedFields,L,Q),qe.touchedFields=n.touchedFields,se=se||(h.touchedFields||m.touchedFields)&&_e!==Q)}se&&ie&&f.state.next(qe)}return se?qe:{}},T=(L,U,Q,ue)=>{const ie=be(n.errors,L),se=(h.isValid||m.isValid)&&Ys(U)&&n.isValid!==U;if(e.delayError&&Q?(c=g(()=>b(L,Q)),c(e.delayError)):(clearTimeout(d),c=null,Q?dt(n.errors,L,Q):Lt(n.errors,L)),(Q?!li(ie,Q):ie)||!Cn(ue)||se){const Ne={...ue,...se&&Ys(U)?{isValid:U}:{},errors:n.errors,name:L};n={...n,...Ne},f.state.next(Ne)}},w=async L=>(y(L,!0),await e.resolver(a,e.context,OR(L||o.mount,s,e.criteriaMode,e.shouldUseNativeValidation))),S=async L=>{const{errors:U}=await w(L);if(y(L),L)for(const Q of L){const ue=be(U,Q);ue?dt(n.errors,Q,ue):Lt(n.errors,Q)}else n.errors=U;return U},M=async(L,U,Q={valid:!0})=>{for(const ue in L){const ie=L[ue];if(ie){const{_f:se,...Ne}=ie;if(se){const qe=o.array.has(se.name),_e=ie._f&&LR(ie._f);_e&&h.validatingFields&&y([se.name],!0);const Wt=await H1(ie,o.disabled,a,p,e.shouldUseNativeValidation&&!U,qe);if(_e&&h.validatingFields&&y([se.name]),Wt[se.name]&&(Q.valid=!1,U||t.shouldUseNativeValidation))break;!U&&(be(Wt,se.name)?qe?VR(n.errors,Wt,se.name):dt(n.errors,se.name,Wt[se.name]):Lt(n.errors,se.name))}!Cn(Ne)&&await M(Ne,U,Q)}}return Q.valid},F=()=>{for(const L of o.unMount){const U=be(s,L);U&&(U._f.refs?U._f.refs.every(Q=>!Fm(Q)):!Fm(U._f.ref))&&On(L)}o.unMount=new Set},R=(L,U)=>!e.disabled&&(L&&U&&dt(a,L,U),!li(ce(),r)),V=(L,U,Q)=>AR(L,o,{...l.mount?a:gt(U)?r:ns(L)?{[L]:U}:U},Q,U),D=L=>Ky(be(l.mount?a:r,L,e.shouldUnregister?be(r,L,[]):[])),z=(L,U,Q={})=>{const ue=be(s,L);let ie=U;if(ue){const se=ue._f;se&&(!se.disabled&&dt(a,L,FC(U,se)),ie=fh(se.ref)&&Bn(U)?"":U,RC(se.ref)?[...se.ref.options].forEach(Ne=>Ne.selected=ie.includes(Ne.value)):se.refs?wd(se.ref)?se.refs.forEach(Ne=>{(!Ne.defaultChecked||!Ne.disabled)&&(Array.isArray(ie)?Ne.checked=!!ie.find(qe=>qe===Ne.value):Ne.checked=ie===Ne.value||!!ie)}):se.refs.forEach(Ne=>Ne.checked=Ne.value===ie):qy(se.ref)?se.ref.value="":(se.ref.value=ie,se.ref.type||f.state.next({name:L,values:Vt(a)})))}(Q.shouldDirty||Q.shouldTouch)&&E(L,ie,Q.shouldTouch,Q.shouldDirty,!0),Q.shouldValidate&&W(L)},C=(L,U,Q)=>{for(const ue in U){if(!U.hasOwnProperty(ue))return;const ie=U[ue],se=L+"."+ue,Ne=be(s,se);(o.array.has(L)||$t(ie)||Ne&&!Ne._f)&&!oa(ie)?C(se,ie,Q):z(se,ie,Q)}},_=(L,U,Q={})=>{const ue=be(s,L),ie=o.array.has(L),se=Vt(U);dt(a,L,se),ie?(f.array.next({name:L,values:Vt(a)}),(h.isDirty||h.dirtyFields||m.isDirty||m.dirtyFields)&&Q.shouldDirty&&f.state.next({name:L,dirtyFields:rl(r,a),isDirty:R(L,se)})):ue&&!ue._f&&!Bn(se)?C(L,se,Q):z(L,se,Q),K1(L,o)?f.state.next({...n,name:L,values:Vt(a)}):f.state.next({name:l.mount?L:void 0,values:Vt(a)})},K=async L=>{l.mount=!0;const U=L.target;let Q=U.name,ue=!0;const ie=be(s,Q),se=_e=>{ue=Number.isNaN(_e)||oa(_e)&&isNaN(_e.getTime())||li(_e,be(a,Q,_e))},Ne=_1(e.mode),qe=_1(e.reValidateMode);if(ie){let _e,Wt;const hr=U.type?B1(ie._f):jR(L),qs=L.type===O1.BLUR||L.type===O1.FOCUS_OUT,Wr=!FR(ie._f)&&!e.resolver&&!be(n.errors,Q)&&!ie._f.deps||BR(qs,be(n.touchedFields,Q),n.isSubmitted,qe,Ne),bo=K1(Q,o,qs);dt(a,Q,hr),qs?(!U||!U.readOnly)&&(ie._f.onBlur&&ie._f.onBlur(L),c&&c(0)):ie._f.onChange&&ie._f.onChange(L);const Ya=E(Q,hr,qs),Xf=!Cn(Ya)||bo;if(!qs&&f.state.next({name:Q,type:L.type,values:Vt(a)}),Wr)return(h.isValid||m.isValid)&&(e.mode==="onBlur"?qs&&x():qs||x()),Xf&&f.state.next({name:Q,...bo?{}:Ya});if(!qs&&bo&&f.state.next({...n}),e.resolver){const{errors:jo}=await w([Q]);if(y([Q]),se(hr),ue){const Ad=U1(n.errors,s,Q),No=U1(jo,s,Ad.name||Q);_e=No.error,Q=No.name,Wt=Cn(jo)}}else y([Q],!0),_e=(await H1(ie,o.disabled,a,p,e.shouldUseNativeValidation))[Q],y([Q]),se(hr),ue&&(_e?Wt=!1:(h.isValid||m.isValid)&&(Wt=await M(s,!0)));ue&&(ie._f.deps&&(!Array.isArray(ie._f.deps)||ie._f.deps.length>0)&&W(ie._f.deps),T(Q,Wt,_e,Ya))}},B=(L,U)=>{if(be(n.errors,U)&&L.focus)return L.focus(),1},W=async(L,U={})=>{let Q,ue;const ie=rc(L);if(e.resolver){const se=await S(gt(L)?L:ie);Q=Cn(se),ue=L?!ie.some(Ne=>be(se,Ne)):Q}else L?(ue=(await Promise.all(ie.map(async se=>{const Ne=be(s,se);return await M(Ne&&Ne._f?{[se]:Ne}:Ne)}))).every(Boolean),!(!ue&&!n.isValid)&&x()):ue=Q=await M(s);return f.state.next({...!ns(L)||(h.isValid||m.isValid)&&Q!==n.isValid?{}:{name:L},...e.resolver||!L?{isValid:Q}:{},errors:n.errors}),U.shouldFocus&&!ue&&ic(s,B,L?ie:o.mount),ue},ce=(L,U)=>{let Q={...l.mount?a:r};return U&&(Q=IC(U.dirtyFields?n.dirtyFields:n.touchedFields,Q)),gt(L)?Q:ns(L)?be(Q,L):L.map(ue=>be(Q,ue))},he=(L,U)=>({invalid:!!be((U||n).errors,L),isDirty:!!be((U||n).dirtyFields,L),error:be((U||n).errors,L),isValidating:!!be(n.validatingFields,L),isTouched:!!be((U||n).touchedFields,L)}),Je=L=>{L&&rc(L).forEach(U=>Lt(n.errors,U)),f.state.next({errors:L?n.errors:{}})},et=(L,U,Q)=>{const ue=(be(s,L,{_f:{}})._f||{}).ref,ie=be(n.errors,L)||{},{ref:se,message:Ne,type:qe,..._e}=ie;dt(n.errors,L,{..._e,...U,ref:ue}),f.state.next({name:L,errors:n.errors,isValid:!1}),Q&&Q.shouldFocus&&ue&&ue.focus&&ue.focus()},mt=(L,U)=>Rs(L)?f.state.subscribe({next:Q=>"values"in Q&&L(V(void 0,U),Q)}):V(L,U,!0),A=L=>f.state.subscribe({next:U=>{$R(L.name,U.name,L.exact)&&zR(U,L.formState||h,Ln,L.reRenderRoot)&&L.callback({values:{...a},...n,...U,defaultValues:r})}}).unsubscribe,pt=L=>(l.mount=!0,m={...m,...L.formState},A({...L,formState:{...u,...L.formState}})),On=(L,U={})=>{for(const Q of L?rc(L):o.mount)o.mount.delete(Q),o.array.delete(Q),U.keepValue||(Lt(s,Q),Lt(a,Q)),!U.keepError&&Lt(n.errors,Q),!U.keepDirty&&Lt(n.dirtyFields,Q),!U.keepTouched&&Lt(n.touchedFields,Q),!U.keepIsValidating&&Lt(n.validatingFields,Q),!e.shouldUnregister&&!U.keepDefaultValue&&Lt(r,Q);f.state.next({values:Vt(a)}),f.state.next({...n,...U.keepDirty?{isDirty:R()}:{}}),!U.keepIsValid&&x()},wn=({disabled:L,name:U})=>{if(Ys(L)&&l.mount||L||o.disabled.has(U)){const ie=o.disabled.has(U)!==!!L;L?o.disabled.add(U):o.disabled.delete(U),ie&&l.mount&&!l.action&&x()}},le=(L,U={})=>{let Q=be(s,L);const ue=Ys(U.disabled)||Ys(e.disabled);return dt(s,L,{...Q||{},_f:{...Q&&Q._f?Q._f:{ref:{name:L}},name:L,mount:!0,...U}}),o.mount.add(L),Q?wn({disabled:Ys(U.disabled)?U.disabled:e.disabled,name:L}):k(L,!0,U.value),{...ue?{disabled:U.disabled||e.disabled}:{},...e.progressive?{required:!!U.required,min:Io(U.min),max:Io(U.max),minLength:Io(U.minLength),maxLength:Io(U.maxLength),pattern:Io(U.pattern)}:{},name:L,onChange:K,onBlur:K,ref:ie=>{if(ie){le(L,U),Q=be(s,L);const se=gt(ie.value)&&ie.querySelectorAll&&ie.querySelectorAll("input,select,textarea")[0]||ie,Ne=TR(se),qe=Q._f.refs||[];if(Ne?qe.find(_e=>_e===se):se===Q._f.ref)return;dt(s,L,{_f:{...Q._f,...Ne?{refs:[...qe.filter(Fm),se,...Array.isArray(be(r,L))?[{}]:[]],ref:{type:se.type,name:L}}:{ref:se}}}),k(L,!1,void 0,se)}else Q=be(s,L,{}),Q._f&&(Q._f.mount=!1),(e.shouldUnregister||U.shouldUnregister)&&!(wR(o.array,L)&&l.action)&&o.unMount.add(L)}}},it=()=>e.shouldFocusError&&ic(s,B,o.mount),Rt=L=>{Ys(L)&&(f.state.next({disabled:L}),ic(s,(U,Q)=>{const ue=be(s,Q);ue&&(U.disabled=ue._f.disabled||L,Array.isArray(ue._f.refs)&&ue._f.refs.forEach(ie=>{ie.disabled=ue._f.disabled||L}))},0,!1))},J=(L,U)=>async Q=>{let ue;Q&&(Q.preventDefault&&Q.preventDefault(),Q.persist&&Q.persist());let ie=Vt(a);if(f.state.next({isSubmitting:!0}),e.resolver){const{errors:se,values:Ne}=await w();y(),n.errors=se,ie=Vt(Ne)}else await M(s);if(o.disabled.size)for(const se of o.disabled)Lt(ie,se);if(Lt(n.errors,"root"),Cn(n.errors)){f.state.next({errors:{}});try{await L(ie,Q)}catch(se){ue=se}}else U&&await U({...n.errors},Q),it(),setTimeout(it);if(f.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Cn(n.errors)&&!ue,submitCount:n.submitCount+1,errors:n.errors}),ue)throw ue},Ke=(L,U={})=>{be(s,L)&&(gt(U.defaultValue)?_(L,Vt(be(r,L))):(_(L,U.defaultValue),dt(r,L,Vt(U.defaultValue))),U.keepTouched||Lt(n.touchedFields,L),U.keepDirty||(Lt(n.dirtyFields,L),n.isDirty=U.defaultValue?R(L,Vt(be(r,L))):R()),U.keepError||(Lt(n.errors,L),h.isValid&&x()),f.state.next({...n}))},ct=(L,U={})=>{const Q=L?Vt(L):r,ue=Vt(Q),ie=Cn(L),se=ie?r:ue;if(U.keepDefaultValues||(r=Q),!U.keepValues){if(U.keepDirtyValues){const Ne=new Set([...o.mount,...Object.keys(rl(r,a))]);for(const qe of Array.from(Ne)){const _e=be(n.dirtyFields,qe),Wt=be(a,qe),hr=be(se,qe);_e&&!gt(Wt)?dt(se,qe,Wt):!_e&&!gt(hr)&&_(qe,hr)}}else{if(Vy&>(L))for(const Ne of o.mount){const qe=be(s,Ne);if(qe&&qe._f){const _e=Array.isArray(qe._f.refs)?qe._f.refs[0]:qe._f.ref;if(fh(_e)){const Wt=_e.closest("form");if(Wt){Wt.reset();break}}}}if(U.keepFieldsRef)for(const Ne of o.mount)_(Ne,be(se,Ne));else s={}}a=e.shouldUnregister?U.keepDefaultValues?Vt(r):{}:Vt(se),f.array.next({values:{...se}}),f.state.next({values:{...se}})}o={mount:U.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!U.keepIsValid||!!U.keepDirtyValues||!e.shouldUnregister&&!Cn(se),l.watch=!!e.shouldUnregister,l.keepIsValid=!!U.keepIsValid,l.action=!1,U.keepErrors||(n.errors={}),f.state.next({submitCount:U.keepSubmitCount?n.submitCount:0,isDirty:ie?!1:U.keepDirty?n.isDirty:!!(U.keepDefaultValues&&!li(L,r)),isSubmitted:U.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:ie?{}:U.keepDirtyValues?U.keepDefaultValues&&a?rl(r,a):n.dirtyFields:U.keepDefaultValues&&L?rl(r,L):U.keepDirty?n.dirtyFields:{},touchedFields:U.keepTouched?n.touchedFields:{},errors:U.keepErrors?n.errors:{},isSubmitSuccessful:U.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:r})},ee=(L,U)=>ct(Rs(L)?L(a):L,{...e.resetOptions,...U}),pe=(L,U={})=>{const Q=be(s,L),ue=Q&&Q._f;if(ue){const ie=ue.refs?ue.refs[0]:ue.ref;ie.focus&&setTimeout(()=>{ie.focus(),U.shouldSelect&&Rs(ie.select)&&ie.select()})}},Ln=L=>{n={...n,...L}},Ot={control:{register:le,unregister:On,getFieldState:he,handleSubmit:J,setError:et,_subscribe:A,_runSchema:w,_updateIsValidating:y,_focusError:it,_getWatch:V,_getDirty:R,_setValid:x,_setFieldArray:v,_setDisabledField:wn,_setErrors:j,_getFieldArray:D,_reset:ct,_resetDefaultValues:()=>Rs(e.defaultValues)&&e.defaultValues().then(L=>{ee(L,e.resetOptions),f.state.next({isLoading:!1})}),_removeUnmounted:F,_disableForm:Rt,_subjects:f,_proxyFormState:h,get _fields(){return s},get _formValues(){return a},get _state(){return l},set _state(L){l=L},get _defaultValues(){return r},get _names(){return o},set _names(L){o=L},get _formState(){return n},get _options(){return e},set _options(L){e={...e,...L}}},subscribe:pt,trigger:W,register:le,handleSubmit:J,watch:mt,setValue:_,getValues:ce,reset:ee,resetField:Ke,clearErrors:Je,unregister:On,setError:et,setFocus:pe,getFieldState:he};return{...Ot,formControl:Ot}}function $C(t={}){const e=ut.useRef(void 0),n=ut.useRef(void 0),[s,r]=ut.useState({isDirty:!1,isValidating:!1,isLoading:Rs(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:Rs(t.defaultValues)?void 0:t.defaultValues});if(!e.current)if(t.formControl)e.current={...t.formControl,formState:s},t.defaultValues&&!Rs(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:l,...o}=UR(t);e.current={...o,formState:s}}const a=e.current.control;return a._options=t,ER(()=>{const l=a._subscribe({formState:a._proxyFormState,callback:()=>r({...a._formState}),reRenderRoot:!0});return r(o=>({...o,isReady:!0})),a._formState.isReady=!0,l},[a]),ut.useEffect(()=>a._disableForm(t.disabled),[a,t.disabled]),ut.useEffect(()=>{t.mode&&(a._options.mode=t.mode),t.reValidateMode&&(a._options.reValidateMode=t.reValidateMode)},[a,t.mode,t.reValidateMode]),ut.useEffect(()=>{t.errors&&(a._setErrors(t.errors),a._focusError())},[a,t.errors]),ut.useEffect(()=>{t.shouldUnregister&&a._subjects.state.next({values:a._getWatch()})},[a,t.shouldUnregister]),ut.useEffect(()=>{if(a._proxyFormState.isDirty){const l=a._getDirty();l!==s.isDirty&&a._subjects.state.next({isDirty:l})}},[a,s.isDirty]),ut.useEffect(()=>{var l;t.values&&!li(t.values,n.current)?(a._reset(t.values,{keepFieldsRef:!0,...a._options.resetOptions}),!((l=a._options.resetOptions)===null||l===void 0)&&l.keepIsValid||a._setValid(),n.current=t.values,r(o=>({...o}))):a._resetDefaultValues()},[a,t.values]),ut.useEffect(()=>{a._state.mount||(a._setValid(),a._state.mount=!0),a._state.watch&&(a._state.watch=!1,a._subjects.state.next({...a._formState})),a._removeUnmounted()}),e.current.formState=ut.useMemo(()=>CR(s,a),[a,s]),e.current}function W1(){var y,v;const{id:t}=md(),e=fn(),n=ye(),s=!!t,{register:r,handleSubmit:a,reset:l,watch:o,setValue:c,formState:{errors:d}}=$C(),u=o("type"),{data:h}=fe({queryKey:["customer",t],queryFn:()=>Zt.getById(parseInt(t)),enabled:s});N.useEffect(()=>{if(h!=null&&h.data){const b={...h.data};b.birthDate&&(b.birthDate=b.birthDate.split("T")[0]),b.foundingDate&&(b.foundingDate=b.foundingDate.split("T")[0]),l(b)}},[h,l]);const m=G({mutationFn:Zt.create,onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),e("/customers")}}),f=G({mutationFn:b=>Zt.update(parseInt(t),b),onSuccess:()=>{n.invalidateQueries({queryKey:["customers"]}),n.invalidateQueries({queryKey:["customer",t]}),e(`/customers/${t}`)}}),p=b=>{const j={type:b.type,salutation:b.salutation||void 0,firstName:b.firstName,lastName:b.lastName,companyName:b.companyName||void 0,email:b.email||void 0,phone:b.phone||void 0,mobile:b.mobile||void 0,taxNumber:b.taxNumber||void 0,commercialRegisterNumber:b.commercialRegisterNumber||void 0,notes:b.notes||void 0,birthPlace:b.birthPlace||void 0};b.birthDate&&typeof b.birthDate=="string"&&b.birthDate.trim()!==""?j.birthDate=new Date(b.birthDate).toISOString():j.birthDate=null,b.foundingDate&&typeof b.foundingDate=="string"&&b.foundingDate.trim()!==""?j.foundingDate=new Date(b.foundingDate).toISOString():j.foundingDate=null,s?f.mutate(j):m.mutate(j)},g=m.isPending||f.isPending,x=m.error||f.error;return i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold mb-6",children:s?"Kunde bearbeiten":"Neuer Kunde"}),x&&i.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:x instanceof Error?x.message:"Ein Fehler ist aufgetreten"}),i.jsxs("form",{onSubmit:a(p),children:[i.jsx(Z,{className:"mb-6",title:"Stammdaten",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(Fe,{label:"Kundentyp",...r("type"),options:[{value:"PRIVATE",label:"Privatkunde"},{value:"BUSINESS",label:"Geschäftskunde"}]}),i.jsx(Fe,{label:"Anrede",...r("salutation"),options:[{value:"Herr",label:"Herr"},{value:"Frau",label:"Frau"},{value:"Divers",label:"Divers"}]}),i.jsx(q,{label:"Vorname",...r("firstName",{required:"Vorname erforderlich"}),error:(y=d.firstName)==null?void 0:y.message}),i.jsx(q,{label:"Nachname",...r("lastName",{required:"Nachname erforderlich"}),error:(v=d.lastName)==null?void 0:v.message}),u==="BUSINESS"&&i.jsxs(i.Fragment,{children:[i.jsx(q,{label:"Firmenname",...r("companyName"),className:"md:col-span-2"}),i.jsx(q,{label:"Gründungsdatum",type:"date",...r("foundingDate"),value:o("foundingDate")||"",onClear:()=>c("foundingDate","")})]}),u!=="BUSINESS"&&i.jsxs(i.Fragment,{children:[i.jsx(q,{label:"Geburtsdatum",type:"date",...r("birthDate"),value:o("birthDate")||"",onClear:()=>c("birthDate","")}),i.jsx(q,{label:"Geburtsort",...r("birthPlace")})]})]})}),i.jsx(Z,{className:"mb-6",title:"Kontaktdaten",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(q,{label:"E-Mail",type:"email",...r("email")}),i.jsx(q,{label:"Telefon",...r("phone")}),i.jsx(q,{label:"Mobil",...r("mobile")})]})}),u==="BUSINESS"&&i.jsxs(Z,{className:"mb-6",title:"Geschäftsdaten",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(q,{label:"Steuernummer",...r("taxNumber")}),i.jsx(q,{label:"Handelsregisternummer",...r("commercialRegisterNumber"),placeholder:"z.B. HRB 12345"})]}),s&&i.jsx("p",{className:"mt-4 text-sm text-gray-500",children:"Dokumente (Gewerbeanmeldung, Handelsregisterauszug) können nach dem Speichern in der Kundendetailansicht hochgeladen werden."})]}),i.jsx(Z,{className:"mb-6",title:"Notizen",children:i.jsx("textarea",{...r("notes"),rows:4,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"Interne Notizen..."})}),i.jsxs("div",{className:"flex justify-end gap-4",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:()=>e(-1),children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:g,children:g?"Speichern...":"Speichern"})]})]})]})}const zm={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},$m={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},Q1={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},qR=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function HR({isOpen:t,onClose:e}){return t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:e}),i.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),i.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-600",children:i.jsx(nn,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"space-y-2",children:qR.map(({status:n,label:s,description:r,color:a})=>i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:`font-medium text-sm min-w-[90px] ${a}`,children:s}),i.jsx("span",{className:"text-sm text-gray-600",children:r})]},n))})]})]}):null}function WR(){const[t,e]=Sf(),n=fn(),[s,r]=N.useState(t.get("search")||""),[a,l]=N.useState(t.get("type")||""),[o,c]=N.useState(t.get("status")||""),[d,u]=N.useState(parseInt(t.get("page")||"1",10)),[h,m]=N.useState(new Set),[f,p]=N.useState(!1),{hasPermission:g,isCustomer:x,isCustomerPortal:y,user:v}=nt(),b=ye();N.useEffect(()=>{const D=new URLSearchParams;s&&D.set("search",s),a&&D.set("type",a),o&&D.set("status",o),d>1&&D.set("page",d.toString()),e(D,{replace:!0})},[s,a,o,d,e]);const j=G({mutationFn:He.delete,onSuccess:()=>{b.invalidateQueries({queryKey:["contracts"]})}}),{data:k,isLoading:E}=fe({queryKey:["contracts",s,a,o,d,x?v==null?void 0:v.customerId:null],queryFn:()=>He.getAll({search:s||void 0,type:a||void 0,status:o||void 0,page:d,limit:20,customerId:x?v==null?void 0:v.customerId:void 0})}),T=N.useMemo(()=>{if(!y||!(k!=null&&k.data))return[];const D=new Set;return v!=null&&v.customerId&&D.add(v.customerId),k.data.forEach(z=>D.add(z.customerId)),[...D]},[k==null?void 0:k.data,y,v==null?void 0:v.customerId]),w=BT({queries:T.map(D=>({queryKey:["contract-tree",D],queryFn:()=>He.getTreeForCustomer(D),enabled:y}))}),S=N.useMemo(()=>{const D=new Map;return T.forEach((z,C)=>{var K;const _=w[C];(K=_==null?void 0:_.data)!=null&&K.data&&D.set(z,_.data.data)}),D},[T,w]),M=N.useMemo(()=>{if(!y||!(k!=null&&k.data))return null;const D={};for(const z of k.data){const C=z.customerId;if(!D[C]){const _=z.customer?z.customer.companyName||`${z.customer.firstName} ${z.customer.lastName}`:`Kunde ${C}`;D[C]={customerId:C,customerName:_,isOwn:C===(v==null?void 0:v.customerId),contracts:[],tree:S.get(C)||[]}}D[C].contracts.push(z)}return Object.values(D).sort((z,C)=>z.isOwn&&!C.isOwn?-1:!z.isOwn&&C.isOwn?1:z.customerName.localeCompare(C.customerName))},[k==null?void 0:k.data,y,v==null?void 0:v.customerId,S]),F=D=>{m(z=>{const C=new Set(z);return C.has(D)?C.delete(D):C.add(D),C})},R=(D,z)=>D.map(C=>i.jsx("div",{children:V(C,z)},C.contract.id)),V=(D,z=0)=>{var ce,he,Je,et,mt,A,pt;const{contract:C,predecessors:_,hasHistory:K}=D,B=h.has(C.id),W=z>0;return i.jsxs("div",{children:[i.jsxs("div",{className:` + border rounded-lg p-4 transition-colors + ${W?"ml-6 border-l-4 border-l-gray-300 bg-gray-50":"hover:bg-gray-50"} + `,children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[!W&&K?i.jsx("button",{onClick:()=>F(C.id),className:"p-1 hover:bg-gray-200 rounded transition-colors",title:B?"Einklappen":"Vorgänger anzeigen",children:B?i.jsx(Us,{className:"w-4 h-4 text-gray-500"}):i.jsx(At,{className:"w-4 h-4 text-gray-500"})}):W?null:i.jsx("div",{className:"w-6"}),i.jsxs("span",{className:"font-mono flex items-center gap-1",children:[C.contractNumber,i.jsx(de,{value:C.contractNumber})]}),i.jsx(je,{children:zm[C.type]||C.type}),i.jsx(je,{variant:Q1[C.status]||"default",children:$m[C.status]||C.status}),W&&i.jsx("span",{className:"text-xs text-gray-500 ml-2",children:"(Vorgänger)"})]}),i.jsx("div",{className:"flex gap-2",children:i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${C.id}`,{state:{from:"contracts"}}),title:"Ansehen",children:i.jsx(Oe,{className:"w-4 h-4"})})})]}),(C.providerName||((ce=C.provider)==null?void 0:ce.name))&&i.jsxs("p",{className:`flex items-center gap-1 ${W?"ml-6":""}`,children:[C.providerName||((he=C.provider)==null?void 0:he.name),(C.tariffName||((Je=C.tariff)==null?void 0:Je.name))&&` - ${C.tariffName||((et=C.tariff)==null?void 0:et.name)}`,i.jsx(de,{value:(C.providerName||((mt=C.provider)==null?void 0:mt.name)||"")+(C.tariffName||(A=C.tariff)!=null&&A.name?` - ${C.tariffName||((pt=C.tariff)==null?void 0:pt.name)}`:"")})]}),C.startDate&&i.jsxs("p",{className:`text-sm text-gray-500 ${W?"ml-6":""}`,children:["Beginn: ",new Date(C.startDate).toLocaleDateString("de-DE"),C.endDate&&` | Ende: ${new Date(C.endDate).toLocaleDateString("de-DE")}`]})]}),(z===0&&B||z>0)&&_.length>0&&i.jsx("div",{className:"mt-2",children:R(_,z+1)})]},C.id)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold",children:"Verträge"}),g("contracts:create")&&!x&&i.jsx(Me,{to:"/contracts/new",children:i.jsxs(I,{children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neuer Vertrag"]})})]}),i.jsx(Z,{className:"mb-6",children:i.jsxs("div",{className:"flex gap-4 flex-wrap",children:[i.jsx("div",{className:"flex-1 min-w-[200px]",children:i.jsx(q,{placeholder:"Suchen...",value:s,onChange:D=>r(D.target.value)})}),i.jsx(Fe,{value:a,onChange:D=>l(D.target.value),options:Object.entries(zm).map(([D,z])=>({value:D,label:z})),className:"w-48"}),i.jsx(Fe,{value:o,onChange:D=>c(D.target.value),options:Object.entries($m).map(([D,z])=>({value:D,label:z})),className:"w-48"}),i.jsx(I,{variant:"secondary",children:i.jsx(jd,{className:"w-4 h-4"})})]})}),E?i.jsx(Z,{children:i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."})}):k!=null&&k.data&&k.data.length>0?i.jsx(i.Fragment,{children:y&&M?i.jsx("div",{className:"space-y-6",children:M.map(D=>i.jsxs(Z,{children:[i.jsx("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:D.isOwn?i.jsxs(i.Fragment,{children:[i.jsx(yo,{className:"w-5 h-5 text-blue-600"}),i.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"Meine Verträge"}),i.jsx(je,{variant:"default",children:D.contracts.length})]}):i.jsxs(i.Fragment,{children:[i.jsx(Ca,{className:"w-5 h-5 text-purple-600"}),i.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:["Verträge von ",D.customerName]}),i.jsx(je,{variant:"default",children:D.contracts.length})]})}),D.tree.length>0?i.jsx("div",{className:"space-y-4",children:D.tree.map(z=>V(z,0))}):i.jsx("p",{className:"text-gray-500",children:"Keine Verträge vorhanden."})]},D.isOwn?"own":D.customerName))}):i.jsxs(Z,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Vertragsnr."}),!x&&i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kunde"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Typ"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Anbieter / Tarif"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:i.jsxs("span",{className:"flex items-center gap-1",children:["Status",i.jsx("button",{onClick:()=>p(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:i.jsx(bd,{className:"w-4 h-4"})})]})}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beginn"}),i.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),i.jsx("tbody",{children:k.data.map(D=>i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsx("td",{className:"py-3 px-4 font-mono text-sm",children:D.contractNumber}),!x&&i.jsx("td",{className:"py-3 px-4",children:D.customer&&i.jsx(Me,{to:`/customers/${D.customer.id}`,className:"text-blue-600 hover:underline",children:D.customer.companyName||`${D.customer.firstName} ${D.customer.lastName}`})}),i.jsx("td",{className:"py-3 px-4",children:i.jsx(je,{children:zm[D.type]})}),i.jsxs("td",{className:"py-3 px-4",children:[D.providerName||"-",D.tariffName&&i.jsxs("span",{className:"text-gray-500",children:[" / ",D.tariffName]})]}),i.jsx("td",{className:"py-3 px-4",children:i.jsx(je,{variant:Q1[D.status],children:$m[D.status]})}),i.jsx("td",{className:"py-3 px-4",children:D.startDate?new Date(D.startDate).toLocaleDateString("de-DE"):"-"}),i.jsx("td",{className:"py-3 px-4 text-right",children:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>n(`/contracts/${D.id}`,{state:{from:"contracts"}}),children:i.jsx(Oe,{className:"w-4 h-4"})}),g("contracts:update")&&!x&&i.jsx(Me,{to:`/contracts/${D.id}/edit`,children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(rt,{className:"w-4 h-4"})})}),g("contracts:delete")&&!x&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertrag wirklich löschen?")&&j.mutate(D.id)},children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})})]},D.id))})]})}),k.pagination&&k.pagination.totalPages>1&&i.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[i.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",k.pagination.page," von ",k.pagination.totalPages," (",k.pagination.total," Einträge)"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>u(D=>Math.max(1,D-1)),disabled:d===1,children:"Zurück"}),i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>u(D=>D+1),disabled:d>=k.pagination.totalPages,children:"Weiter"})]})]})]})}):i.jsx(Z,{children:i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Verträge gefunden."})}),i.jsx(HR,{isOpen:f,onClose:()=>p(!1)})]})}const QR={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},GR={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},JR={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"};function ZR({contractId:t,isOpen:e,onClose:n}){var o,c,d,u,h,m,f,p,g,x,y;const{data:s,isLoading:r,error:a}=fe({queryKey:["contract",t],queryFn:()=>He.getById(t),enabled:e}),l=s==null?void 0:s.data;return i.jsxs(Xe,{isOpen:e,onClose:n,title:"Vertragsdetails",size:"xl",children:[r&&i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}),a&&i.jsx("div",{className:"text-center py-8 text-red-600",children:"Fehler beim Laden des Vertrags"}),l&&i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center gap-3 pb-4 border-b",children:[i.jsxs("span",{className:"text-xl font-bold font-mono flex items-center gap-2",children:[l.contractNumber,i.jsx(de,{value:l.contractNumber})]}),i.jsx(je,{children:QR[l.type]||l.type}),i.jsx(je,{variant:JR[l.status]||"default",children:GR[l.status]||l.status})]}),(l.providerName||((o=l.provider)==null?void 0:o.name)||l.tariffName||((c=l.tariff)==null?void 0:c.name))&&i.jsx(Z,{title:"Anbieter & Tarif",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(l.providerName||((d=l.provider)==null?void 0:d.name))&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[l.providerName||((u=l.provider)==null?void 0:u.name),i.jsx(de,{value:l.providerName||((h=l.provider)==null?void 0:h.name)||""})]})]}),(l.tariffName||((m=l.tariff)==null?void 0:m.name))&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Tarif"}),i.jsxs("dd",{className:"flex items-center gap-1",children:[l.tariffName||((f=l.tariff)==null?void 0:f.name),i.jsx(de,{value:l.tariffName||((p=l.tariff)==null?void 0:p.name)||""})]})]}),l.customerNumberAtProvider&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer beim Anbieter"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.customerNumberAtProvider,i.jsx(de,{value:l.customerNumberAtProvider})]})]}),l.contractNumberAtProvider&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer beim Anbieter"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.contractNumberAtProvider,i.jsx(de,{value:l.contractNumberAtProvider})]})]})]})}),(l.type==="ELECTRICITY"||l.type==="GAS")&&((g=l.energyDetails)==null?void 0:g.meter)&&i.jsx(Z,{title:"Zähler",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Zählernummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.energyDetails.meter.meterNumber,i.jsx(de,{value:l.energyDetails.meter.meterNumber})]})]}),l.energyDetails.maloId&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"MaLo-ID"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.energyDetails.maloId,i.jsx(de,{value:l.energyDetails.maloId})]})]})]})}),i.jsx(Z,{title:"Laufzeit",children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[l.startDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsbeginn"}),i.jsx("dd",{children:new Date(l.startDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),l.endDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsende"}),i.jsx("dd",{children:new Date(l.endDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),l.contractDuration&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Laufzeit"}),i.jsx("dd",{children:l.contractDuration.description})]}),l.cancellationPeriod&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsfrist"}),i.jsx("dd",{children:l.cancellationPeriod.description})]})]})}),(l.portalUsername||((x=l.provider)==null?void 0:x.portalUrl))&&i.jsx(Z,{title:"Portal-Zugangsdaten",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[((y=l.provider)==null?void 0:y.portalUrl)&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Portal-URL"}),i.jsx("dd",{children:i.jsx("a",{href:l.provider.portalUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:l.provider.portalUrl})})]}),l.portalUsername&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Benutzername"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[l.portalUsername,i.jsx(de,{value:l.portalUsername})]})]})]})}),l.address&&i.jsxs(Z,{title:"Lieferadresse",children:[i.jsxs("p",{children:[l.address.street," ",l.address.houseNumber]}),i.jsxs("p",{children:[l.address.postalCode," ",l.address.city]})]}),l.notes&&i.jsx(Z,{title:"Notizen",children:i.jsx("p",{className:"whitespace-pre-wrap text-gray-700",children:l.notes})})]})]})}function YR({contractId:t,canEdit:e}){const[n,s]=N.useState(!1),[r,a]=N.useState(!1),[l,o]=N.useState(null),c=ye(),{data:d,isLoading:u}=fe({queryKey:["contract-history",t],queryFn:()=>uh.getByContract(t)}),h=G({mutationFn:p=>uh.delete(t,p),onSuccess:()=>{c.invalidateQueries({queryKey:["contract-history",t]})}}),m=(d==null?void 0:d.data)||[],f=[...m].sort((p,g)=>new Date(g.createdAt).getTime()-new Date(p.createdAt).getTime());return i.jsxs("div",{className:"bg-white rounded-lg border p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(S5,{className:"w-4 h-4 text-gray-500"}),i.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Vertragshistorie"}),i.jsx(je,{variant:"default",children:m.length})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[e&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>a(!0),children:i.jsx(Ge,{className:"w-4 h-4"})}),m.length>0&&i.jsx("button",{onClick:()=>s(!n),className:"text-gray-500 hover:text-gray-700",children:n?i.jsx(If,{className:"w-4 h-4"}):i.jsx(Us,{className:"w-4 h-4"})})]})]}),u&&i.jsx("p",{className:"text-sm text-gray-500",children:"Laden..."}),!n&&!u&&f.length>0&&i.jsxs("div",{className:"text-sm text-gray-600",children:[i.jsx("span",{className:"font-medium",children:new Date(f[0].createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})})," - ",f[0].title]}),n&&!u&&f.length>0&&i.jsx("div",{className:"space-y-2",children:f.map(p=>i.jsxs("div",{className:"flex items-start justify-between p-3 bg-gray-50 rounded-lg group",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx("span",{className:"text-sm font-medium text-gray-800",children:p.title}),p.isAutomatic?i.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 text-xs rounded bg-blue-100 text-blue-700",title:"Automatisch erstellt",children:[i.jsx(m5,{className:"w-3 h-3"}),"Auto"]}):i.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 text-xs rounded bg-gray-100 text-gray-600",title:"Manuell erstellt",children:[i.jsx(yo,{className:"w-3 h-3"}),"Manuell"]})]}),p.description&&i.jsx("p",{className:"text-sm text-gray-600 whitespace-pre-wrap mb-1",children:p.description}),i.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-400",children:[i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(cs,{className:"w-3 h-3"}),new Date(p.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})]}),i.jsxs("span",{children:["von ",p.createdBy]})]})]}),e&&!p.isAutomatic&&i.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 ml-3",children:[i.jsx("button",{onClick:()=>o(p),className:"text-gray-500 hover:text-blue-600",title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm("Eintrag wirklich löschen?")&&h.mutate(p.id)},className:"text-gray-500 hover:text-red-600",title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4"})})]})]},p.id))}),n&&!u&&f.length===0&&i.jsx("p",{className:"text-sm text-gray-500 italic",children:"Keine Historie vorhanden."}),(r||l)&&i.jsx(XR,{isOpen:!0,onClose:()=>{a(!1),o(null)},contractId:t,entry:l})]})}function XR({isOpen:t,onClose:e,contractId:n,entry:s}){const r=ye(),a=!!s,[l,o]=N.useState({title:(s==null?void 0:s.title)||"",description:(s==null?void 0:s.description)||""}),[c,d]=N.useState(null),u=G({mutationFn:()=>uh.create(n,{title:l.title,description:l.description||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["contract-history",n]}),e()},onError:p=>{d(p.message)}}),h=G({mutationFn:()=>uh.update(n,s.id,{title:l.title,description:l.description||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["contract-history",n]}),e()},onError:p=>{d(p.message)}}),m=p=>{if(p.preventDefault(),d(null),!l.title.trim()){d("Titel ist erforderlich");return}a?h.mutate():u.mutate()},f=u.isPending||h.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:a?"Eintrag bearbeiten":"Historie-Eintrag hinzufügen",children:i.jsxs("form",{onSubmit:m,className:"space-y-4",children:[c&&i.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm",children:c}),i.jsx(q,{label:"Titel *",value:l.title,onChange:p=>o({...l,title:p.target.value}),placeholder:"z.B. kWh auf 18000 erhöht",required:!0}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung (optional)"}),i.jsx("textarea",{value:l.description,onChange:p=>o({...l,description:p.target.value}),placeholder:"Weitere Details...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})]}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:f,children:f?"Wird gespeichert...":a?"Speichern":"Hinzufügen"})]})]})})}const G1={INTERIM:"Zwischenrechnung",FINAL:"Schlussrechnung",NOT_AVAILABLE:"Nicht verfügbar"};function e3({ecdId:t,invoices:e,contractId:n,canEdit:s}){const[r,a]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=ye(),h=G({mutationFn:g=>sl.deleteInvoice(t,g),onSuccess:()=>{u.invalidateQueries({queryKey:["contract",n.toString()]})}}),m=[...e].sort((g,x)=>new Date(x.invoiceDate).getTime()-new Date(g.invoiceDate).getTime()),f=e.some(g=>g.invoiceType==="FINAL"),p=e.some(g=>g.invoiceType==="NOT_AVAILABLE");return i.jsxs("div",{className:"mt-4 pt-4 border-t",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(We,{className:"w-4 h-4 text-gray-500"}),i.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Rechnungen"}),i.jsx(je,{variant:"default",children:e.length}),f?i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-green-100 text-green-800",children:[i.jsx(Vr,{className:"w-3 h-3"}),"Schlussrechnung"]}):p?i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800",children:[i.jsx(Mn,{className:"w-3 h-3"}),"Nicht verfügbar"]}):e.length>0?i.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-orange-100 text-orange-800",children:[i.jsx(Mn,{className:"w-3 h-3"}),"Schlussrechnung fehlt"]}):null]}),i.jsxs("div",{className:"flex items-center gap-2",children:[s&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>o(!0),children:i.jsx(Ge,{className:"w-4 h-4"})}),e.length>0&&i.jsx("button",{onClick:()=>a(!r),className:"text-gray-500 hover:text-gray-700",children:r?i.jsx(If,{className:"w-4 h-4"}):i.jsx(Us,{className:"w-4 h-4"})})]})]}),!r&&m.length>0&&i.jsxs("div",{className:"text-sm text-gray-600",children:["Letzte: ",new Date(m[0].invoiceDate).toLocaleDateString("de-DE")," - ",G1[m[0].invoiceType]]}),r&&m.length>0&&i.jsx("div",{className:"space-y-2",children:m.map(g=>i.jsxs("div",{className:"flex items-center justify-between p-3 bg-gray-50 rounded-lg group",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-sm font-medium",children:new Date(g.invoiceDate).toLocaleDateString("de-DE")}),i.jsx("div",{className:"text-xs text-gray-500",children:G1[g.invoiceType]})]}),g.documentPath&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("a",{href:`/api${g.documentPath}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm",title:"Anzeigen",children:i.jsx(Oe,{className:"w-4 h-4"})}),i.jsx("a",{href:`/api${g.documentPath}`,download:!0,className:"flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm",title:"Download",children:i.jsx(qn,{className:"w-4 h-4"})})]}),g.notes&&i.jsx("span",{className:"text-xs text-gray-400 italic",children:g.notes})]}),s&&i.jsxs("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100",children:[i.jsx("button",{onClick:()=>d(g),className:"text-gray-500 hover:text-blue-600",title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm("Rechnung wirklich löschen?")&&h.mutate(g.id)},className:"text-gray-500 hover:text-red-600",title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4"})})]})]},g.id))}),r&&m.length===0&&i.jsx("p",{className:"text-sm text-gray-500 italic",children:"Keine Rechnungen vorhanden."}),(l||c)&&i.jsx(t3,{isOpen:!0,onClose:()=>{o(!1),d(null)},ecdId:t,contractId:n,invoice:c})]})}function t3({isOpen:t,onClose:e,ecdId:n,contractId:s,invoice:r}){const a=ye(),l=!!r,o=N.useRef(null),[c,d]=N.useState({invoiceDate:r!=null&&r.invoiceDate?new Date(r.invoiceDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],invoiceType:(r==null?void 0:r.invoiceType)||"INTERIM",notes:(r==null?void 0:r.notes)||""}),[u,h]=N.useState(null),[m,f]=N.useState(null),p=G({mutationFn:async j=>{var E;const k=await sl.addInvoice(n,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return(E=k.data)!=null&&E.id&&await sl.uploadDocument(k.data.id,j),k},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",s.toString()]}),e()},onError:j=>{f(j.message)}}),g=G({mutationFn:async()=>await sl.addInvoice(n,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0}),onSuccess:()=>{a.invalidateQueries({queryKey:["contract",s.toString()]}),e()},onError:j=>{f(j.message)}}),x=G({mutationFn:async j=>{const k=await sl.updateInvoice(n,r.id,{invoiceDate:c.invoiceDate,invoiceType:c.invoiceType,notes:c.notes||void 0});return j&&await sl.uploadDocument(r.id,j),k},onSuccess:()=>{a.invalidateQueries({queryKey:["contract",s.toString()]}),e()},onError:j=>{f(j.message)}}),y=j=>{if(j.preventDefault(),f(null),l){if(c.invoiceType!=="NOT_AVAILABLE"&&!(r!=null&&r.documentPath)&&!u){f("Bitte laden Sie ein Dokument hoch");return}x.mutate(u)}else if(c.invoiceType==="NOT_AVAILABLE")g.mutate();else if(u)p.mutate(u);else{f("Bitte laden Sie ein Dokument hoch");return}},v=j=>{var E;const k=(E=j.target.files)==null?void 0:E[0];if(k){if(k.type!=="application/pdf"){f("Nur PDF-Dateien sind erlaubt");return}if(k.size>10*1024*1024){f("Datei ist zu groß (max. 10 MB)");return}h(k),f(null)}},b=p.isPending||g.isPending||x.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:l?"Rechnung bearbeiten":"Rechnung hinzufügen",children:i.jsxs("form",{onSubmit:y,className:"space-y-4",children:[m&&i.jsx("div",{className:"p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm",children:m}),i.jsx(q,{label:"Rechnungsdatum",type:"date",value:c.invoiceDate,onChange:j=>d({...c,invoiceDate:j.target.value}),required:!0}),i.jsx(Fe,{label:"Rechnungstyp",value:c.invoiceType,onChange:j=>d({...c,invoiceType:j.target.value}),options:[{value:"INTERIM",label:"Zwischenrechnung"},{value:"FINAL",label:"Schlussrechnung"},{value:"NOT_AVAILABLE",label:"Nicht verfügbar"}]}),c.invoiceType!=="NOT_AVAILABLE"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Dokument (PDF) *"}),(r==null?void 0:r.documentPath)&&!u&&i.jsxs("div",{className:"mb-2 text-sm text-green-600 flex items-center gap-1",children:[i.jsx(Vr,{className:"w-4 h-4"}),"Dokument vorhanden"]}),u&&i.jsxs("div",{className:"mb-2 text-sm text-blue-600 flex items-center gap-1",children:[i.jsx(We,{className:"w-4 h-4"}),u.name]}),i.jsx("input",{type:"file",ref:o,accept:".pdf",onChange:v,className:"hidden"}),i.jsx(I,{type:"button",variant:"secondary",onClick:()=>{var j;return(j=o.current)==null?void 0:j.click()},children:r!=null&&r.documentPath||u?"Ersetzen":"PDF hochladen"})]}),c.invoiceType==="NOT_AVAILABLE"&&i.jsx("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-800 text-sm",children:'Bei diesem Typ wird kein Dokument benötigt. Die Rechnung wird als "nicht mehr zu bekommen" markiert.'}),i.jsx(q,{label:"Notizen (optional)",value:c.notes,onChange:j=>d({...c,notes:j.target.value}),placeholder:"Optionale Anmerkungen..."}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:b,children:b?"Wird gespeichert...":l?"Speichern":"Hinzufügen"})]})]})})}const n3=10.5;function J1(t,e){const n=new Date(t),s=new Date(e);n.setHours(0,0,0,0),s.setHours(0,0,0,0);const r=s.getTime()-n.getTime();return Math.ceil(r/(1e3*60*60*24))}function s3(t,e,n){const s=new Date(e),r=new Date(n);return s.setHours(0,0,0,0),r.setHours(0,0,0,0),t.filter(a=>{const l=new Date(a.readingDate);return l.setHours(0,0,0,0),l>=s&&l<=r})}function r3(t,e,n,s){const r=s3(t,e,n);if(r.length===0)return{type:"none",consumptionKwh:0};if(r.length===1)return{type:"insufficient",consumptionKwh:0,message:"Berechnung auf Grund fehlender Stände nicht möglich"};const a=[...r].sort((p,g)=>new Date(p.readingDate).getTime()-new Date(g.readingDate).getTime()),l=a[0],o=a[a.length-1],c=new Date(o.readingDate),d=new Date(n);if(c.setHours(0,0,0,0),d.setHours(0,0,0,0),c>=d){const p=o.value-l.value;return Z1("exact",p,s,l,o)}const u=J1(l.readingDate,o.readingDate);if(u<1)return{type:"insufficient",consumptionKwh:0,message:"Zeitraum zwischen Zählerständen zu kurz für Berechnung"};const h=J1(e,n),f=(o.value-l.value)/u*h;return Z1("projected",f,s,l,o,n)}function Z1(t,e,n,s,r,a){return n==="GAS"?{type:t,consumptionM3:e,consumptionKwh:e*n3,startReading:s,endReading:r,projectedEndDate:a}:{type:t,consumptionKwh:e,startReading:s,endReading:r,projectedEndDate:a}}function i3(t,e,n,s){if(e==null&&n==null)return null;const r=(e??0)*12,a=t*(n??0),l=r+a,o=l-(s??0),c=o/12;return{annualBaseCost:r,annualConsumptionCost:a,annualTotalCost:l,monthlyPayment:c,bonus:s??void 0,effectiveAnnualCost:o}}const a3={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabelinternet",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ-Versicherung"},l3={DRAFT:"Entwurf",PENDING:"Ausstehend",ACTIVE:"Aktiv",CANCELLED:"Gekündigt",EXPIRED:"Abgelaufen",DEACTIVATED:"Deaktiviert"},o3={ACTIVE:"success",PENDING:"warning",CANCELLED:"danger",EXPIRED:"danger",DRAFT:"default",DEACTIVATED:"default"},c3=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function d3({isOpen:t,onClose:e}){return t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:e}),i.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),i.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-600",children:i.jsx(nn,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"space-y-2",children:c3.map(({status:n,label:s,description:r,color:a})=>i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:`font-medium text-sm min-w-[90px] ${a}`,children:s}),i.jsx("span",{className:"text-sm text-gray-600",children:r})]},n))})]})]}):null}function u3(t){const e=t.match(/^(\d+)([TMWJ])$/);if(!e)return!1;const n=parseInt(e[1]),s=e[2];let r=0;return s==="T"?r=n:s==="W"?r=n*7:s==="M"?r=n*30:s==="J"&&(r=n*365),r<=30}function h3({simCard:t}){const[e,n]=N.useState(!1),[s,r]=N.useState(null),[a,l]=N.useState(!1),o=async()=>{if(e)n(!1),r(null);else{l(!0);try{const c=await He.getSimCardCredentials(t.id);c.data&&(r(c.data),n(!0))}catch{alert("PIN/PUK konnte nicht geladen werden")}finally{l(!1)}}};return i.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg border",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.isMain&&i.jsx(je,{variant:"success",children:"Hauptkarte"}),t.isMultisim&&i.jsx(je,{variant:"warning",children:"Multisim"})]}),i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[t.phoneNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"Rufnummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[t.phoneNumber,i.jsx(de,{value:t.phoneNumber})]})]}),t.simCardNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"SIM-Nr."}),i.jsxs("dd",{className:"font-mono text-xs flex items-center gap-1",children:[t.simCardNumber,i.jsx(de,{value:t.simCardNumber})]})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"PIN"}),i.jsx("dd",{className:"font-mono flex items-center gap-1",children:e&&(s!=null&&s.pin)?i.jsxs(i.Fragment,{children:[s.pin,i.jsx(de,{value:s.pin})]}):"••••"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"PUK"}),i.jsx("dd",{className:"font-mono flex items-center gap-1",children:e&&(s!=null&&s.puk)?i.jsxs(i.Fragment,{children:[s.puk,i.jsx(de,{value:s.puk})]}):"••••••••"})]})]}),i.jsx("div",{className:"mt-2",children:i.jsx(I,{variant:"ghost",size:"sm",onClick:o,disabled:a,children:a?"Laden...":e?i.jsxs(i.Fragment,{children:[i.jsx(on,{className:"w-4 h-4 mr-1"})," PIN/PUK verbergen"]}):i.jsxs(i.Fragment,{children:[i.jsx(Oe,{className:"w-4 h-4 mr-1"})," PIN/PUK anzeigen"]})})})]})}function f3({meterId:t,meterType:e,readings:n,contractId:s,canEdit:r}){const[a,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),h=ye(),m=G({mutationFn:g=>ar.deleteReading(t,g),onSuccess:()=>{h.invalidateQueries({queryKey:["contract",s.toString()]})}}),f=[...n].sort((g,x)=>new Date(x.readingDate).getTime()-new Date(g.readingDate).getTime()),p=e==="ELECTRICITY"?"kWh":"m³";return i.jsxs("div",{className:"mt-4 pt-4 border-t",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(bC,{className:"w-4 h-4 text-gray-500"}),i.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Zählerstände"}),i.jsx(je,{variant:"default",children:n.length})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[r&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>c(!0),title:"Zählerstand erfassen",children:i.jsx(Ge,{className:"w-4 h-4"})}),n.length>0&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>l(!a),children:a?i.jsx(If,{className:"w-4 h-4"}):i.jsx(Us,{className:"w-4 h-4"})})]})]}),a&&n.length>0&&i.jsx("div",{className:"space-y-2 bg-gray-50 rounded-lg p-3",children:f.map(g=>i.jsxs("div",{className:"flex justify-between items-center text-sm group py-1 border-b border-gray-200 last:border-0",children:[i.jsxs("span",{className:"text-gray-500 flex items-center gap-1",children:[new Date(g.readingDate).toLocaleDateString("de-DE"),i.jsx(de,{value:new Date(g.readingDate).toLocaleDateString("de-DE")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"font-mono flex items-center gap-1",children:[g.value.toLocaleString("de-DE")," ",g.unit,i.jsx(de,{value:g.value.toString(),title:"Nur Wert kopieren"})]}),r&&i.jsxs("div",{className:"opacity-0 group-hover:opacity-100 flex gap-1",children:[i.jsx("button",{onClick:()=>u(g),className:"text-gray-400 hover:text-blue-600",title:"Bearbeiten",children:i.jsx(rt,{className:"w-3 h-3"})}),i.jsx("button",{onClick:()=>{confirm("Zählerstand wirklich löschen?")&&m.mutate(g.id)},className:"text-gray-400 hover:text-red-600",title:"Löschen",children:i.jsx(Ee,{className:"w-3 h-3"})})]})]})]},g.id))}),!a&&n.length>0&&i.jsxs("p",{className:"text-sm text-gray-500",children:["Letzter Stand: ",f[0].value.toLocaleString("de-DE")," ",f[0].unit," (",new Date(f[0].readingDate).toLocaleDateString("de-DE"),")"]}),n.length===0&&i.jsx("p",{className:"text-sm text-gray-500",children:"Keine Zählerstände vorhanden."}),(o||d)&&i.jsx(m3,{isOpen:!0,onClose:()=>{c(!1),u(null)},meterId:t,contractId:s,reading:d,defaultUnit:p})]})}function m3({isOpen:t,onClose:e,meterId:n,contractId:s,reading:r,defaultUnit:a}){var p;const l=ye(),o=!!r,[c,d]=N.useState({readingDate:r!=null&&r.readingDate?new Date(r.readingDate).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],value:((p=r==null?void 0:r.value)==null?void 0:p.toString())||"",notes:(r==null?void 0:r.notes)||""}),u=G({mutationFn:g=>ar.addReading(n,g),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",s.toString()]}),e()}}),h=G({mutationFn:g=>ar.updateReading(n,r.id,g),onSuccess:()=>{l.invalidateQueries({queryKey:["contract",s.toString()]}),e()}}),m=g=>{g.preventDefault();const x={readingDate:new Date(c.readingDate),value:parseFloat(c.value),unit:a,notes:c.notes||void 0};o?h.mutate(x):u.mutate(x)},f=u.isPending||h.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:o?"Zählerstand bearbeiten":"Zählerstand erfassen",children:i.jsxs("form",{onSubmit:m,className:"space-y-4",children:[i.jsx(q,{label:"Ablesedatum",type:"date",value:c.readingDate,onChange:g=>d({...c,readingDate:g.target.value}),required:!0}),i.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[i.jsx("div",{className:"col-span-2",children:i.jsx(q,{label:"Zählerstand",type:"number",step:"0.01",value:c.value,onChange:g=>d({...c,value:g.target.value}),required:!0})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Einheit"}),i.jsx("div",{className:"h-10 flex items-center px-3 bg-gray-100 border border-gray-300 rounded-md text-gray-700",children:a})]})]}),i.jsx(q,{label:"Notizen (optional)",value:c.notes,onChange:g=>d({...c,notes:g.target.value})}),i.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:f||!c.value,children:f?"Speichern...":o?"Speichern":"Erfassen"})]})]})})}function p3({contractType:t,readings:e,startDate:n,endDate:s,basePrice:r,unitPrice:a,bonus:l}){const o=r3(e,n,s,t),c=o.consumptionKwh>0?i3(o.consumptionKwh,r,a,l):null;if(o.type==="none")return null;const d=(h,m=2)=>h.toLocaleString("de-DE",{minimumFractionDigits:m,maximumFractionDigits:m}),u=h=>new Date(h).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"});return i.jsxs("div",{className:"mt-4 pt-4 border-t",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(x5,{className:"w-4 h-4 text-gray-500"}),i.jsx("h4",{className:"text-sm font-medium text-gray-700",children:"Verbrauch & Kosten"}),o.type==="exact"&&i.jsx(je,{variant:"success",children:"Exakt"}),o.type==="projected"&&i.jsx(je,{variant:"warning",children:"Hochrechnung"})]}),o.type==="insufficient"?i.jsx("p",{className:"text-sm text-gray-500 italic",children:o.message}):i.jsxs("div",{className:"bg-gray-50 rounded-lg p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsxs("h5",{className:"text-sm font-medium text-gray-600 mb-2",children:["Berechneter Verbrauch",o.type==="projected"&&" (hochgerechnet)"]}),i.jsx("div",{className:"text-lg font-semibold text-gray-900",children:t==="GAS"?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"font-mono",children:[d(o.consumptionM3||0)," m³"]}),i.jsxs("span",{className:"text-gray-500 text-sm ml-2",children:["= ",d(o.consumptionKwh)," kWh"]})]}):i.jsxs("span",{className:"font-mono",children:[d(o.consumptionKwh)," kWh"]})}),o.startReading&&o.endReading&&i.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:["Basierend auf Zählerständen vom ",u(o.startReading.readingDate)," bis ",u(o.endReading.readingDate)]})]}),c&&i.jsxs("div",{className:"border-t border-gray-200 pt-4",children:[i.jsx("h5",{className:"text-sm font-medium text-gray-600 mb-3",children:"Kostenvorschau"}),i.jsxs("div",{className:"space-y-2 text-sm",children:[r!=null&&r>0&&i.jsxs("div",{className:"flex justify-between",children:[i.jsxs("span",{className:"text-gray-600",children:["Grundpreis: ",d(r)," €/Mon × 12"]}),i.jsxs("span",{className:"font-mono",children:[d(c.annualBaseCost)," €"]})]}),a!=null&&a>0&&i.jsxs("div",{className:"flex justify-between",children:[i.jsxs("span",{className:"text-gray-600",children:["Arbeitspreis: ",d(o.consumptionKwh)," kWh × ",d(a,4)," €"]}),i.jsxs("span",{className:"font-mono",children:[d(c.annualConsumptionCost)," €"]})]}),i.jsx("div",{className:"border-t border-gray-300 pt-2",children:i.jsxs("div",{className:"flex justify-between font-medium",children:[i.jsx("span",{className:"text-gray-700",children:"Jahreskosten"}),i.jsxs("span",{className:"font-mono",children:[d(c.annualTotalCost)," €"]})]})}),c.bonus!=null&&c.bonus>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex justify-between text-green-600",children:[i.jsx("span",{children:"Bonus"}),i.jsxs("span",{className:"font-mono",children:["- ",d(c.bonus)," €"]})]}),i.jsx("div",{className:"border-t border-gray-300 pt-2",children:i.jsxs("div",{className:"flex justify-between font-semibold",children:[i.jsx("span",{className:"text-gray-800",children:"Effektive Jahreskosten"}),i.jsxs("span",{className:"font-mono",children:[d(c.effectiveAnnualCost)," €"]})]})})]}),i.jsx("div",{className:"border-t border-gray-300 pt-2 mt-2",children:i.jsxs("div",{className:"flex justify-between text-blue-700 font-semibold",children:[i.jsx("span",{children:"Monatlicher Abschlag"}),i.jsxs("span",{className:"font-mono",children:[d(c.monthlyPayment)," €"]})]})})]})]})]})]})}function Y1({task:t,contractId:e,canEdit:n,isCustomerPortal:s,isCompleted:r,onEdit:a}){const[l,o]=N.useState(""),[c,d]=N.useState(!1),[u,h]=N.useState(null),[m,f]=N.useState(""),p=ye(),g=G({mutationFn:_=>ht.complete(_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]})}}),x=G({mutationFn:_=>ht.reopen(_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]})}}),y=G({mutationFn:_=>ht.delete(_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]})}}),v=G({mutationFn:_=>ht.createSubtask(t.id,_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]}),o(""),d(!1)},onError:_=>{console.error("Fehler beim Erstellen der Unteraufgabe:",_),alert("Fehler beim Erstellen der Unteraufgabe. Bitte versuchen Sie es erneut.")}}),b=G({mutationFn:_=>ht.createReply(t.id,_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]}),o(""),d(!1)},onError:_=>{console.error("Fehler beim Erstellen der Antwort:",_),alert("Fehler beim Erstellen der Antwort. Bitte versuchen Sie es erneut.")}}),j=G({mutationFn:({id:_,title:K})=>ht.updateSubtask(_,K),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]}),h(null),f("")}}),k=G({mutationFn:_=>ht.completeSubtask(_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]})}}),E=G({mutationFn:_=>ht.reopenSubtask(_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]})}}),T=G({mutationFn:_=>ht.deleteSubtask(_),onSuccess:async()=>{await p.refetchQueries({queryKey:["contract-tasks",e]})}}),w=_=>{_.preventDefault(),l.trim()&&(s?b.mutate(l.trim()):v.mutate(l.trim()))},S=_=>{_.preventDefault(),m.trim()&&u&&j.mutate({id:u,title:m.trim()})},M=(_,K)=>{h(_),f(K)},F=()=>{h(null),f("")},R=t.subtasks||[],V=R.filter(_=>_.status==="OPEN"),D=R.filter(_=>_.status==="COMPLETED"),z=s?{singular:"Antwort",placeholder:"Antwort...",deleteConfirm:"Antwort löschen?"}:{singular:"Unteraufgabe",placeholder:"Unteraufgabe...",deleteConfirm:"Unteraufgabe löschen?"},C=(_,K)=>u===_.id?i.jsx("div",{className:"py-1",children:i.jsxs("form",{onSubmit:S,className:"flex items-center gap-2",children:[i.jsx(Eu,{className:"w-4 h-4 text-gray-300 flex-shrink-0"}),i.jsx("input",{type:"text",value:m,onChange:W=>f(W.target.value),className:"flex-1 text-sm px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500",autoFocus:!0}),i.jsx(I,{type:"submit",size:"sm",disabled:!m.trim()||j.isPending,children:"✓"}),i.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:F,children:"×"})]})},_.id):i.jsx("div",{className:`py-1 group/subtask ${K?"opacity-60":""}`,children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("button",{onClick:()=>K?E.mutate(_.id):k.mutate(_.id),disabled:k.isPending||E.isPending||s,className:`flex-shrink-0 mt-0.5 ${s?"cursor-default":K?"hover:text-yellow-600":"hover:text-green-600"}`,children:K?i.jsx(Un,{className:"w-4 h-4 text-green-500"}):i.jsx(Eu,{className:"w-4 h-4 text-gray-400"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:`text-sm ${K?"line-through text-gray-500":""}`,children:_.title}),n&&!s&&!K&&i.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover/subtask:opacity-100",children:[i.jsx("button",{onClick:()=>M(_.id,_.title),className:"text-gray-400 hover:text-blue-600 p-0.5",title:"Bearbeiten",children:i.jsx(rt,{className:"w-3 h-3"})}),i.jsx("button",{onClick:()=>{confirm(z.deleteConfirm)&&T.mutate(_.id)},className:"text-gray-400 hover:text-red-600 p-0.5",title:"Löschen",children:i.jsx(Ee,{className:"w-3 h-3"})})]}),n&&!s&&K&&i.jsx("button",{onClick:()=>{confirm(z.deleteConfirm)&&T.mutate(_.id)},className:"text-gray-400 hover:text-red-600 p-0.5 opacity-0 group-hover/subtask:opacity-100",title:"Löschen",children:i.jsx(Ee,{className:"w-3 h-3"})})]}),i.jsxs("p",{className:"text-xs text-gray-400",children:[_.createdBy&&`${_.createdBy} • `,K?`Erledigt am ${_.completedAt?new Date(_.completedAt).toLocaleDateString("de-DE"):new Date(_.updatedAt).toLocaleDateString("de-DE")}`:new Date(_.createdAt).toLocaleDateString("de-DE")]})]})]})},_.id);return i.jsx("div",{className:`p-3 bg-gray-50 rounded-lg group ${r?"bg-gray-50/50 opacity-70":""}`,children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>r?x.mutate(t.id):g.mutate(t.id),disabled:g.isPending||x.isPending||s,className:`mt-0.5 flex-shrink-0 ${s?"cursor-default":r?"hover:text-yellow-600":"hover:text-green-600"}`,title:s?void 0:r?"Wieder öffnen":"Als erledigt markieren",children:r?i.jsx(Un,{className:"w-5 h-5 text-green-500"}):i.jsx(Eu,{className:"w-5 h-5 text-gray-400"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`font-medium ${r?"line-through text-gray-500":""}`,children:t.title}),t.visibleInPortal&&i.jsx(je,{variant:"default",className:"text-xs",children:"Portal"}),R.length>0&&i.jsxs("span",{className:"text-xs text-gray-400",children:["(",D.length,"/",R.length,")"]})]}),t.description&&i.jsx("p",{className:`text-sm mt-1 whitespace-pre-wrap ${r?"text-gray-500":"text-gray-600"}`,children:t.description}),i.jsxs("p",{className:"text-xs text-gray-400 mt-1",children:[t.createdBy&&`${t.createdBy} • `,r?`Erledigt am ${t.completedAt?new Date(t.completedAt).toLocaleDateString("de-DE"):"-"}`:new Date(t.createdAt).toLocaleDateString("de-DE")]}),R.length>0&&i.jsxs("div",{className:"mt-3 ml-2 space-y-0 border-l-2 border-gray-200 pl-3",children:[V.map(_=>C(_,!1)),D.map(_=>C(_,!0))]}),!r&&(n&&!s||s)&&i.jsx("div",{className:"mt-2 ml-2",children:c?i.jsxs("form",{onSubmit:w,className:"flex items-center gap-2",children:[i.jsx("input",{type:"text",value:l,onChange:_=>o(_.target.value),placeholder:z.placeholder,className:"flex-1 text-sm px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-blue-500",autoFocus:!0}),i.jsx(I,{type:"submit",size:"sm",disabled:!l.trim()||v.isPending||b.isPending,children:i.jsx(Ge,{className:"w-3 h-3"})}),i.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>{d(!1),o("")},children:"×"})]}):i.jsxs("button",{onClick:()=>d(!0),className:"text-xs text-gray-400 hover:text-blue-600 flex items-center gap-1",children:[i.jsx(Ge,{className:"w-3 h-3"}),z.singular]})})]}),n&&!s&&i.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100",children:[!r&&i.jsx("button",{onClick:a,className:"text-gray-400 hover:text-blue-600 p-1",title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm("Aufgabe wirklich löschen?")&&y.mutate(t.id)},className:"text-gray-400 hover:text-red-600 p-1",title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4"})})]})]})})}function g3({contractId:t,canEdit:e,isCustomerPortal:n}){var b;const[s,r]=N.useState(!1),[a,l]=N.useState(null),{data:o,isLoading:c}=fe({queryKey:["contract-tasks",t],queryFn:()=>ht.getByContract(t),staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:d,isLoading:u}=fe({queryKey:["app-settings-public"],queryFn:()=>Ba.getPublic(),enabled:n,staleTime:0}),h=!u&&((b=d==null?void 0:d.data)==null?void 0:b.customerSupportTicketsEnabled)==="true",m=(o==null?void 0:o.data)||[],f=m.filter(j=>j.status==="OPEN"),p=m.filter(j=>j.status==="COMPLETED"),g=n?{title:"Support-Anfragen",button:"Anfrage erstellen",empty:"Keine Support-Anfragen vorhanden."}:{title:"Aufgaben",button:"Aufgabe",empty:"Keine Aufgaben vorhanden."},x=n?Vc:_c;if(c||n&&u)return i.jsx(Z,{className:"mb-6",title:g.title,children:i.jsx("div",{className:"text-center py-4 text-gray-500",children:"Laden..."})});const v=e&&!n||n&&h;return i.jsxs(Z,{className:"mb-6",title:g.title,children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(x,{className:"w-5 h-5 text-gray-500"}),i.jsxs("span",{className:"text-sm text-gray-600",children:[f.length," offen, ",p.length," erledigt"]})]}),v&&i.jsxs(I,{size:"sm",onClick:()=>r(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-1"}),g.button]})]}),m.length===0?i.jsx("p",{className:"text-center py-4 text-gray-500",children:g.empty}):i.jsxs("div",{className:"space-y-2",children:[f.map(j=>i.jsx(Y1,{task:j,contractId:t,canEdit:e,isCustomerPortal:n,isCompleted:!1,onEdit:()=>l(j)},j.id)),p.length>0&&f.length>0&&i.jsx("div",{className:"border-t my-3"}),p.map(j=>i.jsx(Y1,{task:j,contractId:t,canEdit:e,isCustomerPortal:n,isCompleted:!0,onEdit:()=>{}},j.id))]}),(s||a)&&i.jsx(x3,{isOpen:!0,onClose:()=>{r(!1),l(null)},contractId:t,task:a,isCustomerPortal:n})]})}function x3({isOpen:t,onClose:e,contractId:n,task:s,isCustomerPortal:r=!1}){const a=ye(),l=!!s,[o,c]=N.useState({title:(s==null?void 0:s.title)||"",description:(s==null?void 0:s.description)||"",visibleInPortal:(s==null?void 0:s.visibleInPortal)||!1});N.useEffect(()=>{t&&c({title:(s==null?void 0:s.title)||"",description:(s==null?void 0:s.description)||"",visibleInPortal:(s==null?void 0:s.visibleInPortal)||!1})},[t,s]);const d=G({mutationFn:g=>ht.create(n,g),onSuccess:async()=>{await a.refetchQueries({queryKey:["contract-tasks",n]}),e()}}),u=G({mutationFn:g=>ht.createSupportTicket(n,g),onSuccess:async()=>{await a.refetchQueries({queryKey:["contract-tasks",n]}),e()}}),h=G({mutationFn:g=>ht.update(s.id,g),onSuccess:async()=>{await a.refetchQueries({queryKey:["contract-tasks",n]}),e()}}),m=g=>{g.preventDefault(),l?h.mutate({title:o.title,description:o.description||void 0,visibleInPortal:o.visibleInPortal}):r?u.mutate({title:o.title,description:o.description||void 0}):d.mutate({title:o.title,description:o.description||void 0,visibleInPortal:o.visibleInPortal})},f=d.isPending||u.isPending||h.isPending,p=r?{modalTitle:l?"Anfrage bearbeiten":"Neue Support-Anfrage",titleLabel:"Betreff",titlePlaceholder:"Kurze Beschreibung Ihrer Anfrage",descLabel:"Ihre Nachricht",descPlaceholder:"Beschreiben Sie Ihr Anliegen...",submitBtn:l?"Speichern":"Anfrage senden"}:{modalTitle:l?"Aufgabe bearbeiten":"Neue Aufgabe",titleLabel:"Titel",titlePlaceholder:"Kurze Beschreibung der Aufgabe",descLabel:"Beschreibung (optional)",descPlaceholder:"Details zur Aufgabe...",submitBtn:l?"Speichern":"Erstellen"};return i.jsx(Xe,{isOpen:t,onClose:e,title:p.modalTitle,children:i.jsxs("form",{onSubmit:m,className:"space-y-4",children:[i.jsx(q,{label:p.titleLabel,value:o.title,onChange:g=>c({...o,title:g.target.value}),required:!0,placeholder:p.titlePlaceholder}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:p.descLabel}),i.jsx("textarea",{value:o.description,onChange:g=>c({...o,description:g.target.value}),className:"w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",rows:r?5:3,placeholder:p.descPlaceholder})]}),!r&&i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:o.visibleInPortal,onChange:g=>c({...o,visibleInPortal:g.target.checked}),className:"w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),i.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:f||!o.title.trim(),children:f?"Speichern...":p.submitBtn})]})]})})}function y3(){var pt,On,wn,le,it,Rt;const{id:t}=md(),e=fn(),s=qr().state,r=ye(),{hasPermission:a,isCustomer:l,isCustomerPortal:o}=nt(),c=parseInt(t),[d,u]=N.useState(!1),[h,m]=N.useState(null),[f,p]=N.useState(!1),[g,x]=N.useState(!1),[y,v]=N.useState(null),[b,j]=N.useState({}),[k,E]=N.useState({}),[T,w]=N.useState(!1),[S,M]=N.useState(!1),[F,R]=N.useState(!1),[V,D]=N.useState(!1),{data:z,isLoading:C}=fe({queryKey:["contract",t],queryFn:()=>He.getById(c)}),_=G({mutationFn:()=>He.delete(c),onSuccess:()=>{e("/contracts")}}),K=G({mutationFn:()=>He.createFollowUp(c),onSuccess:J=>{J.data?e(`/contracts/${J.data.id}/edit`):alert("Folgevertrag wurde erstellt, aber keine ID zurückgegeben")},onError:J=>{console.error("Folgevertrag Fehler:",J),alert(`Fehler beim Erstellen des Folgevertrags: ${J instanceof Error?J.message:"Unbekannter Fehler"}`)}}),B=G({mutationFn:()=>He.snooze(c,{}),onSuccess:()=>{r.invalidateQueries({queryKey:["contract",t]}),r.invalidateQueries({queryKey:["contract-cockpit"]}),D(!1)},onError:J=>{console.error("Un-Snooze Fehler:",J),alert(`Fehler beim Aufheben der Zurückstellung: ${J instanceof Error?J.message:"Unbekannter Fehler"}`)}}),W=G({mutationFn:J=>{const ct={cancellationConfirmationDate:J?new Date(J).toISOString():null};return He.update(c,ct)},onSuccess:()=>{r.invalidateQueries({queryKey:["contract",t]}),r.invalidateQueries({queryKey:["contract-cockpit"]})},onError:J=>{console.error("Fehler beim Speichern des Datums:",J),alert("Fehler beim Speichern des Datums")}}),ce=G({mutationFn:J=>{const ct={cancellationConfirmationOptionsDate:J?new Date(J).toISOString():null};return He.update(c,ct)},onSuccess:()=>{r.invalidateQueries({queryKey:["contract",t]}),r.invalidateQueries({queryKey:["contract-cockpit"]})},onError:J=>{console.error("Fehler beim Speichern des Datums:",J),alert("Fehler beim Speichern des Datums")}}),he=async()=>{var J;if(d)u(!1),m(null);else try{const Ke=await He.getPassword(c);(J=Ke.data)!=null&&J.password&&(m(Ke.data.password),u(!0))}catch{alert("Passwort konnte nicht entschlüsselt werden")}},Je=async()=>{var J;if(g)x(!1),v(null);else try{const Ke=await He.getInternetCredentials(c);(J=Ke.data)!=null&&J.password&&(v(Ke.data.password),x(!0))}catch{alert("Internet-Passwort konnte nicht entschlüsselt werden")}},et=async J=>{var Ke;if(b[J])j(ct=>({...ct,[J]:!1})),E(ct=>({...ct,[J]:null}));else try{const ee=(Ke=(await He.getSipCredentials(J)).data)==null?void 0:Ke.password;ee&&(E(pe=>({...pe,[J]:ee})),j(pe=>({...pe,[J]:!0})))}catch{alert("SIP-Passwort konnte nicht entschlüsselt werden")}},mt=async()=>{var ct,ee,pe;const J=z==null?void 0:z.data,Ke=((ct=J==null?void 0:J.stressfreiEmail)==null?void 0:ct.email)||(J==null?void 0:J.portalUsername);if(!((ee=J==null?void 0:J.provider)!=null&&ee.portalUrl)||!Ke){alert("Portal-URL oder Benutzername fehlt");return}p(!0);try{const Ln=await He.getPassword(c);if(!((pe=Ln.data)!=null&&pe.password)){alert("Passwort konnte nicht entschlüsselt werden");return}const ur=J.provider,Ot=ur.portalUrl,L=ur.usernameFieldName||"username",U=ur.passwordFieldName||"password",Q=new URL(Ot);Q.searchParams.set(L,Ke),Q.searchParams.set(U,Ln.data.password),window.open(Q.toString(),"_blank")}catch{alert("Fehler beim Auto-Login")}finally{p(!1)}};if(C)return i.jsx("div",{className:"text-center py-8",children:"Laden..."});if(!(z!=null&&z.data))return i.jsx("div",{className:"text-center py-8 text-red-600",children:"Vertrag nicht gefunden"});const A=z.data;return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-2",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{if((s==null?void 0:s.from)==="customer"&&(s!=null&&s.customerId))e(`/customers/${s.customerId}?tab=contracts`);else if((s==null?void 0:s.from)==="cockpit"){const J=s.filter?`?filter=${s.filter}`:"";e(`/contracts/cockpit${J}`)}else(s==null?void 0:s.from)==="contracts"?e("/contracts"):A.customer?e(`/customers/${A.customer.id}?tab=contracts`):e("/contracts")},children:i.jsx(Yn,{className:"w-4 h-4"})}),i.jsx("h1",{className:"text-2xl font-bold",children:A.contractNumber}),i.jsx(je,{children:a3[A.type]}),i.jsx(je,{variant:o3[A.status],children:l3[A.status]}),i.jsx("button",{onClick:()=>R(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:i.jsx(bd,{className:"w-4 h-4"})}),A.nextReviewDate&&new Date(A.nextReviewDate)>new Date&&i.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-amber-100 text-amber-800 rounded-full text-xs",children:[i.jsx(mC,{className:"w-3 h-3"}),i.jsxs("span",{children:["Zurückgestellt bis ",new Date(A.nextReviewDate).toLocaleDateString("de-DE")]}),a("contracts:update")&&i.jsx("button",{onClick:()=>D(!0),className:"ml-1 p-0.5 hover:bg-amber-200 rounded",title:"Zurückstellung aufheben",children:i.jsx(nn,{className:"w-3 h-3"})})]})]}),A.customer&&i.jsxs("p",{className:"text-gray-500 ml-10",children:["Kunde:"," ",i.jsx(Me,{to:`/customers/${A.customer.id}`,className:"text-blue-600 hover:underline",children:A.customer.companyName||`${A.customer.firstName} ${A.customer.lastName}`})]})]}),!l&&i.jsxs("div",{className:"flex gap-2",children:[A.previousContract&&i.jsx(Me,{to:`/contracts/${A.previousContract.id}`,children:i.jsxs(I,{variant:"secondary",children:[i.jsx(Yn,{className:"w-4 h-4 mr-2"}),"Vorgängervertrag"]})}),a("contracts:create")&&!A.followUpContract&&i.jsxs(I,{variant:"secondary",onClick:()=>M(!0),disabled:K.isPending,children:[i.jsx(Iy,{className:"w-4 h-4 mr-2"}),K.isPending?"Erstelle...":"Folgevertrag anlegen"]}),A.followUpContract&&i.jsx(Me,{to:`/contracts/${A.followUpContract.id}`,children:i.jsxs(I,{variant:"secondary",children:[i.jsx(fC,{className:"w-4 h-4 mr-2"}),"Folgevertrag anzeigen"]})}),a("contracts:update")&&i.jsx(Me,{to:`/contracts/${t}/edit`,children:i.jsxs(I,{variant:"secondary",children:[i.jsx(rt,{className:"w-4 h-4 mr-2"}),"Bearbeiten"]})}),a("contracts:delete")&&i.jsxs(I,{variant:"danger",onClick:()=>{confirm("Vertrag wirklich löschen?")&&_.mutate()},children:[i.jsx(Ee,{className:"w-4 h-4 mr-2"}),"Löschen"]})]})]}),A.previousContract&&i.jsx(Z,{className:"mb-6 border-l-4 border-l-blue-500",title:"Vorgängervertrag",children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),i.jsx("dd",{children:i.jsx("button",{onClick:()=>w(!0),className:"text-blue-600 hover:underline",children:A.previousContract.contractNumber})})]}),A.previousContract.providerName&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),i.jsx("dd",{children:A.previousContract.providerName})]}),A.previousContract.customerNumberAtProvider&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),i.jsx("dd",{className:"font-mono",children:A.previousContract.customerNumberAtProvider})]}),A.previousContract.contractNumberAtProvider&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),i.jsx("dd",{className:"font-mono",children:A.previousContract.contractNumberAtProvider})]}),A.previousContract.portalUsername&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Zugangsdaten"}),i.jsx("dd",{children:A.previousContract.portalUsername})]})]})}),!A.previousContract&&(A.previousProvider||A.previousCustomerNumber||A.previousContractNumber)&&i.jsx(Z,{className:"mb-6 border-l-4 border-l-gray-400",title:"Altanbieter",children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[A.previousProvider&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),i.jsx("dd",{children:A.previousProvider.name})]}),A.previousCustomerNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.previousCustomerNumber,i.jsx(de,{value:A.previousCustomerNumber})]})]}),A.previousContractNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.previousContractNumber,i.jsx(de,{value:A.previousContractNumber})]})]})]})}),A.cancellationConfirmationDate&&i.jsxs("div",{className:"mb-6 p-4 bg-red-50 border-2 border-red-400 rounded-lg flex items-start gap-3",children:[i.jsx("span",{className:"text-red-600 text-xl font-bold",children:"!"}),i.jsxs("div",{children:[i.jsx("p",{className:"font-semibold text-red-800",children:"Kündigungsbestätigung vorhanden"}),i.jsxs("p",{className:"text-sm text-red-700 mt-1",children:["Dieser Vertrag hat eine Kündigungsbestätigung vom"," ",i.jsx("strong",{children:new Date(A.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),".",A.cancellationConfirmationOptionsDate&&i.jsxs(i.Fragment,{children:[" Optionen-Bestätigung: ",i.jsx("strong",{children:new Date(A.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}),"."]})]})]})]}),A.type==="MOBILE"&&((pt=A.mobileDetails)==null?void 0:pt.requiresMultisim)&&i.jsxs("div",{className:"mb-6 p-4 bg-amber-50 border border-amber-300 rounded-lg flex items-start gap-3",children:[i.jsx("span",{className:"text-amber-600 text-xl font-bold",children:"!"}),i.jsxs("div",{children:[i.jsx("p",{className:"font-semibold text-amber-800",children:"Multisim erforderlich"}),i.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"Dieser Kunde benötigt eine Multisim-Karte. Multisim ist bei Klarmobil, Congstar und Otelo nicht buchbar. Bitte einen Anbieter wie Freenet oder vergleichbar wählen."})]})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6",children:[i.jsx(Z,{title:"Anbieter & Tarif",children:i.jsxs("dl",{className:"space-y-3",children:[(A.provider||A.providerName)&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Anbieter"}),i.jsx("dd",{className:"font-medium",children:((On=A.provider)==null?void 0:On.name)||A.providerName})]}),(A.tariff||A.tariffName)&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Tarif"}),i.jsx("dd",{children:((wn=A.tariff)==null?void 0:wn.name)||A.tariffName})]}),A.customerNumberAtProvider&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kundennummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.customerNumberAtProvider,i.jsx(de,{value:A.customerNumberAtProvider})]})]}),A.contractNumberAtProvider&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsnummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.contractNumberAtProvider,i.jsx(de,{value:A.contractNumberAtProvider})]})]}),A.salesPlatform&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertriebsplattform"}),i.jsx("dd",{children:A.salesPlatform.name})]}),A.commission!==null&&A.commission!==void 0&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Provision"}),i.jsx("dd",{children:A.commission.toLocaleString("de-DE",{style:"currency",currency:"EUR"})})]}),A.priceFirst12Months&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Preis erste 12 Monate"}),i.jsx("dd",{children:A.priceFirst12Months})]}),A.priceFrom13Months&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Preis ab 13. Monat"}),i.jsx("dd",{children:A.priceFrom13Months})]}),A.priceAfter24Months&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Preis nach 24 Monaten"}),i.jsx("dd",{children:A.priceAfter24Months})]})]})}),i.jsxs(Z,{title:"Laufzeit und Kündigung",className:A.cancellationConfirmationDate?"border-2 border-red-400":"",children:[A.contractDuration&&u3(A.contractDuration.code)&&i.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[i.jsx("strong",{children:"Hinweis:"})," Dieser Vertrag gilt als unbefristet mit der jeweiligen Kündigungsfrist."]}),i.jsxs("dl",{className:"space-y-3",children:[A.startDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsbeginn"}),i.jsx("dd",{children:new Date(A.startDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),A.endDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragsende"}),i.jsx("dd",{children:new Date(A.endDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),A.contractDuration&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vertragslaufzeit"}),i.jsx("dd",{children:A.contractDuration.description})]}),A.cancellationPeriod&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsfrist"}),i.jsx("dd",{children:A.cancellationPeriod.description})]}),A.cancellationConfirmationDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsdatum"}),i.jsx("dd",{children:new Date(A.cancellationConfirmationDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),A.cancellationConfirmationOptionsDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kündigungsbestätigungsoptionendatum"}),i.jsx("dd",{children:new Date(A.cancellationConfirmationOptionsDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})]}),A.wasSpecialCancellation&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Sonderkündigung"}),i.jsx("dd",{children:i.jsx(je,{variant:"warning",children:"Ja"})})]})]}),a("contracts:update")&&i.jsxs("div",{className:"mt-6 pt-6 border-t",children:[i.jsx("h4",{className:"font-medium mb-4",children:"Kündigungsdokumente"}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsschreiben"}),A.cancellationLetterPath?i.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[i.jsxs("a",{href:`/api${A.cancellationLetterPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${A.cancellationLetterPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationLetter(c,J),r.invalidateQueries({queryKey:["contract",t]})},existingFile:A.cancellationLetterPath,accept:".pdf",label:"Ersetzen"}),i.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await Ct.deleteCancellationLetter(c),r.invalidateQueries({queryKey:["contract",t]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]}):i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationLetter(c,J),r.invalidateQueries({queryKey:["contract",t]})},accept:".pdf",label:"PDF hochladen"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsbestätigung"}),A.cancellationConfirmationPath?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[i.jsxs("a",{href:`/api${A.cancellationConfirmationPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${A.cancellationConfirmationPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationConfirmation(c,J),r.invalidateQueries({queryKey:["contract",t]})},existingFile:A.cancellationConfirmationPath,accept:".pdf",label:"Ersetzen"}),i.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await Ct.deleteCancellationConfirmation(c),r.invalidateQueries({queryKey:["contract",t]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]}),i.jsxs("div",{className:"mt-2",children:[i.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Bestätigung erhalten am"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"date",value:A.cancellationConfirmationDate?A.cancellationConfirmationDate.split("T")[0]:"",onChange:J=>{const Ke=J.target.value||null;W.mutate(Ke)},className:"block w-full max-w-[180px] px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"}),A.cancellationConfirmationDate&&i.jsx("button",{onClick:()=>W.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:i.jsx(Ee,{className:"w-4 h-4"})})]})]})]}):i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationConfirmation(c,J),r.invalidateQueries({queryKey:["contract",t]})},accept:".pdf",label:"PDF hochladen"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsschreiben Optionen"}),A.cancellationLetterOptionsPath?i.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[i.jsxs("a",{href:`/api${A.cancellationLetterOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${A.cancellationLetterOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationLetterOptions(c,J),r.invalidateQueries({queryKey:["contract",t]})},existingFile:A.cancellationLetterOptionsPath,accept:".pdf",label:"Ersetzen"}),i.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await Ct.deleteCancellationLetterOptions(c),r.invalidateQueries({queryKey:["contract",t]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]}):i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationLetterOptions(c,J),r.invalidateQueries({queryKey:["contract",t]})},accept:".pdf",label:"PDF hochladen"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500 mb-1",children:"Kündigungsbestätigung Optionen"}),A.cancellationConfirmationOptionsPath?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[i.jsxs("a",{href:`/api${A.cancellationConfirmationOptionsPath}`,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Oe,{className:"w-4 h-4"}),"Anzeigen"]}),i.jsxs("a",{href:`/api${A.cancellationConfirmationOptionsPath}`,download:!0,className:"text-blue-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(qn,{className:"w-4 h-4"}),"Download"]}),i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationConfirmationOptions(c,J),r.invalidateQueries({queryKey:["contract",t]})},existingFile:A.cancellationConfirmationOptionsPath,accept:".pdf",label:"Ersetzen"}),i.jsxs("button",{onClick:async()=>{confirm("Dokument wirklich löschen?")&&(await Ct.deleteCancellationConfirmationOptions(c),r.invalidateQueries({queryKey:["contract",t]}))},className:"text-red-600 hover:underline text-sm flex items-center gap-1",children:[i.jsx(Ee,{className:"w-4 h-4"}),"Löschen"]})]}),i.jsxs("div",{className:"mt-2",children:[i.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Bestätigung erhalten am"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"date",value:A.cancellationConfirmationOptionsDate?A.cancellationConfirmationOptionsDate.split("T")[0]:"",onChange:J=>{const Ke=J.target.value||null;ce.mutate(Ke)},className:"block w-full max-w-[180px] px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"}),A.cancellationConfirmationOptionsDate&&i.jsx("button",{onClick:()=>ce.mutate(null),className:"p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded",title:"Datum löschen",children:i.jsx(Ee,{className:"w-4 h-4"})})]})]})]}):i.jsx(Jt,{onUpload:async J=>{await Ct.uploadCancellationConfirmationOptions(c,J),r.invalidateQueries({queryKey:["contract",t]})},accept:".pdf",label:"PDF hochladen"})]})]})]})]})]}),(A.portalUsername||A.stressfreiEmail||A.portalPasswordEncrypted)&&i.jsxs(Z,{className:"mb-6",title:"Zugangsdaten",children:[i.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[(A.portalUsername||A.stressfreiEmail)&&i.jsxs("div",{children:[i.jsxs("dt",{className:"text-sm text-gray-500",children:["Benutzername",A.stressfreiEmail&&i.jsx("span",{className:"ml-2 text-xs text-blue-600",children:"(Stressfrei-Wechseln)"})]}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[((le=A.stressfreiEmail)==null?void 0:le.email)||A.portalUsername,i.jsx(de,{value:((it=A.stressfreiEmail)==null?void 0:it.email)||A.portalUsername||""})]})]}),A.portalPasswordEncrypted&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Passwort"}),i.jsxs("dd",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"font-mono",children:d&&h?h:"••••••••"}),d&&h&&i.jsx(de,{value:h}),i.jsx(I,{variant:"ghost",size:"sm",onClick:he,children:d?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]})]}),((Rt=A.provider)==null?void 0:Rt.portalUrl)&&(A.portalUsername||A.stressfreiEmail)&&A.portalPasswordEncrypted&&i.jsxs("div",{className:"mt-4 pt-4 border-t",children:[i.jsxs(I,{onClick:mt,disabled:f,className:"w-full sm:w-auto",children:[i.jsx(Oy,{className:"w-4 h-4 mr-2"}),f?"Wird geöffnet...":"Zum Kundenportal (Auto-Login)"]}),i.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"Öffnet das Portal mit vorausgefüllten Zugangsdaten"})]})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6",children:[A.address&&i.jsx(Z,{title:"Lieferadresse",children:i.jsxs(Vg,{values:[`${A.address.street} ${A.address.houseNumber}`,`${A.address.postalCode} ${A.address.city}`,A.address.country],children:[i.jsxs("p",{children:[A.address.street," ",A.address.houseNumber]}),i.jsxs("p",{children:[A.address.postalCode," ",A.address.city]}),i.jsx("p",{className:"text-gray-500",children:A.address.country})]})}),(A.billingAddress||A.address)&&i.jsx(Z,{title:"Rechnungsadresse",children:(()=>{const J=A.billingAddress||A.address;return J?i.jsxs(Vg,{values:[`${J.street} ${J.houseNumber}`,`${J.postalCode} ${J.city}`,J.country],children:[i.jsxs("p",{children:[J.street," ",J.houseNumber]}),i.jsxs("p",{children:[J.postalCode," ",J.city]}),i.jsx("p",{className:"text-gray-500",children:J.country}),!A.billingAddress&&A.address&&i.jsx("p",{className:"text-xs text-gray-400 mt-1",children:"(wie Lieferadresse)"})]}):null})()}),A.bankCard&&i.jsxs(Z,{title:"Bankkarte",children:[i.jsx("p",{className:"font-medium",children:A.bankCard.accountHolder}),i.jsxs("p",{className:"font-mono flex items-center gap-1",children:[A.bankCard.iban,i.jsx(de,{value:A.bankCard.iban})]}),A.bankCard.bankName&&i.jsx("p",{className:"text-gray-500",children:A.bankCard.bankName})]}),A.identityDocument&&i.jsxs(Z,{title:"Ausweis",children:[i.jsxs("p",{className:"font-mono flex items-center gap-1",children:[A.identityDocument.documentNumber,i.jsx(de,{value:A.identityDocument.documentNumber})]}),i.jsx("p",{className:"text-gray-500",children:A.identityDocument.type})]})]}),A.energyDetails&&i.jsxs(Z,{className:"mb-6",title:A.type==="ELECTRICITY"?"Strom-Details":"Gas-Details",children:[i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[A.energyDetails.meter&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Zählernummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.energyDetails.meter.meterNumber,i.jsx(de,{value:A.energyDetails.meter.meterNumber})]})]}),A.energyDetails.maloId&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"MaLo-ID"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.energyDetails.maloId,i.jsx(de,{value:A.energyDetails.maloId})]})]}),A.energyDetails.annualConsumption&&i.jsxs("div",{children:[i.jsxs("dt",{className:"text-sm text-gray-500",children:["Jahresverbrauch ",A.type==="ELECTRICITY"?"":"(m³)"]}),i.jsxs("dd",{children:[A.energyDetails.annualConsumption.toLocaleString("de-DE")," ",A.type==="ELECTRICITY"?"kWh":"m³"]})]}),A.type==="GAS"&&A.energyDetails.annualConsumptionKwh&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Jahresverbrauch (kWh)"}),i.jsxs("dd",{children:[A.energyDetails.annualConsumptionKwh.toLocaleString("de-DE")," kWh"]})]}),A.energyDetails.basePrice!=null&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Grundpreis"}),i.jsxs("dd",{children:[A.energyDetails.basePrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/Monat"]})]}),A.energyDetails.unitPrice!=null&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Arbeitspreis"}),i.jsxs("dd",{children:[A.energyDetails.unitPrice.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:10})," €/kWh"]})]}),A.energyDetails.bonus&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Bonus"}),i.jsxs("dd",{children:[A.energyDetails.bonus.toLocaleString("de-DE")," €"]})]}),A.energyDetails.previousProviderName&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversorger"}),i.jsx("dd",{children:A.energyDetails.previousProviderName})]}),A.energyDetails.previousCustomerNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vorherige Kundennr."}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.energyDetails.previousCustomerNumber,i.jsx(de,{value:A.energyDetails.previousCustomerNumber})]})]})]}),A.energyDetails.meter&&i.jsx(f3,{meterId:A.energyDetails.meter.id,meterType:A.energyDetails.meter.type,readings:A.energyDetails.meter.readings||[],contractId:c,canEdit:a("contracts:update")&&!l}),A.energyDetails.meter&&A.startDate&&A.endDate&&i.jsx(p3,{contractType:A.type,readings:A.energyDetails.meter.readings||[],startDate:A.startDate,endDate:A.endDate,basePrice:A.energyDetails.basePrice,unitPrice:A.energyDetails.unitPrice,bonus:A.energyDetails.bonus}),i.jsx(e3,{ecdId:A.energyDetails.id,invoices:A.energyDetails.invoices||[],contractId:c,canEdit:a("contracts:update")&&!l})]}),A.internetDetails&&i.jsxs(Z,{className:"mb-6",title:A.type==="DSL"?"DSL-Details":A.type==="CABLE"?"Kabelinternet-Details":"Glasfaser-Details",children:[i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[A.internetDetails.downloadSpeed&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Download"}),i.jsxs("dd",{children:[A.internetDetails.downloadSpeed," Mbit/s"]})]}),A.internetDetails.uploadSpeed&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Upload"}),i.jsxs("dd",{children:[A.internetDetails.uploadSpeed," Mbit/s"]})]}),A.internetDetails.routerModel&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Router"}),i.jsx("dd",{children:A.internetDetails.routerModel})]}),A.internetDetails.routerSerialNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Router S/N"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.internetDetails.routerSerialNumber,i.jsx(de,{value:A.internetDetails.routerSerialNumber})]})]}),A.internetDetails.installationDate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Installation"}),i.jsx("dd",{children:new Date(A.internetDetails.installationDate).toLocaleDateString("de-DE")})]}),A.internetDetails.homeId&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Home-ID"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.internetDetails.homeId,i.jsx(de,{value:A.internetDetails.homeId})]})]}),A.internetDetails.activationCode&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Aktivierungscode"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.internetDetails.activationCode,i.jsx(de,{value:A.internetDetails.activationCode})]})]})]}),(A.internetDetails.internetUsername||A.internetDetails.internetPasswordEncrypted)&&i.jsxs("div",{className:"mt-4 pt-4 border-t",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Internet-Zugangsdaten"}),i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[A.internetDetails.internetUsername&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Benutzername"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.internetDetails.internetUsername,i.jsx(de,{value:A.internetDetails.internetUsername})]})]}),A.internetDetails.internetPasswordEncrypted&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Passwort"}),i.jsxs("dd",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"font-mono",children:g&&y?y:"••••••••"}),g&&y&&i.jsx(de,{value:y}),i.jsx(I,{variant:"ghost",size:"sm",onClick:Je,children:g?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]})]})]}),A.internetDetails.phoneNumbers&&A.internetDetails.phoneNumbers.length>0&&i.jsxs("div",{className:"mt-4 pt-4 border-t",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Rufnummern & SIP-Zugangsdaten"}),i.jsx("div",{className:"space-y-3",children:A.internetDetails.phoneNumbers.map(J=>i.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsxs("span",{className:"font-mono font-medium flex items-center gap-1",children:[J.phoneNumber,i.jsx(de,{value:J.phoneNumber})]}),J.isMain&&i.jsx(je,{variant:"success",children:"Hauptnummer"})]}),(J.sipUsername||J.sipPasswordEncrypted||J.sipServer)&&i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-sm",children:[J.sipUsername&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"SIP-Benutzer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[J.sipUsername,i.jsx(de,{value:J.sipUsername})]})]}),J.sipPasswordEncrypted&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"SIP-Passwort"}),i.jsxs("dd",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"font-mono",children:b[J.id]&&k[J.id]?k[J.id]:"••••••••"}),b[J.id]&&k[J.id]&&i.jsx(de,{value:k[J.id]}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>et(J.id),children:b[J.id]?i.jsx(on,{className:"w-3 h-3"}):i.jsx(Oe,{className:"w-3 h-3"})})]})]}),J.sipServer&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"SIP-Server"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[J.sipServer,i.jsx(de,{value:J.sipServer})]})]})]})]},J.id))})]})]}),A.mobileDetails&&i.jsxs(Z,{className:"mb-6",title:"Mobilfunk-Details",children:[i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[A.mobileDetails.dataVolume&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Datenvolumen"}),i.jsxs("dd",{children:[A.mobileDetails.dataVolume," GB"]})]}),A.mobileDetails.includedMinutes&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-Minuten"}),i.jsx("dd",{children:A.mobileDetails.includedMinutes})]}),A.mobileDetails.includedSMS&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Inklusiv-SMS"}),i.jsx("dd",{children:A.mobileDetails.includedSMS})]}),A.mobileDetails.deviceModel&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Gerät"}),i.jsx("dd",{children:A.mobileDetails.deviceModel})]}),A.mobileDetails.deviceImei&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"IMEI"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.mobileDetails.deviceImei,i.jsx(de,{value:A.mobileDetails.deviceImei})]})]}),A.mobileDetails.requiresMultisim&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Multisim"}),i.jsx("dd",{children:i.jsx(je,{variant:"warning",children:"Erforderlich"})})]})]}),A.mobileDetails.simCards&&A.mobileDetails.simCards.length>0&&i.jsxs("div",{className:"mt-6 pt-6 border-t",children:[i.jsx("h4",{className:"font-medium mb-4",children:"SIM-Karten"}),i.jsx("div",{className:"space-y-3",children:A.mobileDetails.simCards.map(J=>i.jsx(h3,{simCard:J},J.id))})]}),(!A.mobileDetails.simCards||A.mobileDetails.simCards.length===0)&&(A.mobileDetails.phoneNumber||A.mobileDetails.simCardNumber)&&i.jsxs("div",{className:"mt-6 pt-6 border-t",children:[i.jsx("h4",{className:"font-medium mb-4",children:"SIM-Karte (Legacy)"}),i.jsxs("dl",{className:"grid grid-cols-2 gap-4",children:[A.mobileDetails.phoneNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Rufnummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.mobileDetails.phoneNumber,i.jsx(de,{value:A.mobileDetails.phoneNumber})]})]}),A.mobileDetails.simCardNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"SIM-Kartennummer"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.mobileDetails.simCardNumber,i.jsx(de,{value:A.mobileDetails.simCardNumber})]})]})]})]})]}),A.tvDetails&&i.jsx(Z,{className:"mb-6",title:"TV-Details",children:i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[A.tvDetails.receiverModel&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Receiver"}),i.jsx("dd",{children:A.tvDetails.receiverModel})]}),A.tvDetails.smartcardNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Smartcard"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.tvDetails.smartcardNumber,i.jsx(de,{value:A.tvDetails.smartcardNumber})]})]}),A.tvDetails.package&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Paket"}),i.jsx("dd",{children:A.tvDetails.package})]})]})}),A.carInsuranceDetails&&i.jsx(Z,{className:"mb-6",title:"KFZ-Versicherung Details",children:i.jsxs("dl",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[A.carInsuranceDetails.licensePlate&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Kennzeichen"}),i.jsxs("dd",{className:"font-mono font-bold flex items-center gap-1",children:[A.carInsuranceDetails.licensePlate,i.jsx(de,{value:A.carInsuranceDetails.licensePlate})]})]}),A.carInsuranceDetails.vehicleType&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Fahrzeug"}),i.jsx("dd",{children:A.carInsuranceDetails.vehicleType})]}),A.carInsuranceDetails.hsn&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"HSN/TSN"}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.carInsuranceDetails.hsn,"/",A.carInsuranceDetails.tsn,i.jsx(de,{value:`${A.carInsuranceDetails.hsn}/${A.carInsuranceDetails.tsn}`})]})]}),A.carInsuranceDetails.vin&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"FIN"}),i.jsxs("dd",{className:"font-mono text-sm flex items-center gap-1",children:[A.carInsuranceDetails.vin,i.jsx(de,{value:A.carInsuranceDetails.vin})]})]}),A.carInsuranceDetails.firstRegistration&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Erstzulassung"}),i.jsx("dd",{children:new Date(A.carInsuranceDetails.firstRegistration).toLocaleDateString("de-DE")})]}),A.carInsuranceDetails.noClaimsClass&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"SF-Klasse"}),i.jsx("dd",{children:A.carInsuranceDetails.noClaimsClass})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Versicherungsart"}),i.jsx("dd",{children:i.jsx(je,{variant:A.carInsuranceDetails.insuranceType==="FULL"?"success":A.carInsuranceDetails.insuranceType==="PARTIAL"?"warning":"default",children:A.carInsuranceDetails.insuranceType==="FULL"?"Vollkasko":A.carInsuranceDetails.insuranceType==="PARTIAL"?"Teilkasko":"Haftpflicht"})})]}),A.carInsuranceDetails.deductiblePartial&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"SB Teilkasko"}),i.jsxs("dd",{children:[A.carInsuranceDetails.deductiblePartial," €"]})]}),A.carInsuranceDetails.deductibleFull&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"SB Vollkasko"}),i.jsxs("dd",{children:[A.carInsuranceDetails.deductibleFull," €"]})]}),A.carInsuranceDetails.policyNumber&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Versicherungsschein-Nr."}),i.jsxs("dd",{className:"font-mono flex items-center gap-1",children:[A.carInsuranceDetails.policyNumber,i.jsx(de,{value:A.carInsuranceDetails.policyNumber})]})]}),A.carInsuranceDetails.previousInsurer&&i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Vorversicherer"}),i.jsx("dd",{children:A.carInsuranceDetails.previousInsurer})]})]})}),i.jsx(g3,{contractId:c,canEdit:a("contracts:update"),isCustomerPortal:o}),!o&&a("contracts:read")&&A.customerId&&i.jsx(iR,{contractId:c,customerId:A.customerId}),A.notes&&i.jsx(Z,{title:"Notizen",children:i.jsx("p",{className:"whitespace-pre-wrap",children:A.notes})}),!o&&a("contracts:read")&&i.jsx(YR,{contractId:c,canEdit:a("contracts:update")}),T&&A.previousContract&&i.jsx(ZR,{contractId:A.previousContract.id,isOpen:!0,onClose:()=>w(!1)}),i.jsx(Xe,{isOpen:S,onClose:()=>M(!1),title:"Folgevertrag anlegen",size:"sm",children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-gray-700",children:"Möchten Sie wirklich einen Folgevertrag für diesen Vertrag anlegen?"}),i.jsx("p",{className:"text-sm text-gray-500",children:"Die Daten des aktuellen Vertrags werden als Vorlage übernommen."}),i.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[i.jsx(I,{variant:"secondary",onClick:()=>M(!1),children:"Nein"}),i.jsx(I,{onClick:()=>{M(!1),K.mutate()},children:"Ja, anlegen"})]})]})}),i.jsx(d3,{isOpen:F,onClose:()=>R(!1)}),i.jsx(Xe,{isOpen:V,onClose:()=>D(!1),title:"Zurückstellung aufheben?",children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-gray-700",children:"Möchten Sie die Zurückstellung für diesen Vertrag wirklich aufheben?"}),i.jsx("p",{className:"text-sm text-gray-500",children:"Der Vertrag wird danach wieder im Cockpit angezeigt, wenn Fristen anstehen oder abgelaufen sind."}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:()=>D(!1),children:"Abbrechen"}),i.jsx(I,{variant:"danger",onClick:()=>B.mutate(),disabled:B.isPending,children:B.isPending?"Wird aufgehoben...":"Ja, aufheben"})]})]})})]})}const v3=[{value:"DRAFT",label:"Entwurf"},{value:"PENDING",label:"Ausstehend"},{value:"ACTIVE",label:"Aktiv"},{value:"CANCELLED",label:"Gekündigt"},{value:"EXPIRED",label:"Abgelaufen"},{value:"DEACTIVATED",label:"Deaktiviert"}],b3=[{status:"DRAFT",label:"Entwurf",description:"Vertrag wird noch vorbereitet",color:"text-gray-600"},{status:"PENDING",label:"Ausstehend",description:"Wartet auf Aktivierung",color:"text-yellow-600"},{status:"ACTIVE",label:"Aktiv",description:"Vertrag läuft normal",color:"text-green-600"},{status:"EXPIRED",label:"Abgelaufen",description:"Laufzeit vorbei, läuft aber ohne Kündigung weiter",color:"text-orange-600"},{status:"CANCELLED",label:"Gekündigt",description:"Aktive Kündigung eingereicht, Vertrag endet",color:"text-red-600"},{status:"DEACTIVATED",label:"Deaktiviert",description:"Manuell beendet/archiviert",color:"text-gray-500"}];function j3({isOpen:t,onClose:e}){return t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"fixed inset-0 bg-black/20",onClick:e}),i.jsxs("div",{className:"relative bg-white rounded-lg shadow-xl p-4 max-w-sm w-full mx-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-gray-900",children:"Vertragsstatus-Übersicht"}),i.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-600",children:i.jsx(nn,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"space-y-2",children:b3.map(({status:n,label:s,description:r,color:a})=>i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:`font-medium text-sm min-w-[90px] ${a}`,children:s}),i.jsx("span",{className:"text-sm text-gray-600",children:r})]},n))})]})]}):null}function X1(){var jo,Ad,No,R0,O0,L0,F0,z0,$0;const{id:t}=md(),[e]=Sf(),n=fn(),s=ye(),r=!!t,a=e.get("customerId"),{register:l,handleSubmit:o,reset:c,watch:d,setValue:u,formState:{errors:h}}=$C({defaultValues:{customerId:a||"",type:"ELECTRICITY",status:"DRAFT",previousContractId:""}}),m=d("type"),f=d("customerId"),p=d("previousContractId"),{data:g}=fe({queryKey:["contract",t],queryFn:()=>He.getById(parseInt(t)),enabled:r}),{data:x}=fe({queryKey:["customers-all"],queryFn:()=>Zt.getAll({limit:1e3})}),{data:y}=fe({queryKey:["customer",f],queryFn:()=>Zt.getById(parseInt(f)),enabled:!!f}),{data:v}=fe({queryKey:["customer-contracts-for-predecessor",f],queryFn:()=>He.getAll({customerId:parseInt(f),limit:1e3}),enabled:!!f}),{data:b}=fe({queryKey:["platforms"],queryFn:()=>Fc.getAll()}),{data:j}=fe({queryKey:["cancellation-periods"],queryFn:()=>zc.getAll()}),{data:k}=fe({queryKey:["contract-durations"],queryFn:()=>$c.getAll()}),{data:E}=fe({queryKey:["providers"],queryFn:()=>to.getAll()}),{data:T}=fe({queryKey:["contract-categories"],queryFn:()=>Bc.getAll()}),w=d("providerId"),[S,M]=N.useState(null),[F,R]=N.useState([]),[V,D]=N.useState([]),[z,C]=N.useState(!1),[_,K]=N.useState("manual"),[B,W]=N.useState(""),[ce,he]=N.useState(!1),[Je,et]=N.useState(!1),[mt,A]=N.useState({}),[pt,On]=N.useState({}),[wn,le]=N.useState({}),[it,Rt]=N.useState(!1);N.useEffect(()=>{r||C(!0)},[r]),N.useEffect(()=>{!r&&a&&(x!=null&&x.data)&&x.data.some(oe=>oe.id.toString()===a)&&u("customerId",a)},[r,a,x,u]),N.useEffect(()=>{z&&S&&w!==S&&u("tariffId",""),M(w)},[w,S,u,z]),N.useEffect(()=>{if(!r&&(T!=null&&T.data)&&T.data.length>0){const O=d("type"),oe=T.data.filter(ve=>ve.isActive),Ae=oe.some(ve=>ve.code===O);if(!O||!Ae){const ve=oe.sort((Se,wt)=>Se.sortOrder-wt.sortOrder)[0];ve&&u("type",ve.code)}}},[T,r,u,d]),N.useEffect(()=>{r&&(g!=null&&g.data)&&!f&&u("customerId",g.data.customerId.toString())},[r,g,f,u]),N.useEffect(()=>{var O,oe,Ae,ve,Se,wt,Re,wo,B0,_0,V0,K0,U0,q0,H0,W0,Q0,G0,J0,Z0,Y0,X0,ev,tv,nv,sv,rv,iv,av,lv,ov,cv,dv,uv,hv,fv,mv,pv,gv,xv,yv,vv,bv,jv,Nv,wv,kv,Sv,Cv,Ev,Av,Dv;if(g!=null&&g.data&&(b!=null&&b.data)&&(T!=null&&T.data)&&(E!=null&&E.data)&&(y!=null&&y.data)){const ae=g.data;c({customerId:ae.customerId.toString(),type:ae.type,status:ae.status,addressId:((O=ae.addressId)==null?void 0:O.toString())||"",billingAddressId:((oe=ae.billingAddressId)==null?void 0:oe.toString())||"",bankCardId:((Ae=ae.bankCardId)==null?void 0:Ae.toString())||"",identityDocumentId:((ve=ae.identityDocumentId)==null?void 0:ve.toString())||"",salesPlatformId:((Se=ae.salesPlatformId)==null?void 0:Se.toString())||"",providerId:((wt=ae.providerId)==null?void 0:wt.toString())||"",tariffId:((Re=ae.tariffId)==null?void 0:Re.toString())||"",providerName:ae.providerName||"",tariffName:ae.tariffName||"",customerNumberAtProvider:ae.customerNumberAtProvider||"",contractNumberAtProvider:ae.contractNumberAtProvider||"",priceFirst12Months:ae.priceFirst12Months||"",priceFrom13Months:ae.priceFrom13Months||"",priceAfter24Months:ae.priceAfter24Months||"",startDate:ae.startDate?ae.startDate.split("T")[0]:"",endDate:ae.endDate?ae.endDate.split("T")[0]:"",cancellationPeriodId:((wo=ae.cancellationPeriodId)==null?void 0:wo.toString())||"",contractDurationId:((B0=ae.contractDurationId)==null?void 0:B0.toString())||"",commission:ae.commission||"",portalUsername:ae.portalUsername||"",notes:ae.notes||"",meterId:((V0=(_0=ae.energyDetails)==null?void 0:_0.meterId)==null?void 0:V0.toString())||"",maloId:((K0=ae.energyDetails)==null?void 0:K0.maloId)||"",annualConsumption:((U0=ae.energyDetails)==null?void 0:U0.annualConsumption)||"",annualConsumptionKwh:((q0=ae.energyDetails)==null?void 0:q0.annualConsumptionKwh)||"",basePrice:((H0=ae.energyDetails)==null?void 0:H0.basePrice)||"",unitPrice:((W0=ae.energyDetails)==null?void 0:W0.unitPrice)||"",bonus:((Q0=ae.energyDetails)==null?void 0:Q0.bonus)||"",downloadSpeed:((G0=ae.internetDetails)==null?void 0:G0.downloadSpeed)||"",uploadSpeed:((J0=ae.internetDetails)==null?void 0:J0.uploadSpeed)||"",routerModel:((Z0=ae.internetDetails)==null?void 0:Z0.routerModel)||"",routerSerialNumber:((Y0=ae.internetDetails)==null?void 0:Y0.routerSerialNumber)||"",installationDate:(X0=ae.internetDetails)!=null&&X0.installationDate?ae.internetDetails.installationDate.split("T")[0]:"",internetUsername:((ev=ae.internetDetails)==null?void 0:ev.internetUsername)||"",homeId:((tv=ae.internetDetails)==null?void 0:tv.homeId)||"",activationCode:((nv=ae.internetDetails)==null?void 0:nv.activationCode)||"",requiresMultisim:((sv=ae.mobileDetails)==null?void 0:sv.requiresMultisim)||!1,dataVolume:((rv=ae.mobileDetails)==null?void 0:rv.dataVolume)||"",includedMinutes:((iv=ae.mobileDetails)==null?void 0:iv.includedMinutes)||"",includedSMS:((av=ae.mobileDetails)==null?void 0:av.includedSMS)||"",deviceModel:((lv=ae.mobileDetails)==null?void 0:lv.deviceModel)||"",deviceImei:((ov=ae.mobileDetails)==null?void 0:ov.deviceImei)||"",phoneNumber:((cv=ae.mobileDetails)==null?void 0:cv.phoneNumber)||"",simCardNumber:((dv=ae.mobileDetails)==null?void 0:dv.simCardNumber)||"",receiverModel:((uv=ae.tvDetails)==null?void 0:uv.receiverModel)||"",smartcardNumber:((hv=ae.tvDetails)==null?void 0:hv.smartcardNumber)||"",tvPackage:((fv=ae.tvDetails)==null?void 0:fv.package)||"",licensePlate:((mv=ae.carInsuranceDetails)==null?void 0:mv.licensePlate)||"",hsn:((pv=ae.carInsuranceDetails)==null?void 0:pv.hsn)||"",tsn:((gv=ae.carInsuranceDetails)==null?void 0:gv.tsn)||"",vin:((xv=ae.carInsuranceDetails)==null?void 0:xv.vin)||"",vehicleType:((yv=ae.carInsuranceDetails)==null?void 0:yv.vehicleType)||"",firstRegistration:(vv=ae.carInsuranceDetails)!=null&&vv.firstRegistration?ae.carInsuranceDetails.firstRegistration.split("T")[0]:"",noClaimsClass:((bv=ae.carInsuranceDetails)==null?void 0:bv.noClaimsClass)||"",insuranceType:((jv=ae.carInsuranceDetails)==null?void 0:jv.insuranceType)||"LIABILITY",deductiblePartial:((Nv=ae.carInsuranceDetails)==null?void 0:Nv.deductiblePartial)||"",deductibleFull:((wv=ae.carInsuranceDetails)==null?void 0:wv.deductibleFull)||"",policyNumber:((kv=ae.carInsuranceDetails)==null?void 0:kv.policyNumber)||"",previousInsurer:((Sv=ae.carInsuranceDetails)==null?void 0:Sv.previousInsurer)||"",cancellationConfirmationDate:ae.cancellationConfirmationDate?ae.cancellationConfirmationDate.split("T")[0]:"",cancellationConfirmationOptionsDate:ae.cancellationConfirmationOptionsDate?ae.cancellationConfirmationOptionsDate.split("T")[0]:"",wasSpecialCancellation:ae.wasSpecialCancellation||!1,previousContractId:((Cv=ae.previousContractId)==null?void 0:Cv.toString())||"",previousProviderId:((Ev=ae.previousProviderId)==null?void 0:Ev.toString())||"",previousCustomerNumber:ae.previousCustomerNumber||"",previousContractNumber:ae.previousContractNumber||""}),(Av=ae.mobileDetails)!=null&&Av.simCards&&ae.mobileDetails.simCards.length>0?R(ae.mobileDetails.simCards.map(Fn=>({id:Fn.id,phoneNumber:Fn.phoneNumber||"",simCardNumber:Fn.simCardNumber||"",pin:"",puk:"",hasExistingPin:!!Fn.pin,hasExistingPuk:!!Fn.puk,isMultisim:Fn.isMultisim,isMain:Fn.isMain}))):R([]),(Dv=ae.internetDetails)!=null&&Dv.phoneNumbers&&ae.internetDetails.phoneNumbers.length>0?D(ae.internetDetails.phoneNumbers.map(Fn=>({id:Fn.id,phoneNumber:Fn.phoneNumber||"",sipUsername:Fn.sipUsername||"",sipPassword:"",hasExistingSipPassword:!!Fn.sipPasswordEncrypted,sipServer:Fn.sipServer||"",isMain:Fn.isMain}))):D([]),ae.stressfreiEmailId?(K("stressfrei"),W(ae.stressfreiEmailId.toString())):(K("manual"),W("")),C(!0)}},[g,c,b,T,E,y]);const J=d("startDate"),Ke=d("contractDurationId");N.useEffect(()=>{if(J&&Ke&&(k!=null&&k.data)){const O=k.data.find(oe=>oe.id===parseInt(Ke));if(O){const oe=new Date(J),ve=O.code.match(/^(\d+)([MTJ])$/);if(ve){const Se=parseInt(ve[1]),wt=ve[2];let Re=new Date(oe);wt==="T"?Re.setDate(Re.getDate()+Se):wt==="M"?Re.setMonth(Re.getMonth()+Se):wt==="J"&&Re.setFullYear(Re.getFullYear()+Se),u("endDate",Re.toISOString().split("T")[0])}}}},[J,Ke,k,u]);const ct=G({mutationFn:He.create,onSuccess:(O,oe)=>{s.invalidateQueries({queryKey:["contracts"]}),oe.customerId&&s.invalidateQueries({queryKey:["customer",oe.customerId.toString()]}),s.invalidateQueries({queryKey:["customers"]}),n(a?`/customers/${a}?tab=contracts`:"/contracts")}}),ee=G({mutationFn:O=>He.update(parseInt(t),O),onSuccess:(O,oe)=>{s.invalidateQueries({queryKey:["contracts"]}),s.invalidateQueries({queryKey:["contract",t]}),oe.customerId&&s.invalidateQueries({queryKey:["customer",oe.customerId.toString()]}),s.invalidateQueries({queryKey:["customers"]}),n(`/contracts/${t}`)}}),pe=O=>{const oe=Re=>{if(Re==null||Re==="")return;const wo=parseInt(String(Re));return isNaN(wo)?void 0:wo},Ae=Wt.find(Re=>Re.code===O.type),ve=oe(O.customerId);if(!ve){alert("Bitte wählen Sie einen Kunden aus");return}if(!O.type||!Ae){alert("Bitte wählen Sie einen Vertragstyp aus");return}const Se=Re=>Re==null||Re===""?null:Re,wt={customerId:ve,type:O.type,contractCategoryId:Ae.id,status:O.status,addressId:oe(O.addressId)??null,billingAddressId:oe(O.billingAddressId)??null,bankCardId:oe(O.bankCardId)??null,identityDocumentId:oe(O.identityDocumentId)??null,salesPlatformId:oe(O.salesPlatformId)??null,providerId:oe(O.providerId)??null,tariffId:oe(O.tariffId)??null,providerName:Se(O.providerName),tariffName:Se(O.tariffName),customerNumberAtProvider:Se(O.customerNumberAtProvider),contractNumberAtProvider:Se(O.contractNumberAtProvider),priceFirst12Months:Se(O.priceFirst12Months),priceFrom13Months:Se(O.priceFrom13Months),priceAfter24Months:Se(O.priceAfter24Months),startDate:O.startDate?new Date(O.startDate):null,endDate:O.endDate?new Date(O.endDate):null,cancellationPeriodId:oe(O.cancellationPeriodId)??null,contractDurationId:oe(O.contractDurationId)??null,commission:O.commission?parseFloat(O.commission):null,portalUsername:_==="manual"?Se(O.portalUsername):null,stressfreiEmailId:_==="stressfrei"&&B?parseInt(B):null,portalPassword:O.portalPassword||void 0,notes:Se(O.notes),cancellationConfirmationDate:O.cancellationConfirmationDate?new Date(O.cancellationConfirmationDate):null,cancellationConfirmationOptionsDate:O.cancellationConfirmationOptionsDate?new Date(O.cancellationConfirmationOptionsDate):null,wasSpecialCancellation:O.wasSpecialCancellation||!1,previousContractId:oe(O.previousContractId)??null,previousProviderId:O.previousContractId?null:oe(O.previousProviderId)??null,previousCustomerNumber:O.previousContractId?null:Se(O.previousCustomerNumber),previousContractNumber:O.previousContractId?null:Se(O.previousContractNumber)};["ELECTRICITY","GAS"].includes(O.type)&&(wt.energyDetails={meterId:oe(O.meterId)??null,maloId:Se(O.maloId),annualConsumption:O.annualConsumption?parseFloat(O.annualConsumption):null,annualConsumptionKwh:O.annualConsumptionKwh?parseFloat(O.annualConsumptionKwh):null,basePrice:O.basePrice?parseFloat(O.basePrice):null,unitPrice:O.unitPrice?parseFloat(O.unitPrice):null,bonus:O.bonus?parseFloat(O.bonus):null}),["DSL","CABLE","FIBER"].includes(O.type)&&(wt.internetDetails={downloadSpeed:oe(O.downloadSpeed)??null,uploadSpeed:oe(O.uploadSpeed)??null,routerModel:Se(O.routerModel),routerSerialNumber:Se(O.routerSerialNumber),installationDate:O.installationDate?new Date(O.installationDate):null,internetUsername:Se(O.internetUsername),internetPassword:O.internetPassword||void 0,homeId:Se(O.homeId),activationCode:Se(O.activationCode),phoneNumbers:V.length>0?V.map(Re=>({id:Re.id,phoneNumber:Re.phoneNumber||"",isMain:Re.isMain??!1,sipUsername:Se(Re.sipUsername),sipPassword:Re.sipPassword||void 0,sipServer:Se(Re.sipServer)})):void 0}),O.type==="MOBILE"&&(wt.mobileDetails={requiresMultisim:O.requiresMultisim||!1,dataVolume:O.dataVolume?parseFloat(O.dataVolume):null,includedMinutes:oe(O.includedMinutes)??null,includedSMS:oe(O.includedSMS)??null,deviceModel:Se(O.deviceModel),deviceImei:Se(O.deviceImei),phoneNumber:Se(O.phoneNumber),simCardNumber:Se(O.simCardNumber),simCards:F.length>0?F.map(Re=>({id:Re.id,phoneNumber:Se(Re.phoneNumber),simCardNumber:Se(Re.simCardNumber),pin:Re.pin||void 0,puk:Re.puk||void 0,isMultisim:Re.isMultisim,isMain:Re.isMain})):void 0}),O.type==="TV"&&(wt.tvDetails={receiverModel:Se(O.receiverModel),smartcardNumber:Se(O.smartcardNumber),package:Se(O.tvPackage)}),O.type==="CAR_INSURANCE"&&(wt.carInsuranceDetails={licensePlate:Se(O.licensePlate),hsn:Se(O.hsn),tsn:Se(O.tsn),vin:Se(O.vin),vehicleType:Se(O.vehicleType),firstRegistration:O.firstRegistration?new Date(O.firstRegistration):null,noClaimsClass:Se(O.noClaimsClass),insuranceType:O.insuranceType,deductiblePartial:O.deductiblePartial?parseFloat(O.deductiblePartial):null,deductibleFull:O.deductibleFull?parseFloat(O.deductibleFull):null,policyNumber:Se(O.policyNumber),previousInsurer:Se(O.previousInsurer)}),r?ee.mutate(wt):ct.mutate(wt)},Ln=ct.isPending||ee.isPending,ur=ct.error||ee.error,Ot=y==null?void 0:y.data,L=(Ot==null?void 0:Ot.addresses)||[],U=((jo=Ot==null?void 0:Ot.bankCards)==null?void 0:jo.filter(O=>O.isActive))||[],Q=((Ad=Ot==null?void 0:Ot.identityDocuments)==null?void 0:Ad.filter(O=>O.isActive))||[],ue=((No=Ot==null?void 0:Ot.meters)==null?void 0:No.filter(O=>O.isActive))||[],ie=((R0=Ot==null?void 0:Ot.stressfreiEmails)==null?void 0:R0.filter(O=>O.isActive))||[],se=(b==null?void 0:b.data)||[],Ne=(j==null?void 0:j.data)||[],qe=(k==null?void 0:k.data)||[],_e=((O0=E==null?void 0:E.data)==null?void 0:O0.filter(O=>O.isActive))||[],Wt=((L0=T==null?void 0:T.data)==null?void 0:L0.filter(O=>O.isActive).sort((O,oe)=>O.sortOrder-oe.sortOrder))||[],hr=Wt.map(O=>({value:O.code,label:O.name})),qs=((v==null?void 0:v.data)||[]).filter(O=>!r||O.id!==parseInt(t)).sort((O,oe)=>new Date(oe.startDate||0).getTime()-new Date(O.startDate||0).getTime()),Wr=_e.find(O=>O.id===parseInt(w||"0")),bo=((F0=Wr==null?void 0:Wr.tariffs)==null?void 0:F0.filter(O=>O.isActive))||[],Ya=O=>{const oe=O.companyName||`${O.firstName} ${O.lastName}`,Ae=O.birthDate?` (geb. ${new Date(O.birthDate).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})})`:"";return`${O.customerNumber} - ${oe}${Ae}`},Xf=(()=>{var Ae;const oe=((x==null?void 0:x.data)||[]).map(ve=>({value:ve.id.toString(),label:Ya(ve)}));if(r&&((Ae=g==null?void 0:g.data)!=null&&Ae.customer)){const ve=g.data.customer;oe.some(wt=>wt.value===ve.id.toString())||oe.unshift({value:ve.id.toString(),label:Ya(ve)})}return oe})();return i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold mb-6",children:r?"Vertrag bearbeiten":"Neuer Vertrag"}),ur&&i.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg",children:ur instanceof Error?ur.message:"Ein Fehler ist aufgetreten"}),i.jsxs("form",{onSubmit:o(pe),children:[i.jsx(Z,{className:"mb-6",title:"Vertragsdaten",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(Fe,{label:"Kunde *",...l("customerId",{required:"Kunde erforderlich"}),options:Xf,error:(z0=h.customerId)==null?void 0:z0.message}),i.jsx(Fe,{label:"Vertragstyp *",...l("type",{required:"Typ erforderlich"}),options:hr}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Status"}),i.jsx("button",{type:"button",onClick:()=>Rt(!0),className:"text-gray-400 hover:text-blue-600 transition-colors",title:"Status-Erklärung",children:i.jsx(bd,{className:"w-4 h-4"})})]}),i.jsx(Fe,{...l("status"),options:v3})]}),i.jsx(Fe,{label:"Vertriebsplattform",...l("salesPlatformId"),options:se.map(O=>({value:O.id,label:O.name}))}),f&&i.jsx(Fe,{label:"Vorgänger-Vertrag",...l("previousContractId"),options:qs.map(O=>({value:O.id,label:`${O.contractNumber} (${O.type}${O.startDate?` - ${new Date(O.startDate).toLocaleDateString("de-DE")}`:""})`})),placeholder:"Keinen Vorgänger auswählen"}),f&&!p&&i.jsxs("div",{className:"mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"Altanbieter-Daten"}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(Fe,{label:"Altanbieter",...l("previousProviderId"),options:_e.map(O=>({value:O.id,label:O.name})),placeholder:"Bitte wählen..."}),i.jsx(q,{label:"Kundennr. beim Altanbieter",...l("previousCustomerNumber")}),i.jsx(q,{label:"Vertragsnr. beim Altanbieter",...l("previousContractNumber")})]})]})]})}),f&&i.jsxs(Z,{className:"mb-6",title:"Kundendaten verknüpfen",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[i.jsx(Fe,{label:"Lieferadresse",...l("addressId"),options:L.filter(O=>O.type==="DELIVERY_RESIDENCE").map(O=>({value:O.id,label:`${O.street} ${O.houseNumber}, ${O.postalCode} ${O.city}`}))}),i.jsx(Fe,{label:"Rechnungsadresse",...l("billingAddressId"),options:L.filter(O=>O.type==="BILLING").map(O=>({value:O.id,label:`${O.street} ${O.houseNumber}, ${O.postalCode} ${O.city}`})),placeholder:"Wie Lieferadresse"})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(Fe,{label:"Bankkarte",...l("bankCardId"),options:U.map(O=>({value:O.id,label:`${O.iban} (${O.accountHolder})`}))}),i.jsx(Fe,{label:"Ausweis",...l("identityDocumentId"),options:Q.map(O=>({value:O.id,label:`${O.documentNumber} (${O.type})`}))})]})]}),i.jsx(Z,{className:"mb-6",title:"Anbieter & Tarif",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(Fe,{label:"Anbieter",...l("providerId"),options:_e.map(O=>({value:O.id,label:O.name}))}),i.jsx(Fe,{label:"Tarif",...l("tariffId"),options:bo.map(O=>({value:O.id,label:O.name})),disabled:!w}),i.jsx(q,{label:"Kundennummer beim Anbieter",...l("customerNumberAtProvider")}),i.jsx(q,{label:"Vertragsnummer beim Anbieter",...l("contractNumberAtProvider")}),i.jsx(q,{label:"Provision (€)",type:"number",step:"0.01",...l("commission")}),i.jsx(q,{label:"Preis erste 12 Monate",...l("priceFirst12Months"),placeholder:"z.B. 29,99 €/Monat"}),i.jsx(q,{label:"Preis ab 13. Monat",...l("priceFrom13Months"),placeholder:"z.B. 39,99 €/Monat"}),i.jsx(q,{label:"Preis nach 24 Monaten",...l("priceAfter24Months"),placeholder:"z.B. 49,99 €/Monat"})]})}),i.jsxs(Z,{className:"mb-6",title:"Laufzeit und Kündigung",children:[i.jsxs("p",{className:"text-sm text-gray-500 mb-4 bg-blue-50 border border-blue-200 rounded-lg p-3",children:[i.jsx("strong",{children:"Hinweis:"})," Ist die Laufzeit ≤ 4 Wochen, 1 Monat oder 30 Tage, gilt der Vertrag als unbefristet mit der jeweiligen Kündigungsfrist."]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(q,{label:"Vertragsbeginn",type:"date",...l("startDate"),value:d("startDate")||"",onClear:()=>u("startDate","")}),i.jsx(q,{label:"Vertragsende (berechnet)",type:"date",...l("endDate"),disabled:!0,className:"bg-gray-50"}),i.jsx(Fe,{label:"Vertragslaufzeit",...l("contractDurationId"),options:qe.map(O=>({value:O.id,label:O.description}))}),i.jsx(Fe,{label:"Kündigungsfrist",...l("cancellationPeriodId"),options:Ne.map(O=>({value:O.id,label:O.description}))}),i.jsx(q,{label:"Kündigungsbestätigungsdatum",type:"date",...l("cancellationConfirmationDate"),value:d("cancellationConfirmationDate")||"",onClear:()=>u("cancellationConfirmationDate","")}),i.jsx(q,{label:"Kündigungsbestätigungsoptionendatum",type:"date",...l("cancellationConfirmationOptionsDate"),value:d("cancellationConfirmationOptionsDate")||"",onClear:()=>u("cancellationConfirmationOptionsDate","")}),i.jsx("div",{className:"col-span-2",children:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",...l("wasSpecialCancellation"),className:"rounded border-gray-300"}),i.jsx("span",{children:"Wurde sondergekündigt?"})]})})]})]}),i.jsx(Z,{className:"mb-6",title:"Zugangsdaten (verschlüsselt gespeichert)",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Portal Benutzername"}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"radio",name:"usernameType",checked:_==="manual",onChange:()=>{K("manual"),W("")},className:"text-blue-600"}),i.jsx("span",{className:"text-sm",children:"Manuell eingeben"})]}),_==="manual"&&i.jsx(q,{...l("portalUsername"),placeholder:"Benutzername eingeben..."}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"radio",name:"usernameType",checked:_==="stressfrei",onChange:()=>{K("stressfrei"),u("portalUsername","")},className:"text-blue-600"}),i.jsx("span",{className:"text-sm",children:"Stressfrei-Wechseln Adresse"})]}),_==="stressfrei"&&i.jsx(Fe,{value:B,onChange:O=>W(O.target.value),options:ie.map(O=>({value:O.id,label:O.email+(O.notes?` (${O.notes})`:"")})),placeholder:ie.length===0?"Keine Stressfrei-Adressen vorhanden":"Adresse auswählen..."}),_==="stressfrei"&&ie.length===0&&i.jsx("p",{className:"text-xs text-amber-600",children:"Keine Stressfrei-Wechseln Adressen für diesen Kunden vorhanden. Bitte zuerst beim Kunden anlegen."})]})]}),i.jsxs("div",{className:"mt-8",children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:r?"Neues Passwort (leer lassen = unverändert)":"Portal Passwort"}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:ce?"text":"password",...l("portalPassword"),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),i.jsx("button",{type:"button",onClick:()=>he(!ce),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:ce?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]})]})}),["ELECTRICITY","GAS"].includes(m)&&i.jsxs(Z,{className:"mb-6",title:m==="ELECTRICITY"?"Strom-Details":"Gas-Details",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(Fe,{label:"Zähler",...l("meterId"),options:ue.filter(O=>O.type===m).map(O=>({value:O.id,label:`${O.meterNumber}${O.location?` (${O.location})`:""}`}))}),i.jsx(q,{label:"MaLo-ID (Marktlokations-ID)",...l("maloId")}),i.jsx(q,{label:`Jahresverbrauch (${m==="ELECTRICITY"?"kWh":"m³"})`,type:"number",...l("annualConsumption")}),m==="GAS"&&i.jsx(q,{label:"Jahresverbrauch (kWh)",type:"number",...l("annualConsumptionKwh")}),i.jsx(q,{label:"Grundpreis (€/Monat)",type:"number",step:"any",...l("basePrice")}),i.jsx(q,{label:"Arbeitspreis (€/kWh)",type:"number",step:"any",...l("unitPrice")}),i.jsx(q,{label:"Bonus (€)",type:"number",step:"0.01",...l("bonus")})]}),r&&i.jsxs("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700",children:[i.jsx("strong",{children:"Hinweis:"})," Zählerstände und Rechnungen werden in der"," ",i.jsx("span",{className:"font-medium",children:"Vertragsdetailansicht"})," verwaltet, nicht hier im Bearbeitungsformular."]})]}),["DSL","CABLE","FIBER"].includes(m)&&i.jsxs(i.Fragment,{children:[i.jsx(Z,{className:"mb-6",title:m==="DSL"?"DSL-Details":m==="CABLE"?"Kabelinternet-Details":"Glasfaser-Details",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(q,{label:"Download (Mbit/s)",type:"number",...l("downloadSpeed")}),i.jsx(q,{label:"Upload (Mbit/s)",type:"number",...l("uploadSpeed")}),i.jsx(q,{label:"Router Modell",...l("routerModel")}),i.jsx(q,{label:"Router Seriennummer",...l("routerSerialNumber")}),i.jsx(q,{label:"Installationsdatum",type:"date",...l("installationDate"),value:d("installationDate")||"",onClear:()=>u("installationDate","")}),m==="FIBER"&&i.jsx(q,{label:"Home-ID",...l("homeId")}),(($0=Wr==null?void 0:Wr.name)==null?void 0:$0.toLowerCase().includes("vodafone"))&&["DSL","CABLE"].includes(m)&&i.jsx(q,{label:"Aktivierungscode",...l("activationCode")})]})}),i.jsx(Z,{className:"mb-6",title:"Internet-Zugangsdaten (verschlüsselt)",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(q,{label:"Benutzername",...l("internetUsername")}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:r?"Neues Passwort (leer = beibehalten)":"Passwort"}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:Je?"text":"password",...l("internetPassword"),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),i.jsx("button",{type:"button",onClick:()=>et(!Je),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:Je?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]})]})}),i.jsxs(Z,{className:"mb-6",title:"Rufnummern & SIP-Zugangsdaten",children:[i.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie Festnetz-Rufnummern mit SIP-Zugangsdaten erfassen."}),V.length>0&&i.jsx("div",{className:"space-y-4 mb-4",children:V.map((O,oe)=>i.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50",children:[i.jsxs("div",{className:"flex justify-between items-center mb-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"font-medium",children:["Rufnummer ",oe+1]}),i.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[i.jsx("input",{type:"checkbox",checked:O.isMain,onChange:Ae=>{const ve=[...V];Ae.target.checked?ve.forEach((Se,wt)=>Se.isMain=wt===oe):ve[oe].isMain=!1,D(ve)},className:"rounded border-gray-300"}),"Hauptnummer"]})]}),i.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>{D(V.filter((Ae,ve)=>ve!==oe))},children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[i.jsx(q,{label:"Rufnummer",value:O.phoneNumber,onChange:Ae=>{const ve=[...V];ve[oe].phoneNumber=Ae.target.value,D(ve)},placeholder:"z.B. 030 123456"}),i.jsx(q,{label:"SIP-Benutzername",value:O.sipUsername,onChange:Ae=>{const ve=[...V];ve[oe].sipUsername=Ae.target.value,D(ve)}}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:O.hasExistingSipPassword?"SIP-Passwort (bereits hinterlegt)":"SIP-Passwort"}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:mt[oe]?"text":"password",value:O.sipPassword,onChange:Ae=>{const ve=[...V];ve[oe].sipPassword=Ae.target.value,D(ve)},placeholder:O.hasExistingSipPassword?"Leer = beibehalten":"",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),i.jsx("button",{type:"button",onClick:()=>A(Ae=>({...Ae,[oe]:!Ae[oe]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:mt[oe]?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]}),i.jsx(q,{label:"SIP-Server",value:O.sipServer,onChange:Ae=>{const ve=[...V];ve[oe].sipServer=Ae.target.value,D(ve)},placeholder:"z.B. sip.provider.de"})]})]},oe))}),i.jsxs(I,{type:"button",variant:"secondary",onClick:()=>{D([...V,{phoneNumber:"",sipUsername:"",sipPassword:"",sipServer:"",isMain:V.length===0}])},children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Rufnummer hinzufügen"]})]})]}),m==="MOBILE"&&i.jsxs(i.Fragment,{children:[i.jsxs(Z,{className:"mb-6",title:"Mobilfunk-Details",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(q,{label:"Datenvolumen (GB)",type:"number",...l("dataVolume")}),i.jsx(q,{label:"Inklusiv-Minuten",type:"number",...l("includedMinutes")}),i.jsx(q,{label:"Inklusiv-SMS",type:"number",...l("includedSMS")}),i.jsx(q,{label:"Gerät (Modell)",...l("deviceModel")}),i.jsx(q,{label:"Gerät (IMEI)",...l("deviceImei")})]}),i.jsx("div",{className:"mt-4 pt-4 border-t",children:i.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",...l("requiresMultisim"),className:"mt-1 rounded border-gray-300"}),i.jsxs("div",{children:[i.jsx("span",{className:"font-medium",children:"Multisim erforderlich"}),i.jsx("p",{className:"text-sm text-amber-600 mt-1",children:"Hinweis: Multisim ist bei Klarmobil, Congstar und Otelo nicht buchbar. Muss Freenet oder vergleichbar sein."})]})]})})]}),i.jsxs(Z,{className:"mb-6",title:"SIM-Karten",children:[i.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"Hier können Sie alle SIM-Karten zum Vertrag erfassen (Hauptkarte und Multisim-Karten)."}),F.length>0&&i.jsx("div",{className:"space-y-4 mb-4",children:F.map((O,oe)=>i.jsxs("div",{className:"p-4 border rounded-lg bg-gray-50",children:[i.jsxs("div",{className:"flex justify-between items-center mb-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"font-medium",children:["SIM-Karte ",oe+1]}),i.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[i.jsx("input",{type:"checkbox",checked:O.isMain,onChange:Ae=>{const ve=[...F];Ae.target.checked?ve.forEach((Se,wt)=>Se.isMain=wt===oe):ve[oe].isMain=!1,R(ve)},className:"rounded border-gray-300"}),"Hauptkarte"]}),i.jsxs("label",{className:"flex items-center gap-1 text-sm",children:[i.jsx("input",{type:"checkbox",checked:O.isMultisim,onChange:Ae=>{const ve=[...F];ve[oe].isMultisim=Ae.target.checked,R(ve)},className:"rounded border-gray-300"}),"Multisim"]})]}),i.jsx(I,{type:"button",variant:"ghost",size:"sm",onClick:()=>{R(F.filter((Ae,ve)=>ve!==oe))},children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[i.jsx(q,{label:"Rufnummer",value:O.phoneNumber,onChange:Ae=>{const ve=[...F];ve[oe].phoneNumber=Ae.target.value,R(ve)},placeholder:"z.B. 0171 1234567"}),i.jsx(q,{label:"SIM-Kartennummer",value:O.simCardNumber,onChange:Ae=>{const ve=[...F];ve[oe].simCardNumber=Ae.target.value,R(ve)},placeholder:"ICCID"}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:O.hasExistingPin?"PIN (bereits hinterlegt)":"PIN"}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:pt[oe]?"text":"password",value:O.pin,onChange:Ae=>{const ve=[...F];ve[oe].pin=Ae.target.value,R(ve)},placeholder:O.hasExistingPin?"Leer = beibehalten":"4-stellig",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),i.jsx("button",{type:"button",onClick:()=>On(Ae=>({...Ae,[oe]:!Ae[oe]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:pt[oe]?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:O.hasExistingPuk?"PUK (bereits hinterlegt)":"PUK"}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:wn[oe]?"text":"password",value:O.puk,onChange:Ae=>{const ve=[...F];ve[oe].puk=Ae.target.value,R(ve)},placeholder:O.hasExistingPuk?"Leer = beibehalten":"8-stellig",className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),i.jsx("button",{type:"button",onClick:()=>le(Ae=>({...Ae,[oe]:!Ae[oe]})),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:wn[oe]?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]})]})]},oe))}),i.jsxs(I,{type:"button",variant:"secondary",onClick:()=>{R([...F,{phoneNumber:"",simCardNumber:"",pin:"",puk:"",isMultisim:!1,isMain:F.length===0}])},children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"SIM-Karte hinzufügen"]})]})]}),m==="TV"&&i.jsx(Z,{className:"mb-6",title:"TV-Details",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(q,{label:"Receiver Modell",...l("receiverModel")}),i.jsx(q,{label:"Smartcard-Nummer",...l("smartcardNumber")}),i.jsx(q,{label:"Paket",...l("tvPackage"),placeholder:"z.B. Basis, Premium, Sport"})]})}),m==="CAR_INSURANCE"&&i.jsx(Z,{className:"mb-6",title:"KFZ-Versicherung Details",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(q,{label:"Kennzeichen",...l("licensePlate")}),i.jsx(q,{label:"HSN",...l("hsn")}),i.jsx(q,{label:"TSN",...l("tsn")}),i.jsx(q,{label:"FIN (VIN)",...l("vin")}),i.jsx(q,{label:"Fahrzeugtyp",...l("vehicleType")}),i.jsx(q,{label:"Erstzulassung",type:"date",...l("firstRegistration"),value:d("firstRegistration")||"",onClear:()=>u("firstRegistration","")}),i.jsx(q,{label:"SF-Klasse",...l("noClaimsClass")}),i.jsx(Fe,{label:"Versicherungsart",...l("insuranceType"),options:[{value:"LIABILITY",label:"Haftpflicht"},{value:"PARTIAL",label:"Teilkasko"},{value:"FULL",label:"Vollkasko"}]}),i.jsx(q,{label:"SB Teilkasko (€)",type:"number",...l("deductiblePartial")}),i.jsx(q,{label:"SB Vollkasko (€)",type:"number",...l("deductibleFull")}),i.jsx(q,{label:"Versicherungsscheinnummer",...l("policyNumber")}),i.jsx(q,{label:"Vorversicherer",...l("previousInsurer")})]})}),i.jsx(Z,{className:"mb-6",title:"Notizen",children:i.jsx("textarea",{...l("notes"),rows:4,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"Interne Notizen..."})}),i.jsxs("div",{className:"flex justify-end gap-4",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:()=>n(-1),children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:Ln,children:Ln?"Speichern...":"Speichern"})]})]}),i.jsx(j3,{isOpen:it,onClose:()=>Rt(!1)})]})}const N3={ELECTRICITY:_y,GAS:vC,DSL:Al,CABLE:Al,FIBER:Al,MOBILE:$y,TV:EC,CAR_INSURANCE:gC},w3={ELECTRICITY:"Strom",GAS:"Gas",DSL:"DSL",CABLE:"Kabel",FIBER:"Glasfaser",MOBILE:"Mobilfunk",TV:"TV",CAR_INSURANCE:"KFZ"},k3={critical:"bg-red-100 border-red-300 text-red-800",warning:"bg-yellow-100 border-yellow-300 text-yellow-800",ok:"bg-green-100 border-green-300 text-green-800",none:"bg-gray-100 border-gray-300 text-gray-800"},S3={critical:"danger",warning:"warning",ok:"success",none:"default"},C3={cancellation_deadline:pC,contract_ending:cs,missing_cancellation_letter:We,missing_cancellation_confirmation:We,missing_portal_credentials:E5,missing_customer_number:We,missing_provider:We,missing_address:We,missing_bank:We,missing_meter:_y,missing_sim:$y,open_tasks:_c,pending_status:cs,draft_status:We,review_due:wC,missing_invoice:Fy,missing_consents:hh,consent_withdrawn:CC},E3={cancellationDeadlines:"Kündigungsfristen",contractEnding:"Vertragsenden",missingCredentials:"Fehlende Zugangsdaten",missingData:"Fehlende Daten",openTasks:"Offene Aufgaben",pendingContracts:"Wartende Verträge",missingInvoices:"Fehlende Rechnungen",reviewDue:"Erneute Prüfung fällig",missingConsents:"Fehlende Einwilligungen"};function A3(){var w;const[t,e]=Sf(),[n,s]=N.useState(new Set),r=t.get("filter"),[a,l]=N.useState(r||"all");N.useEffect(()=>{a==="all"?t.delete("filter"):t.set("filter",a),e(t,{replace:!0})},[a,t,e]);const{data:o,isLoading:c,error:d}=fe({queryKey:["contract-cockpit"],queryFn:()=>He.getCockpit(),staleTime:0}),u=ye(),[h,m]=N.useState(null),[f,p]=N.useState(""),g=N.useRef(null);N.useEffect(()=>{const S=M=>{g.current&&!g.current.contains(M.target)&&(m(null),p(""))};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const x=G({mutationFn:({contractId:S,data:M})=>He.snooze(S,M),onSuccess:()=>{u.invalidateQueries({queryKey:["contract-cockpit"]}),m(null),p("")}}),y=(S,M)=>{M?x.mutate({contractId:S,data:{months:M}}):f&&x.mutate({contractId:S,data:{nextReviewDate:f}})},v=S=>{x.mutate({contractId:S,data:{}})},b=S=>{s(M=>{const F=new Set(M);return F.has(S)?F.delete(S):F.add(S),F})},j=N.useMemo(()=>{var M;if(!((M=o==null?void 0:o.data)!=null&&M.contracts))return[];const S=o.data.contracts;switch(a){case"critical":return S.filter(F=>F.highestUrgency==="critical");case"warning":return S.filter(F=>F.highestUrgency==="warning");case"ok":return S.filter(F=>F.highestUrgency==="ok");case"deadlines":return S.filter(F=>F.issues.some(R=>["cancellation_deadline","contract_ending"].includes(R.type)));case"credentials":return S.filter(F=>F.issues.some(R=>R.type.includes("credentials")));case"data":return S.filter(F=>F.issues.some(R=>R.type.startsWith("missing_")&&!R.type.includes("credentials")));case"tasks":return S.filter(F=>F.issues.some(R=>["open_tasks","pending_status","draft_status"].includes(R.type)));case"review":return S.filter(F=>F.issues.some(R=>R.type==="review_due"));case"invoices":return S.filter(F=>F.issues.some(R=>R.type.includes("invoice")));case"consents":return S.filter(F=>F.issues.some(R=>["missing_consents","consent_withdrawn"].includes(R.type)));default:return S}},[(w=o==null?void 0:o.data)==null?void 0:w.contracts,a]);if(c)return i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx("div",{className:"text-gray-500",children:"Laden..."})});if(d||!(o!=null&&o.data))return i.jsx("div",{className:"text-center py-12",children:i.jsx("p",{className:"text-red-500",children:"Fehler beim Laden des Cockpits"})});const{summary:k,thresholds:E}=o.data,T=S=>{var R,V,D,z;const M=n.has(S.id),F=N3[S.type]||We;return i.jsxs("div",{className:`border rounded-lg mb-2 ${k3[S.highestUrgency]}`,children:[i.jsxs("div",{className:"flex items-center p-4 cursor-pointer hover:bg-opacity-50",onClick:()=>b(S.id),children:[i.jsx("div",{className:"w-6 mr-2",children:M?i.jsx(Us,{className:"w-5 h-5"}):i.jsx(At,{className:"w-5 h-5"})}),i.jsx(F,{className:"w-5 h-5 mr-3"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx(Me,{to:`/contracts/${S.id}`,state:{from:"cockpit",filter:a!=="all"?a:void 0},className:"font-medium hover:underline",onClick:C=>C.stopPropagation(),children:S.contractNumber}),i.jsxs(je,{variant:S3[S.highestUrgency],children:[S.issues.length," ",S.highestUrgency==="ok"?S.issues.length===1?"Hinweis":"Hinweise":S.issues.length===1?"Problem":"Probleme"]}),i.jsx("span",{className:"text-sm",children:w3[S.type]})]}),i.jsxs("div",{className:"text-sm mt-1",children:[i.jsxs(Me,{to:`/customers/${S.customer.id}`,className:"hover:underline",onClick:C=>C.stopPropagation(),children:[S.customer.customerNumber," - ",S.customer.name]}),(((R=S.provider)==null?void 0:R.name)||S.providerName)&&i.jsxs("span",{className:"ml-2",children:["| ",((V=S.provider)==null?void 0:V.name)||S.providerName,(((D=S.tariff)==null?void 0:D.name)||S.tariffName)&&` - ${((z=S.tariff)==null?void 0:z.name)||S.tariffName}`]})]})]}),i.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[i.jsxs("div",{className:"relative",ref:h===S.id?g:void 0,children:[i.jsx("button",{onClick:C=>{C.stopPropagation(),m(h===S.id?null:S.id),p("")},className:"p-2 hover:bg-white hover:bg-opacity-50 rounded",title:"Zurückstellen",children:i.jsx(mC,{className:"w-4 h-4"})}),h===S.id&&i.jsxs("div",{className:"absolute right-0 top-full mt-1 w-56 bg-white border rounded-lg shadow-lg z-50 p-3",onClick:C=>C.stopPropagation(),children:[i.jsx("div",{className:"text-sm font-medium mb-2",children:"Zurückstellen"}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("button",{onClick:()=>y(S.id,3),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded",disabled:x.isPending,children:"+3 Monate"}),i.jsxs("button",{onClick:()=>y(S.id,6),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded bg-blue-50 border-blue-200",disabled:x.isPending,children:["+6 Monate ",i.jsx("span",{className:"text-xs text-gray-500",children:"(Empfohlen)"})]}),i.jsx("button",{onClick:()=>y(S.id,12),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-100 rounded",disabled:x.isPending,children:"+12 Monate"})]}),i.jsxs("div",{className:"border-t mt-2 pt-2",children:[i.jsx("label",{className:"text-xs text-gray-500 block mb-1",children:"Eigenes Datum:"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(q,{type:"date",value:f,onChange:C=>p(C.target.value),className:"flex-1 text-sm",min:new Date().toISOString().split("T")[0]}),i.jsx(I,{size:"sm",onClick:()=>y(S.id),disabled:!f||x.isPending,children:"OK"})]})]}),S.issues.some(C=>C.type==="review_due")&&i.jsx("div",{className:"border-t mt-2 pt-2",children:i.jsxs("button",{onClick:()=>v(S.id),className:"w-full text-left px-3 py-2 text-sm hover:bg-red-50 text-red-600 rounded flex items-center gap-2",disabled:x.isPending,children:[i.jsx(wC,{className:"w-4 h-4"}),"Snooze aufheben"]})})]})]}),i.jsx(Me,{to:`/contracts/${S.id}`,state:{from:"cockpit",filter:a!=="all"?a:void 0},className:"p-2 hover:bg-white hover:bg-opacity-50 rounded",onClick:C=>C.stopPropagation(),title:"Zum Vertrag",children:i.jsx(Oe,{className:"w-4 h-4"})})]})]}),M&&i.jsx("div",{className:"border-t px-4 py-3 bg-white bg-opacity-50",children:i.jsx("div",{className:"space-y-2",children:S.issues.map((C,_)=>{const K=C3[C.type]||Tr,B=C.urgency==="critical"?Tr:C.urgency==="warning"?Mn:C.urgency==="ok"?Un:cs;return i.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[i.jsx(B,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${C.urgency==="critical"?"text-red-500":C.urgency==="warning"?"text-yellow-500":C.urgency==="ok"?"text-green-500":"text-gray-500"}`}),i.jsx(K,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-gray-500"}),i.jsxs("div",{children:[i.jsx("span",{className:"font-medium",children:C.label}),C.details&&i.jsx("span",{className:"text-gray-600 ml-2",children:C.details})]})]},_)})})})]},S.id)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Tr,{className:"w-6 h-6 text-red-500"}),i.jsx("h1",{className:"text-2xl font-bold",children:"Vertrags-Cockpit"})]}),i.jsx(Me,{to:"/settings/deadlines",className:"text-sm text-blue-600 hover:underline",children:"Fristenschwellen anpassen"})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-6",children:[i.jsx(Z,{className:"!p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:i.jsx(Tr,{className:"w-6 h-6 text-red-500"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-2xl font-bold text-red-600",children:k.criticalCount}),i.jsxs("p",{className:"text-sm text-gray-500",children:["Kritisch (<",E.criticalDays," Tage)"]})]})]})}),i.jsx(Z,{className:"!p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-yellow-100 rounded-lg",children:i.jsx(Mn,{className:"w-6 h-6 text-yellow-500"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-2xl font-bold text-yellow-600",children:k.warningCount}),i.jsxs("p",{className:"text-sm text-gray-500",children:["Warnung (<",E.warningDays," Tage)"]})]})]})}),i.jsx(Z,{className:"!p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-green-100 rounded-lg",children:i.jsx(Un,{className:"w-6 h-6 text-green-500"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-2xl font-bold text-green-600",children:k.okCount}),i.jsxs("p",{className:"text-sm text-gray-500",children:["OK (<",E.okDays," Tage)"]})]})]})}),i.jsx(Z,{className:"!p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-gray-100 rounded-lg",children:i.jsx(We,{className:"w-6 h-6 text-gray-500"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-2xl font-bold text-gray-600",children:k.totalContracts}),i.jsx("p",{className:"text-sm text-gray-500",children:"Verträge mit Handlungsbedarf"})]})]})})]}),i.jsx(Z,{className:"mb-6",children:i.jsx("div",{className:"flex flex-wrap gap-4",children:Object.entries(k.byCategory).map(([S,M])=>M>0&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsxs("span",{className:"font-medium",children:[E3[S]||S,":"]}),i.jsx(je,{variant:"default",children:M})]},S))})}),i.jsx(Z,{className:"mb-6",children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("span",{className:"text-sm text-gray-600",children:"Filter:"}),i.jsx(Fe,{value:a,onChange:S=>l(S.target.value),options:[{value:"all",label:`Alle (${o.data.contracts.length})`},{value:"critical",label:`Kritisch (${k.criticalCount})`},{value:"warning",label:`Warnung (${k.warningCount})`},{value:"ok",label:`OK (${k.okCount})`},{value:"deadlines",label:`Fristen (${k.byCategory.cancellationDeadlines+k.byCategory.contractEnding})`},{value:"credentials",label:`Zugangsdaten (${k.byCategory.missingCredentials})`},{value:"data",label:`Fehlende Daten (${k.byCategory.missingData})`},{value:"tasks",label:`Aufgaben/Status (${k.byCategory.openTasks+k.byCategory.pendingContracts})`},{value:"review",label:`Erneute Prüfung (${k.byCategory.reviewDue||0})`},{value:"invoices",label:`Fehlende Rechnungen (${k.byCategory.missingInvoices||0})`},{value:"consents",label:`Einwilligungen (${k.byCategory.missingConsents||0})`}],className:"w-64"}),i.jsxs("span",{className:"text-sm text-gray-500",children:[j.length," Verträge angezeigt"]})]})}),j.length===0?i.jsx(Z,{children:i.jsx("div",{className:"text-center py-8 text-gray-500",children:a==="all"?i.jsxs(i.Fragment,{children:[i.jsx(Un,{className:"w-12 h-12 mx-auto mb-4 text-green-500"}),i.jsx("p",{className:"text-lg font-medium",children:"Alles in Ordnung!"}),i.jsx("p",{children:"Keine Verträge mit Handlungsbedarf gefunden."})]}):i.jsx("p",{children:"Keine Verträge für diesen Filter gefunden."})})}):i.jsx("div",{children:j.map(T)})]})}const ej={OPEN:"Offen",COMPLETED:"Erledigt"},D3={OPEN:"warning",COMPLETED:"success"};function M3(){var K;const t=fn(),e=ye(),{isCustomerPortal:n,user:s,hasPermission:r}=nt(),[a,l]=N.useState("OPEN"),[o,c]=N.useState(new Set),[d,u]=N.useState(!1),[h,m]=N.useState({}),[f,p]=N.useState(null),g=n?"Support-Anfragen":"Aufgaben",x=n?"Anfrage":"Aufgabe",{data:y,isLoading:v}=fe({queryKey:["app-settings-public"],queryFn:()=>Ba.getPublic(),enabled:n,staleTime:0}),b=!v&&((K=y==null?void 0:y.data)==null?void 0:K.customerSupportTicketsEnabled)==="true",{data:j,isLoading:k}=fe({queryKey:["all-tasks",a],queryFn:()=>ht.getAll({status:a||void 0}),staleTime:0}),E=G({mutationFn:B=>ht.completeSubtask(B),onSuccess:()=>{e.invalidateQueries({queryKey:["all-tasks"]}),e.invalidateQueries({queryKey:["task-stats"]})}}),T=G({mutationFn:B=>ht.reopenSubtask(B),onSuccess:()=>{e.invalidateQueries({queryKey:["all-tasks"]}),e.invalidateQueries({queryKey:["task-stats"]})}}),w=G({mutationFn:({taskId:B,title:W})=>n?ht.createReply(B,W):ht.createSubtask(B,W),onSuccess:(B,{taskId:W})=>{e.invalidateQueries({queryKey:["all-tasks"]}),m(ce=>({...ce,[W]:""}))}}),S=G({mutationFn:B=>ht.delete(B),onSuccess:()=>{e.invalidateQueries({queryKey:["all-tasks"]}),e.invalidateQueries({queryKey:["task-stats"]})}}),M=G({mutationFn:({taskId:B,data:W})=>ht.update(B,W),onSuccess:()=>{e.invalidateQueries({queryKey:["all-tasks"]}),p(null)}}),F=N.useMemo(()=>{var he;if(!(j!=null&&j.data))return{ownTasks:[],representedTasks:[],allTasks:[]};const B=j.data;if(!n)return{allTasks:B,ownTasks:[],representedTasks:[]};const W=[],ce=[];for(const Je of B)((he=Je.contract)==null?void 0:he.customerId)===(s==null?void 0:s.customerId)?W.push(Je):ce.push(Je);return{ownTasks:W,representedTasks:ce,allTasks:[]}},[j==null?void 0:j.data,n,s==null?void 0:s.customerId]),R=B=>{c(W=>{const ce=new Set(W);return ce.has(B)?ce.delete(B):ce.add(B),ce})},V=B=>{E.isPending||T.isPending||(B.status==="COMPLETED"?T.mutate(B.id):E.mutate(B.id))},D=B=>{var ce;const W=(ce=h[B])==null?void 0:ce.trim();W&&w.mutate({taskId:B,title:W})},z=!n&&r("contracts:update"),C=(B,W=!1)=>{var it,Rt,J,Ke,ct,ee;const ce=o.has(B.id),he=B.subtasks&&B.subtasks.length>0,Je=((it=B.subtasks)==null?void 0:it.filter(pe=>pe.status==="COMPLETED").length)||0,et=((Rt=B.subtasks)==null?void 0:Rt.length)||0,mt=B.status==="COMPLETED",A=new Date(B.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),pt=!n&&r("contracts:update"),On=!n&&r("contracts:update"),wn=B.contract?`${B.contract.contractNumber} - ${((J=B.contract.provider)==null?void 0:J.name)||B.contract.providerName||"Kein Anbieter"}`:`Vertrag #${B.contractId}`,le=(Ke=B.contract)!=null&&Ke.customer?B.contract.customer.companyName||`${B.contract.customer.firstName} ${B.contract.customer.lastName}`:"";return i.jsxs("div",{className:"border rounded-lg mb-2",children:[i.jsxs("div",{className:"flex items-center p-4 hover:bg-gray-50 cursor-pointer",onClick:()=>R(B.id),children:[i.jsx("div",{className:"w-6 mr-2",children:ce?i.jsx(Us,{className:"w-5 h-5 text-gray-400"}):i.jsx(At,{className:"w-5 h-5 text-gray-400"})}),i.jsx("div",{className:"mr-3",children:B.status==="COMPLETED"?i.jsx(Un,{className:"w-5 h-5 text-green-500"}):i.jsx(cs,{className:"w-5 h-5 text-yellow-500"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("span",{className:"font-medium",children:B.title}),i.jsx(je,{variant:D3[B.status],children:ej[B.status]}),he&&i.jsxs("span",{className:"text-xs text-gray-500",children:["(",Je,"/",et," erledigt)"]})]}),i.jsxs("div",{className:"text-sm text-gray-500 mt-1 flex items-center gap-2",children:[i.jsx(We,{className:"w-4 h-4"}),i.jsx(Me,{to:`/contracts/${B.contractId}`,className:"text-blue-600 hover:underline",onClick:pe=>pe.stopPropagation(),children:wn}),W&&le&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-gray-400",children:"|"}),i.jsx("span",{children:le})]})]}),B.description&&i.jsx("p",{className:"text-sm text-gray-600 mt-1 line-clamp-2",children:B.description}),i.jsxs("div",{className:"text-xs text-gray-400 mt-1",children:[B.createdBy," • ",A]})]}),i.jsxs("div",{className:"ml-4 flex gap-2",children:[pt&&i.jsx(I,{variant:"ghost",size:"sm",onClick:pe=>{pe.stopPropagation(),p(B)},title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),On&&i.jsx(I,{variant:"ghost",size:"sm",onClick:pe=>{pe.stopPropagation(),confirm("Aufgabe wirklich löschen?")&&S.mutate(B.id)},title:"Löschen",className:"text-red-500 hover:text-red-700",children:i.jsx(Ee,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:pe=>{pe.stopPropagation(),t(`/contracts/${B.contractId}`)},title:"Zum Vertrag",children:i.jsx(Oe,{className:"w-4 h-4"})})]})]}),ce&&i.jsxs("div",{className:"border-t bg-gray-50 px-4 py-3",children:[he&&i.jsx("div",{className:"space-y-2 mb-4",children:(ct=B.subtasks)==null?void 0:ct.map(pe=>{const Ln=new Date(pe.createdAt).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"});return i.jsxs("div",{className:`flex items-start gap-2 text-sm ml-6 ${z?"cursor-pointer hover:bg-gray-100 rounded px-2 py-1 -mx-2":""}`,onClick:z?()=>V(pe):void 0,children:[i.jsx("span",{className:"flex-shrink-0 mt-0.5",children:pe.status==="COMPLETED"?i.jsx(Un,{className:"w-4 h-4 text-green-500"}):i.jsx(Eu,{className:"w-4 h-4 text-gray-400"})}),i.jsxs("span",{className:pe.status==="COMPLETED"?"text-gray-500 line-through":"",children:[pe.title,i.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[pe.createdBy," • ",Ln]})]})]},pe.id)})}),!mt&&(z||n)&&i.jsxs("div",{className:"flex gap-2 ml-6",children:[i.jsx(q,{placeholder:n?"Antwort schreiben...":"Neue Unteraufgabe...",value:h[B.id]||"",onChange:pe=>m(Ln=>({...Ln,[B.id]:pe.target.value})),onKeyDown:pe=>{pe.key==="Enter"&&!pe.shiftKey&&(pe.preventDefault(),D(B.id))},className:"flex-1"}),i.jsx(I,{size:"sm",onClick:()=>D(B.id),disabled:!((ee=h[B.id])!=null&&ee.trim())||w.isPending,children:i.jsx(Nd,{className:"w-4 h-4"})})]}),!he&&mt&&i.jsx("p",{className:"text-gray-500 text-sm text-center py-2",children:"Keine Unteraufgaben vorhanden."})]})]},B.id)},_=n?b:r("contracts:update");return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold",children:g}),_&&i.jsxs(I,{onClick:()=>u(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neue ",x]})]}),i.jsx(Z,{className:"mb-6",children:i.jsx("div",{className:"flex gap-4 flex-wrap items-center",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-gray-600",children:"Status:"}),i.jsx(Fe,{value:a,onChange:B=>l(B.target.value),options:[{value:"",label:"Alle"},...Object.entries(ej).map(([B,W])=>({value:B,label:W}))],className:"w-40"})]})})}),k?i.jsx(Z,{children:i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."})}):i.jsx(i.Fragment,{children:n?i.jsxs("div",{className:"space-y-6",children:[i.jsxs(Z,{children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:[i.jsx(yo,{className:"w-5 h-5 text-blue-600"}),i.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:["Meine ",g]}),i.jsx(je,{variant:"default",children:F.ownTasks.length})]}),F.ownTasks.length>0?i.jsx("div",{children:F.ownTasks.map(B=>C(B,!1))}):i.jsxs("p",{className:"text-gray-500 text-center py-4",children:["Keine eigenen ",g.toLowerCase()," vorhanden."]})]}),F.representedTasks.length>0&&i.jsxs(Z,{children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4 pb-3 border-b",children:[i.jsx(Ca,{className:"w-5 h-5 text-purple-600"}),i.jsxs("h2",{className:"text-lg font-semibold text-gray-900",children:[g," freigegebener Kunden"]}),i.jsx(je,{variant:"default",children:F.representedTasks.length})]}),i.jsx("div",{children:F.representedTasks.map(B=>C(B,!0))})]})]}):i.jsx(Z,{children:F.allTasks&&F.allTasks.length>0?i.jsx("div",{children:F.allTasks.map(B=>C(B,!0))}):i.jsxs("div",{className:"text-center py-8 text-gray-500",children:["Keine ",g.toLowerCase()," gefunden."]})})}),n?i.jsx(T3,{isOpen:d,onClose:()=>u(!1)}):i.jsx(P3,{isOpen:d,onClose:()=>u(!1)}),f&&i.jsx(I3,{task:f,onClose:()=>p(null),onSave:B=>M.mutate({taskId:f.id,data:B}),isPending:M.isPending})]})}function T3({isOpen:t,onClose:e}){const{user:n}=nt(),s=fn(),r=ye(),[a,l]=N.useState("own"),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,m]=N.useState(""),[f,p]=N.useState(!1),[g,x]=N.useState(""),{data:y}=fe({queryKey:["contracts",n==null?void 0:n.customerId],queryFn:()=>He.getAll({customerId:n==null?void 0:n.customerId}),enabled:t}),v=N.useMemo(()=>{if(!(y!=null&&y.data))return{own:[],represented:{}};const w=[],S={};for(const M of y.data)if(M.customerId===(n==null?void 0:n.customerId))w.push(M);else{if(!S[M.customerId]){const F=M.customer?M.customer.companyName||`${M.customer.firstName} ${M.customer.lastName}`:`Kunde ${M.customerId}`;S[M.customerId]={name:F,contracts:[]}}S[M.customerId].contracts.push(M)}return{own:w,represented:S}},[y==null?void 0:y.data,n==null?void 0:n.customerId]),b=Object.keys(v.represented).length>0,j=N.useMemo(()=>{var w;return a==="own"?v.own:((w=v.represented[a])==null?void 0:w.contracts)||[]},[a,v]),k=N.useMemo(()=>{if(!g)return j;const w=g.toLowerCase();return j.filter(S=>S.contractNumber.toLowerCase().includes(w)||(S.providerName||"").toLowerCase().includes(w)||(S.tariffName||"").toLowerCase().includes(w))},[j,g]),E=async()=>{if(!(!o||!d.trim())){p(!0);try{await ht.createSupportTicket(o,{title:d.trim(),description:h.trim()||void 0}),r.invalidateQueries({queryKey:["all-tasks"]}),r.invalidateQueries({queryKey:["task-stats"]}),e(),u(""),m(""),c(null),l("own"),s(`/contracts/${o}`)}catch(w){console.error("Fehler beim Erstellen der Support-Anfrage:",w),alert("Fehler beim Erstellen der Support-Anfrage. Bitte versuchen Sie es erneut.")}finally{p(!1)}}},T=()=>{u(""),m(""),c(null),l("own"),x(""),e()};return i.jsx(Xe,{isOpen:t,onClose:T,title:"Neue Support-Anfrage",children:i.jsxs("div",{className:"space-y-4",children:[b&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde"}),i.jsxs("select",{value:a,onChange:w=>{const S=w.target.value;l(S==="own"?"own":parseInt(S)),c(null),x("")},className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",children:[i.jsx("option",{value:"own",children:"Eigene Verträge"}),Object.entries(v.represented).map(([w,{name:S}])=>i.jsx("option",{value:w,children:S},w))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),i.jsx(q,{placeholder:"Vertrag suchen...",value:g,onChange:w=>x(w.target.value),className:"mb-2"}),i.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-lg",children:k.length>0?k.map(w=>i.jsxs("div",{onClick:()=>c(w.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${o===w.id?"bg-blue-50 border-blue-200":""}`,children:[i.jsx("div",{className:"font-medium",children:w.contractNumber}),i.jsxs("div",{className:"text-sm text-gray-500",children:[w.providerName||"Kein Anbieter",w.tariffName&&` - ${w.tariffName}`]})]},w.id)):i.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Verträge gefunden."})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),i.jsx(q,{value:d,onChange:w=>u(w.target.value),placeholder:"Kurze Beschreibung Ihres Anliegens"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),i.jsx("textarea",{value:h,onChange:w=>m(w.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:4,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:T,children:"Abbrechen"}),i.jsx(I,{onClick:E,disabled:!o||!d.trim()||f,children:f?"Wird erstellt...":"Anfrage erstellen"})]})]})})}function P3({isOpen:t,onClose:e}){const n=fn(),s=ye(),[r,a]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(""),[u,h]=N.useState(""),[m,f]=N.useState(!1),[p,g]=N.useState(!1),[x,y]=N.useState(""),[v,b]=N.useState(""),{data:j}=fe({queryKey:["customers-for-task"],queryFn:()=>Zt.getAll({limit:100}),enabled:t}),{data:k}=fe({queryKey:["contracts-for-task",r],queryFn:()=>He.getAll({customerId:r}),enabled:t&&r!==null}),E=N.useMemo(()=>{if(!(j!=null&&j.data))return[];if(!x)return j.data;const F=x.toLowerCase();return j.data.filter(R=>R.customerNumber.toLowerCase().includes(F)||R.firstName.toLowerCase().includes(F)||R.lastName.toLowerCase().includes(F)||(R.companyName||"").toLowerCase().includes(F))},[j==null?void 0:j.data,x]),T=N.useMemo(()=>{if(!(k!=null&&k.data))return[];if(!v)return k.data;const F=v.toLowerCase();return k.data.filter(R=>R.contractNumber.toLowerCase().includes(F)||(R.providerName||"").toLowerCase().includes(F)||(R.tariffName||"").toLowerCase().includes(F))},[k==null?void 0:k.data,v]),w=async()=>{if(!(!l||!c.trim())){g(!0);try{await ht.create(l,{title:c.trim(),description:u.trim()||void 0,visibleInPortal:m}),s.invalidateQueries({queryKey:["all-tasks"]}),s.invalidateQueries({queryKey:["task-stats"]}),e(),d(""),h(""),f(!1),o(null),a(null),n(`/contracts/${l}`)}catch(F){console.error("Fehler beim Erstellen der Aufgabe:",F),alert("Fehler beim Erstellen der Aufgabe. Bitte versuchen Sie es erneut.")}finally{g(!1)}}},S=()=>{d(""),h(""),f(!1),o(null),a(null),y(""),b(""),e()},M=F=>{const R=F.companyName||`${F.firstName} ${F.lastName}`;return`${F.customerNumber} - ${R}`};return i.jsx(Xe,{isOpen:t,onClose:S,title:"Neue Aufgabe",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kunde *"}),i.jsx(q,{placeholder:"Kunde suchen...",value:x,onChange:F=>y(F.target.value),className:"mb-2"}),i.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:E.length>0?E.map(F=>i.jsx("div",{onClick:()=>{a(F.id),o(null),b("")},className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${r===F.id?"bg-blue-50 border-blue-200":""}`,children:i.jsx("div",{className:"font-medium",children:M(F)})},F.id)):i.jsx("div",{className:"p-3 text-gray-500 text-center",children:"Keine Kunden gefunden."})})]}),r&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Vertrag *"}),i.jsx(q,{placeholder:"Vertrag suchen...",value:v,onChange:F=>b(F.target.value),className:"mb-2"}),i.jsx("div",{className:"max-h-40 overflow-y-auto border rounded-lg",children:T.length>0?T.map(F=>i.jsxs("div",{onClick:()=>o(F.id),className:`p-3 cursor-pointer border-b last:border-b-0 hover:bg-gray-50 ${l===F.id?"bg-blue-50 border-blue-200":""}`,children:[i.jsx("div",{className:"font-medium",children:F.contractNumber}),i.jsxs("div",{className:"text-sm text-gray-500",children:[F.providerName||"Kein Anbieter",F.tariffName&&` - ${F.tariffName}`]})]},F.id)):i.jsx("div",{className:"p-3 text-gray-500 text-center",children:k?"Keine Verträge gefunden.":"Laden..."})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),i.jsx(q,{value:c,onChange:F=>d(F.target.value),placeholder:"Aufgabentitel"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),i.jsx("textarea",{value:u,onChange:F=>h(F.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),i.jsx("div",{children:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:m,onChange:F=>f(F.target.checked),className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),i.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]})}),i.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:S,children:"Abbrechen"}),i.jsx(I,{onClick:w,disabled:!l||!c.trim()||p,children:p?"Wird erstellt...":"Aufgabe erstellen"})]})]})})}function I3({task:t,onClose:e,onSave:n,isPending:s}){const[r,a]=N.useState(t.title),[l,o]=N.useState(t.description||""),[c,d]=N.useState(t.visibleInPortal||!1),u=()=>{r.trim()&&n({title:r.trim(),description:l.trim()||void 0,visibleInPortal:c})};return i.jsx(Xe,{isOpen:!0,onClose:e,title:"Aufgabe bearbeiten",children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Titel *"}),i.jsx(q,{value:r,onChange:h=>a(h.target.value),placeholder:"Aufgabentitel"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Beschreibung"}),i.jsx("textarea",{value:l,onChange:h=>o(h.target.value),placeholder:"Detaillierte Beschreibung (optional)",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),i.jsx("div",{children:i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:c,onChange:h=>d(h.target.checked),className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),i.jsx("span",{className:"text-sm text-gray-700",children:"Im Kundenportal sichtbar"})]})}),i.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[i.jsx(I,{variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{onClick:u,disabled:!r.trim()||s,children:s?"Wird gespeichert...":"Speichern"})]})]})})}function R3(){const[t,e]=N.useState(!1),[n,s]=N.useState(null),[r,a]=N.useState(!1),{hasPermission:l}=nt(),o=ye(),{data:c,isLoading:d}=fe({queryKey:["platforms",r],queryFn:()=>Fc.getAll(r)}),u=G({mutationFn:Fc.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["platforms"]})}}),h=f=>{s(f),e(!0)},m=()=>{e(!1),s(null)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold",children:"Vertriebsplattformen"}),l("platforms:create")&&i.jsxs(I,{onClick:()=>e(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neue Plattform"]})]}),i.jsxs(Z,{children:[i.jsx("div",{className:"mb-4",children:i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:f=>a(f.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),d?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Kontakt"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),i.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),i.jsx("tbody",{children:c.data.map(f=>i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsx("td",{className:"py-3 px-4 font-medium",children:f.name}),i.jsx("td",{className:"py-3 px-4 text-gray-500",children:f.contactInfo||"-"}),i.jsx("td",{className:"py-3 px-4",children:i.jsx(je,{variant:f.isActive?"success":"danger",children:f.isActive?"Aktiv":"Inaktiv"})}),i.jsx("td",{className:"py-3 px-4 text-right",children:i.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>h(f),children:i.jsx(rt,{className:"w-4 h-4"})}),l("platforms:delete")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Plattform wirklich löschen?")&&u.mutate(f.id)},children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})})]},f.id))})]})}):i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Plattformen vorhanden."})]}),i.jsx(O3,{isOpen:t,onClose:m,platform:n})]})}function O3({isOpen:t,onClose:e,platform:n}){const s=ye(),[r,a]=N.useState({name:"",contactInfo:"",isActive:!0});N.useState(()=>{a(n?{name:n.name,contactInfo:n.contactInfo||"",isActive:n.isActive}:{name:"",contactInfo:"",isActive:!0})}),n&&r.name!==n.name?a({name:n.name,contactInfo:n.contactInfo||"",isActive:n.isActive}):!n&&r.name;const l=G({mutationFn:Fc.create,onSuccess:()=>{s.invalidateQueries({queryKey:["platforms"]}),e(),a({name:"",contactInfo:"",isActive:!0})}}),o=G({mutationFn:u=>Fc.update(n.id,u),onSuccess:()=>{s.invalidateQueries({queryKey:["platforms"]}),e()}}),c=u=>{u.preventDefault(),n?o.mutate(r):l.mutate(r)},d=l.isPending||o.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:n?"Plattform bearbeiten":"Neue Plattform",children:i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsx(q,{label:"Name *",value:r.name,onChange:u=>a({...r,name:u.target.value}),required:!0}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Kontaktinformationen"}),i.jsx("textarea",{value:r.contactInfo,onChange:u=>a({...r,contactInfo:u.target.value}),rows:3,className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",placeholder:"E-Mail, Telefon, Ansprechpartner..."})]}),n&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:r.isActive,onChange:u=>a({...r,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function L3(){const[t,e]=N.useState(!1),[n,s]=N.useState(null),[r,a]=N.useState(!1),{hasPermission:l}=nt(),o=ye(),{data:c,isLoading:d}=fe({queryKey:["cancellation-periods",r],queryFn:()=>zc.getAll(r)}),u=G({mutationFn:zc.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["cancellation-periods"]})}}),h=f=>{s(f),e(!0)},m=()=>{e(!1),s(null)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(Yn,{className:"w-4 h-4"})})}),i.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Kündigungsfristen"}),l("platforms:create")&&i.jsxs(I,{onClick:()=>e(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neue Frist"]})]}),i.jsxs(Z,{children:[i.jsx("div",{className:"mb-4",children:i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:f=>a(f.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),i.jsxs("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:[i.jsx("strong",{children:"Code-Format:"})," Zahl + Buchstabe (T=Tage, M=Monate, J=Jahre)",i.jsx("br",{}),i.jsx("strong",{children:"Beispiele:"})," 14T = 14 Tage, 3M = 3 Monate, 1J = 1 Jahr"]}),d?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Code"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beschreibung"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),i.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),i.jsx("tbody",{children:c.data.map(f=>i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsx("td",{className:"py-3 px-4 font-mono font-medium",children:f.code}),i.jsx("td",{className:"py-3 px-4",children:f.description}),i.jsx("td",{className:"py-3 px-4",children:i.jsx(je,{variant:f.isActive?"success":"danger",children:f.isActive?"Aktiv":"Inaktiv"})}),i.jsx("td",{className:"py-3 px-4 text-right",children:i.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>h(f),children:i.jsx(rt,{className:"w-4 h-4"})}),l("platforms:delete")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Kündigungsfrist wirklich löschen?")&&u.mutate(f.id)},children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})})]},f.id))})]})}):i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Kündigungsfristen vorhanden."})]}),i.jsx(F3,{isOpen:t,onClose:m,period:n})]})}function F3({isOpen:t,onClose:e,period:n}){const s=ye(),[r,a]=N.useState({code:"",description:"",isActive:!0});N.useEffect(()=>{t&&a(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[t,n]);const l=G({mutationFn:zc.create,onSuccess:()=>{s.invalidateQueries({queryKey:["cancellation-periods"]}),e(),a({code:"",description:"",isActive:!0})}}),o=G({mutationFn:u=>zc.update(n.id,u),onSuccess:()=>{s.invalidateQueries({queryKey:["cancellation-periods"]}),e()}}),c=u=>{u.preventDefault(),n?o.mutate(r):l.mutate(r)},d=l.isPending||o.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:n?"Kündigungsfrist bearbeiten":"Neue Kündigungsfrist",children:i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsx(q,{label:"Code *",value:r.code,onChange:u=>a({...r,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 14T, 3M, 1J"}),i.jsx(q,{label:"Beschreibung *",value:r.description,onChange:u=>a({...r,description:u.target.value}),required:!0,placeholder:"z.B. 14 Tage, 3 Monate, 1 Jahr"}),n&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:r.isActive,onChange:u=>a({...r,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function z3(){const[t,e]=N.useState(!1),[n,s]=N.useState(null),[r,a]=N.useState(!1),{hasPermission:l}=nt(),o=ye(),{data:c,isLoading:d}=fe({queryKey:["contract-durations",r],queryFn:()=>$c.getAll(r)}),u=G({mutationFn:$c.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["contract-durations"]})}}),h=f=>{s(f),e(!0)},m=()=>{e(!1),s(null)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(Yn,{className:"w-4 h-4"})})}),i.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragslaufzeiten"}),l("platforms:create")&&i.jsxs(I,{onClick:()=>e(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neue Laufzeit"]})]}),i.jsxs(Z,{children:[i.jsx("div",{className:"mb-4",children:i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:f=>a(f.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),i.jsxs("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:[i.jsx("strong",{children:"Code-Format:"})," Zahl + Buchstabe (T=Tage, M=Monate, J=Jahre)",i.jsx("br",{}),i.jsx("strong",{children:"Beispiele:"})," 12M = 12 Monate, 24M = 24 Monate, 2J = 2 Jahre"]}),d?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Code"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Beschreibung"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),i.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),i.jsx("tbody",{children:c.data.map(f=>i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsx("td",{className:"py-3 px-4 font-mono font-medium",children:f.code}),i.jsx("td",{className:"py-3 px-4",children:f.description}),i.jsx("td",{className:"py-3 px-4",children:i.jsx(je,{variant:f.isActive?"success":"danger",children:f.isActive?"Aktiv":"Inaktiv"})}),i.jsx("td",{className:"py-3 px-4 text-right",children:i.jsxs("div",{className:"flex justify-end gap-2",children:[l("platforms:update")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>h(f),children:i.jsx(rt,{className:"w-4 h-4"})}),l("platforms:delete")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Laufzeit wirklich löschen?")&&u.mutate(f.id)},children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})})]},f.id))})]})}):i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Laufzeiten vorhanden."})]}),i.jsx($3,{isOpen:t,onClose:m,duration:n})]})}function $3({isOpen:t,onClose:e,duration:n}){const s=ye(),[r,a]=N.useState({code:"",description:"",isActive:!0});N.useEffect(()=>{t&&a(n?{code:n.code,description:n.description,isActive:n.isActive}:{code:"",description:"",isActive:!0})},[t,n]);const l=G({mutationFn:$c.create,onSuccess:()=>{s.invalidateQueries({queryKey:["contract-durations"]}),e(),a({code:"",description:"",isActive:!0})}}),o=G({mutationFn:u=>$c.update(n.id,u),onSuccess:()=>{s.invalidateQueries({queryKey:["contract-durations"]}),e()}}),c=u=>{u.preventDefault(),n?o.mutate(r):l.mutate(r)},d=l.isPending||o.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:n?"Laufzeit bearbeiten":"Neue Laufzeit",children:i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsx(q,{label:"Code *",value:r.code,onChange:u=>a({...r,code:u.target.value.toUpperCase()}),required:!0,placeholder:"z.B. 12M, 24M, 2J"}),i.jsx(q,{label:"Beschreibung *",value:r.description,onChange:u=>a({...r,description:u.target.value}),required:!0,placeholder:"z.B. 12 Monate, 24 Monate, 2 Jahre"}),n&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:r.isActive,onChange:u=>a({...r,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function B3(){const[t,e]=N.useState(!1),[n,s]=N.useState(null),[r,a]=N.useState(!1),[l,o]=N.useState(new Set),{hasPermission:c}=nt(),d=ye(),{data:u,isLoading:h}=fe({queryKey:["providers",r],queryFn:()=>to.getAll(r)}),m=G({mutationFn:to.delete,onSuccess:()=>{d.invalidateQueries({queryKey:["providers"]})},onError:x=>{alert(x.message)}}),f=x=>{o(y=>{const v=new Set(y);return v.has(x)?v.delete(x):v.add(x),v})},p=x=>{s(x),e(!0)},g=()=>{e(!1),s(null)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(Yn,{className:"w-4 h-4"})})}),i.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Anbieter & Tarife"}),c("providers:create")&&i.jsxs(I,{onClick:()=>e(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neuer Anbieter"]})]}),i.jsxs(Z,{children:[i.jsx("div",{className:"mb-4",children:i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:x=>a(x.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),h?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):u!=null&&u.data&&u.data.length>0?i.jsx("div",{className:"space-y-2",children:u.data.map(x=>i.jsx(_3,{provider:x,isExpanded:l.has(x.id),onToggle:()=>f(x.id),onEdit:()=>p(x),onDelete:()=>{confirm("Anbieter wirklich löschen?")&&m.mutate(x.id)},hasPermission:c,showInactive:r},x.id))}):i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Anbieter vorhanden."})]}),i.jsx(V3,{isOpen:t,onClose:g,provider:n})]})}function _3({provider:t,isExpanded:e,onToggle:n,onEdit:s,onDelete:r,hasPermission:a,showInactive:l}){var p,g;const[o,c]=N.useState(!1),[d,u]=N.useState(null),h=ye(),m=G({mutationFn:oC.delete,onSuccess:()=>{h.invalidateQueries({queryKey:["providers"]})},onError:x=>{alert(x.message)}}),f=((p=t.tariffs)==null?void 0:p.filter(x=>l||x.isActive))||[];return i.jsxs("div",{className:"border rounded-lg",children:[i.jsxs("div",{className:"flex items-center p-4 hover:bg-gray-50",children:[i.jsx("button",{onClick:n,className:"mr-3 p-1 hover:bg-gray-200 rounded",children:e?i.jsx(Us,{className:"w-5 h-5 text-gray-400"}):i.jsx(At,{className:"w-5 h-5 text-gray-400"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("span",{className:"font-medium",children:t.name}),i.jsx(je,{variant:t.isActive?"success":"danger",children:t.isActive?"Aktiv":"Inaktiv"}),i.jsxs("span",{className:"text-sm text-gray-500",children:["(",f.length," Tarife, ",((g=t._count)==null?void 0:g.contracts)||0," Verträge)"]})]}),t.portalUrl&&i.jsxs("a",{href:t.portalUrl,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-600 hover:underline flex items-center gap-1 mt-1",children:[i.jsx(Oy,{className:"w-3 h-3"}),t.portalUrl]})]}),i.jsxs("div",{className:"flex gap-2 ml-4",children:[a("providers:update")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:s,title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),a("providers:delete")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:r,title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]}),e&&i.jsxs("div",{className:"border-t bg-gray-50 p-4",children:[i.jsxs("div",{className:"flex justify-between items-center mb-3",children:[i.jsx("h4",{className:"font-medium text-gray-700",children:"Tarife"}),a("providers:create")&&i.jsxs(I,{size:"sm",onClick:()=>c(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-1"}),"Tarif hinzufügen"]})]}),f.length>0?i.jsx("div",{className:"space-y-2",children:f.map(x=>{var y;return i.jsxs("div",{className:"flex items-center justify-between bg-white p-3 rounded border",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{children:x.name}),i.jsx(je,{variant:x.isActive?"success":"danger",className:"text-xs",children:x.isActive?"Aktiv":"Inaktiv"}),((y=x._count)==null?void 0:y.contracts)!==void 0&&i.jsxs("span",{className:"text-xs text-gray-500",children:["(",x._count.contracts," Verträge)"]})]}),i.jsxs("div",{className:"flex gap-1",children:[a("providers:update")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{u(x),c(!0)},title:"Bearbeiten",children:i.jsx(rt,{className:"w-3 h-3"})}),a("providers:delete")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Tarif wirklich löschen?")&&m.mutate(x.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-3 h-3 text-red-500"})})]})]},x.id)})}):i.jsx("p",{className:"text-sm text-gray-500",children:"Keine Tarife vorhanden."})]}),i.jsx(K3,{isOpen:o,onClose:()=>{c(!1),u(null)},providerId:t.id,tariff:d})]})}function V3({isOpen:t,onClose:e,provider:n}){const s=ye(),[r,a]=N.useState({name:"",portalUrl:"",usernameFieldName:"",passwordFieldName:"",isActive:!0});N.useEffect(()=>{t&&a(n?{name:n.name,portalUrl:n.portalUrl||"",usernameFieldName:n.usernameFieldName||"",passwordFieldName:n.passwordFieldName||"",isActive:n.isActive}:{name:"",portalUrl:"",usernameFieldName:"",passwordFieldName:"",isActive:!0})},[t,n]);const l=G({mutationFn:to.create,onSuccess:()=>{s.invalidateQueries({queryKey:["providers"]}),e()},onError:u=>{alert(u.message)}}),o=G({mutationFn:u=>to.update(n.id,u),onSuccess:()=>{s.invalidateQueries({queryKey:["providers"]}),e()},onError:u=>{alert(u.message)}}),c=u=>{u.preventDefault(),n?o.mutate(r):l.mutate(r)},d=l.isPending||o.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:n?"Anbieter bearbeiten":"Neuer Anbieter",children:i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsx(q,{label:"Anbietername *",value:r.name,onChange:u=>a({...r,name:u.target.value}),required:!0,placeholder:"z.B. Vodafone, E.ON, Allianz"}),i.jsx(q,{label:"Portal-URL (Login-Seite)",value:r.portalUrl,onChange:u=>a({...r,portalUrl:u.target.value}),placeholder:"https://kundenportal.anbieter.de/login"}),i.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg space-y-3",children:[i.jsxs("p",{className:"text-sm text-gray-600",children:[i.jsx("strong",{children:"Auto-Login Felder"})," (optional)",i.jsx("br",{}),"Feldnamen für URL-Parameter beim Auto-Login:"]}),i.jsx(q,{label:"Benutzername-Feldname",value:r.usernameFieldName,onChange:u=>a({...r,usernameFieldName:u.target.value}),placeholder:"z.B. username, email, login"}),i.jsx(q,{label:"Passwort-Feldname",value:r.passwordFieldName,onChange:u=>a({...r,passwordFieldName:u.target.value}),placeholder:"z.B. password, pwd, kennwort"})]}),n&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:r.isActive,onChange:u=>a({...r,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}function K3({isOpen:t,onClose:e,providerId:n,tariff:s}){const r=ye(),[a,l]=N.useState({name:"",isActive:!0});N.useEffect(()=>{t&&l(s?{name:s.name,isActive:s.isActive}:{name:"",isActive:!0})},[t,s]);const o=G({mutationFn:h=>to.createTariff(n,h),onSuccess:()=>{r.invalidateQueries({queryKey:["providers"]}),e()},onError:h=>{alert(h.message)}}),c=G({mutationFn:h=>oC.update(s.id,h),onSuccess:()=>{r.invalidateQueries({queryKey:["providers"]}),e()},onError:h=>{alert(h.message)}}),d=h=>{h.preventDefault(),s?c.mutate(a):o.mutate(a)},u=o.isPending||c.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:s?"Tarif bearbeiten":"Neuer Tarif",children:i.jsxs("form",{onSubmit:d,className:"space-y-4",children:[i.jsx(q,{label:"Tarifname *",value:a.name,onChange:h=>l({...a,name:h.target.value}),required:!0,placeholder:"z.B. Comfort Plus, Basic 100"}),s&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:a.isActive,onChange:h=>l({...a,isActive:h.target.checked}),className:"rounded"}),"Aktiv"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:u,children:u?"Speichern...":"Speichern"})]})]})})}const qg={Zap:i.jsx(_y,{className:"w-5 h-5"}),Flame:i.jsx(vC,{className:"w-5 h-5"}),Wifi:i.jsx(Al,{className:"w-5 h-5"}),Cable:i.jsx(g5,{className:"w-5 h-5"}),Network:i.jsx(L5,{className:"w-5 h-5"}),Smartphone:i.jsx($y,{className:"w-5 h-5"}),Tv:i.jsx(EC,{className:"w-5 h-5"}),Car:i.jsx(gC,{className:"w-5 h-5"}),FileText:i.jsx(We,{className:"w-5 h-5"})},U3=[{value:"Zap",label:"Blitz (Strom)"},{value:"Flame",label:"Flamme (Gas)"},{value:"Wifi",label:"WLAN (DSL)"},{value:"Cable",label:"Kabel"},{value:"Network",label:"Netzwerk (Glasfaser)"},{value:"Smartphone",label:"Smartphone (Mobilfunk)"},{value:"Tv",label:"TV"},{value:"Car",label:"Auto (KFZ)"},{value:"FileText",label:"Dokument (Sonstige)"}],q3=[{value:"#FFC107",label:"Gelb"},{value:"#FF5722",label:"Orange"},{value:"#2196F3",label:"Blau"},{value:"#9C27B0",label:"Lila"},{value:"#4CAF50",label:"Grün"},{value:"#E91E63",label:"Pink"},{value:"#607D8B",label:"Grau"},{value:"#795548",label:"Braun"},{value:"#00BCD4",label:"Cyan"},{value:"#F44336",label:"Rot"}];function H3(){const[t,e]=N.useState(!1),[n,s]=N.useState(null),[r,a]=N.useState(!1),{hasPermission:l}=nt(),o=ye(),{data:c,isLoading:d}=fe({queryKey:["contract-categories",r],queryFn:()=>Bc.getAll(r)}),u=G({mutationFn:Bc.delete,onSuccess:()=>{o.invalidateQueries({queryKey:["contract-categories"]})},onError:f=>{alert(f.message)}}),h=f=>{s(f),e(!0)},m=()=>{e(!1),s(null)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(Yn,{className:"w-4 h-4"})})}),i.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Vertragstypen"}),l("developer:access")&&i.jsxs(I,{onClick:()=>e(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neuer Vertragstyp"]})]}),i.jsxs(Z,{children:[i.jsx("div",{className:"mb-4",children:i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:f=>a(f.target.checked),className:"rounded"}),"Inaktive anzeigen"]})}),d?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):c!=null&&c.data&&c.data.length>0?i.jsx("div",{className:"space-y-2",children:c.data.map(f=>{var p;return i.jsxs("div",{className:"flex items-center p-4 border rounded-lg hover:bg-gray-50",children:[i.jsx("div",{className:"mr-3 text-gray-400",children:i.jsx(j5,{className:"w-5 h-5"})}),i.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center mr-4",style:{backgroundColor:f.color||"#E5E7EB",color:"#fff"},children:f.icon&&qg[f.icon]?qg[f.icon]:i.jsx(We,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("span",{className:"font-medium",children:f.name}),i.jsx(je,{variant:f.isActive?"success":"danger",children:f.isActive?"Aktiv":"Inaktiv"}),i.jsxs("span",{className:"text-sm text-gray-500",children:["(",((p=f._count)==null?void 0:p.contracts)||0," Verträge)"]})]}),i.jsxs("div",{className:"text-sm text-gray-500",children:["Code: ",i.jsx("span",{className:"font-mono",children:f.code})]})]}),i.jsxs("div",{className:"flex gap-2 ml-4",children:[l("developer:access")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>h(f),title:"Bearbeiten",children:i.jsx(rt,{className:"w-4 h-4"})}),l("developer:access")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>{confirm("Vertragstyp wirklich löschen?")&&u.mutate(f.id)},title:"Löschen",children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]},f.id)})}):i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Vertragstypen vorhanden."})]}),i.jsx(W3,{isOpen:t,onClose:m,category:n})]})}function W3({isOpen:t,onClose:e,category:n}){const s=ye(),[r,a]=N.useState({code:"",name:"",icon:"FileText",color:"#607D8B",sortOrder:0,isActive:!0});N.useEffect(()=>{t&&a(n?{code:n.code,name:n.name,icon:n.icon||"FileText",color:n.color||"#607D8B",sortOrder:n.sortOrder,isActive:n.isActive}:{code:"",name:"",icon:"FileText",color:"#607D8B",sortOrder:0,isActive:!0})},[t,n]);const l=G({mutationFn:Bc.create,onSuccess:()=>{s.invalidateQueries({queryKey:["contract-categories"]}),e()},onError:u=>{alert(u.message)}}),o=G({mutationFn:u=>Bc.update(n.id,u),onSuccess:()=>{s.invalidateQueries({queryKey:["contract-categories"]}),e()},onError:u=>{alert(u.message)}}),c=u=>{u.preventDefault(),n?o.mutate(r):l.mutate(r)},d=l.isPending||o.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:n?"Vertragstyp bearbeiten":"Neuer Vertragstyp",children:i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsx(q,{label:"Code (technisch) *",value:r.code,onChange:u=>a({...r,code:u.target.value.toUpperCase().replace(/[^A-Z0-9_]/g,"")}),required:!0,placeholder:"z.B. ELECTRICITY, MOBILE_BUSINESS",disabled:!!n}),i.jsx(q,{label:"Anzeigename *",value:r.name,onChange:u=>a({...r,name:u.target.value}),required:!0,placeholder:"z.B. Strom, Mobilfunk Business"}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Icon"}),i.jsx("div",{className:"grid grid-cols-4 gap-2",children:U3.map(u=>i.jsxs("button",{type:"button",onClick:()=>a({...r,icon:u.value}),className:`p-3 border rounded-lg flex flex-col items-center gap-1 text-xs ${r.icon===u.value?"border-blue-500 bg-blue-50":"border-gray-200 hover:bg-gray-50"}`,children:[qg[u.value],i.jsx("span",{className:"truncate w-full text-center",children:u.label.split(" ")[0]})]},u.value))})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Farbe"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:q3.map(u=>i.jsx("button",{type:"button",onClick:()=>a({...r,color:u.value}),className:`w-8 h-8 rounded-full border-2 ${r.color===u.value?"border-gray-800 ring-2 ring-offset-2 ring-gray-400":"border-transparent"}`,style:{backgroundColor:u.value},title:u.label},u.value))})]}),i.jsx(q,{label:"Sortierung",type:"number",value:r.sortOrder,onChange:u=>a({...r,sortOrder:parseInt(u.target.value)||0}),placeholder:"0"}),n&&i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:r.isActive,onChange:u=>a({...r,isActive:u.target.checked}),className:"rounded"}),"Aktiv"]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:d,children:d?"Speichern...":"Speichern"})]})]})})}const Q3=[{value:"0.1",label:"10%"},{value:"0.2",label:"20%"},{value:"0.3",label:"30%"},{value:"0.4",label:"40%"},{value:"0.5",label:"50%"},{value:"0.6",label:"60%"},{value:"0.7",label:"70% (Standard)"},{value:"0.8",label:"80%"},{value:"0.9",label:"90%"},{value:"999",label:"Deaktiviert"}];function G3(){const{settings:t,updateSettings:e}=uC();return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:i.jsx(Yn,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Oe,{className:"w-6 h-6"}),i.jsx("h1",{className:"text-2xl font-bold",children:"Ansicht"})]})]}),i.jsx(Z,{title:"Scroll-Verhalten",children:i.jsx("div",{className:"space-y-6",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"font-medium",children:"Nach-oben-Button"}),i.jsx("p",{className:"text-sm text-gray-500",children:"Ab welcher Scroll-Position der Button unten rechts erscheinen soll"})]}),i.jsx("div",{className:"w-48",children:i.jsx(Fe,{options:Q3,value:t.scrollToTopThreshold.toString(),onChange:n=>e({scrollToTopThreshold:parseFloat(n.target.value)})})})]})})})]})}function J3(){const t=ye(),{data:e,isLoading:n}=fe({queryKey:["app-settings"],queryFn:()=>Ba.getAll()}),[s,r]=N.useState(!1);N.useEffect(()=>{e!=null&&e.data&&r(e.data.customerSupportTicketsEnabled==="true")},[e]);const a=G({mutationFn:o=>Ba.update(o),onSuccess:()=>{t.invalidateQueries({queryKey:["app-settings"]}),t.invalidateQueries({queryKey:["app-settings-public"]})}}),l=o=>{r(o),a.mutate({customerSupportTicketsEnabled:o?"true":"false"})};return n?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx("div",{className:"text-gray-500",children:"Laden..."})}):i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",className:"text-gray-500 hover:text-gray-700",children:i.jsx(Yn,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Ly,{className:"w-6 h-6"}),i.jsx("h1",{className:"text-2xl font-bold",children:"Kundenportal"})]})]}),i.jsxs(Z,{title:"Support-Anfragen",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Vc,{className:"w-5 h-5 text-gray-500"}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium",children:"Kunden können Support-Anfragen erstellen"}),i.jsx("p",{className:"text-sm text-gray-500",children:"Wenn aktiviert, können Kunden im Portal Support-Anfragen zu ihren Verträgen erstellen. Diese erscheinen als Aufgaben in der Vertragsdetailansicht."})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:s,onChange:o=>l(o.target.checked),disabled:a.isPending,className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),s&&i.jsx("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:i.jsxs("p",{className:"text-sm text-blue-800",children:[i.jsx("strong",{children:"Hinweis:"}),' Kunden sehen diese Anfragen als "Support-Anfragen" in ihrem Portal. Sie können die Anfrage mit einem Titel und einer Beschreibung erstellen. Ihre Mitarbeiter können dann mit Antworten (Unteraufgaben) reagieren.']})})]})]})}function Z3(){const t=ye(),{data:e,isLoading:n}=fe({queryKey:["app-settings"],queryFn:()=>Ba.getAll()}),[s,r]=N.useState("14"),[a,l]=N.useState("42"),[o,c]=N.useState("90"),[d,u]=N.useState(!1);N.useEffect(()=>{e!=null&&e.data&&(r(e.data.deadlineCriticalDays||"14"),l(e.data.deadlineWarningDays||"42"),c(e.data.deadlineOkDays||"90"),u(!1))},[e]);const h=G({mutationFn:p=>Ba.update(p),onSuccess:()=>{t.invalidateQueries({queryKey:["app-settings"]}),t.invalidateQueries({queryKey:["contract-cockpit"]}),u(!1)}}),m=()=>{const p=parseInt(s),g=parseInt(a),x=parseInt(o);if(isNaN(p)||isNaN(g)||isNaN(x)){alert("Bitte gültige Zahlen eingeben");return}if(p>=g||g>=x){alert("Die Werte müssen aufsteigend sein: Kritisch < Warnung < OK");return}h.mutate({deadlineCriticalDays:s,deadlineWarningDays:a,deadlineOkDays:o})},f=(p,g)=>{p(g),u(!0)};return n?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx("div",{className:"text-gray-500",children:"Laden..."})}):i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",className:"text-gray-500 hover:text-gray-700",children:i.jsx(Yn,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(cs,{className:"w-6 h-6"}),i.jsx("h1",{className:"text-2xl font-bold",children:"Fristenschwellen"})]})]}),i.jsxs(Z,{title:"Farbkodierung für Fristen",children:[i.jsx("p",{className:"text-gray-600 mb-6",children:"Definiere, ab wann Vertragsfristen als kritisch (rot), Warnung (gelb) oder OK (grün) angezeigt werden sollen. Die Werte geben die Anzahl der Tage bis zur Frist an."}),i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex items-center gap-4 p-4 bg-red-50 border border-red-200 rounded-lg",children:[i.jsx(Tr,{className:"w-8 h-8 text-red-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block font-medium text-red-800 mb-1",children:"Kritisch (Rot)"}),i.jsx("p",{className:"text-sm text-red-600 mb-2",children:"Fristen mit weniger als X Tagen werden rot markiert"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(q,{type:"number",min:"1",value:s,onChange:p=>f(r,p.target.value),className:"w-24"}),i.jsx("span",{className:"text-red-700",children:"Tage"})]})]})]}),i.jsxs("div",{className:"flex items-center gap-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg",children:[i.jsx(Mn,{className:"w-8 h-8 text-yellow-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block font-medium text-yellow-800 mb-1",children:"Warnung (Gelb)"}),i.jsx("p",{className:"text-sm text-yellow-600 mb-2",children:"Fristen mit weniger als X Tagen werden gelb markiert"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(q,{type:"number",min:"1",value:a,onChange:p=>f(l,p.target.value),className:"w-24"}),i.jsx("span",{className:"text-yellow-700",children:"Tage"})]})]})]}),i.jsxs("div",{className:"flex items-center gap-4 p-4 bg-green-50 border border-green-200 rounded-lg",children:[i.jsx(Un,{className:"w-8 h-8 text-green-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block font-medium text-green-800 mb-1",children:"OK (Grün)"}),i.jsx("p",{className:"text-sm text-green-600 mb-2",children:"Fristen mit weniger als X Tagen werden grün markiert (darüber nicht angezeigt)"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(q,{type:"number",min:"1",value:o,onChange:p=>f(c,p.target.value),className:"w-24"}),i.jsx("span",{className:"text-green-700",children:"Tage"})]})]})]})]}),i.jsxs("div",{className:"mt-6 pt-4 border-t flex justify-between items-center",children:[i.jsx("p",{className:"text-sm text-gray-500",children:"Beispiel: Bei 14/42/90 Tagen wird eine Frist die in 10 Tagen abläuft rot, eine in 30 Tagen gelb, und eine in 60 Tagen grün markiert."}),i.jsx(I,{onClick:m,disabled:!d||h.isPending,children:h.isPending?"Speichere...":"Speichern"})]})]})]})}const Y3=[{value:"PLESK",label:"Plesk"},{value:"CPANEL",label:"cPanel"},{value:"DIRECTADMIN",label:"DirectAdmin"}],tj=[{value:"SSL",label:"SSL/TLS",description:"Verschlüsselung von Anfang an"},{value:"STARTTLS",label:"STARTTLS",description:"Startet unverschlüsselt, dann Upgrade"},{value:"NONE",label:"Keine",description:"Keine Verschlüsselung"}],Bm={name:"",type:"PLESK",apiUrl:"",apiKey:"",username:"",password:"",domain:"stressfrei-wechseln.de",defaultForwardEmail:"",imapEncryption:"SSL",smtpEncryption:"SSL",allowSelfSignedCerts:!1,isActive:!0,isDefault:!1};function X3(){const t=fn(),e=ye(),[n,s]=N.useState(!1),[r,a]=N.useState(null),[l,o]=N.useState(Bm),[c,d]=N.useState(!1),[u,h]=N.useState(null),[m,f]=N.useState(!1),[p,g]=N.useState({}),[x,y]=N.useState(null),{data:v,isLoading:b}=fe({queryKey:["email-provider-configs"],queryFn:()=>wr.getConfigs()}),j=G({mutationFn:C=>wr.createConfig(C),onSuccess:()=>{e.invalidateQueries({queryKey:["email-provider-configs"]}),M()}}),k=G({mutationFn:({id:C,data:_})=>wr.updateConfig(C,_),onSuccess:()=>{e.invalidateQueries({queryKey:["email-provider-configs"]}),M()}}),E=G({mutationFn:C=>wr.deleteConfig(C),onSuccess:()=>{e.invalidateQueries({queryKey:["email-provider-configs"]})}}),T=(v==null?void 0:v.data)||[],w=()=>{o(Bm),a(null),d(!1),h(null),s(!0)},S=C=>{o({name:C.name,type:C.type,apiUrl:C.apiUrl,apiKey:C.apiKey||"",username:C.username||"",password:"",domain:C.domain,defaultForwardEmail:C.defaultForwardEmail||"",imapEncryption:C.imapEncryption??"SSL",smtpEncryption:C.smtpEncryption??"SSL",allowSelfSignedCerts:C.allowSelfSignedCerts??!1,isActive:C.isActive,isDefault:C.isDefault}),a(C.id),d(!1),h(null),s(!0)},M=()=>{s(!1),a(null),o(Bm),d(!1),h(null)},F=async C=>{var _,K,B;y(C.id),g(W=>({...W,[C.id]:null}));try{const W=await wr.testConnection({id:C.id}),ce={success:((_=W.data)==null?void 0:_.success)||!1,message:(K=W.data)==null?void 0:K.message,error:(B=W.data)==null?void 0:B.error};g(he=>({...he,[C.id]:ce}))}catch(W){g(ce=>({...ce,[C.id]:{success:!1,error:W instanceof Error?W.message:"Unbekannter Fehler beim Testen"}}))}finally{y(null)}},R=async()=>{var C,_,K;if(!l.apiUrl||!l.domain){h({success:!1,error:"Bitte geben Sie API-URL und Domain ein."});return}f(!0),h(null);try{const B=await wr.testConnection({testData:{type:l.type,apiUrl:l.apiUrl,apiKey:l.apiKey||void 0,username:l.username||void 0,password:l.password||void 0,domain:l.domain}});h({success:((C=B.data)==null?void 0:C.success)||!1,message:(_=B.data)==null?void 0:_.message,error:(K=B.data)==null?void 0:K.error})}catch(B){h({success:!1,error:B instanceof Error?B.message:"Unbekannter Fehler beim Verbindungstest"})}finally{f(!1)}},V=C=>{C.preventDefault();const _={name:l.name,type:l.type,apiUrl:l.apiUrl,apiKey:l.apiKey,username:l.username,domain:l.domain,defaultForwardEmail:l.defaultForwardEmail,imapEncryption:l.imapEncryption,smtpEncryption:l.smtpEncryption,allowSelfSignedCerts:l.allowSelfSignedCerts,isActive:l.isActive,isDefault:l.isDefault};l.password&&(_.password=l.password),r?k.mutate({id:r,data:_}):j.mutate(_)},D=(C,_)=>{confirm(`Möchten Sie den Provider "${_}" wirklich löschen?`)&&E.mutate(C)},z=C=>C.error?C.error:C.message?C.message:"Verbindung fehlgeschlagen";return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsxs(I,{variant:"ghost",onClick:()=>t("/settings"),children:[i.jsx(Yn,{className:"w-4 h-4 mr-2"}),"Zurück"]}),i.jsx("h1",{className:"text-2xl font-bold",children:"Email-Provisionierung"})]}),i.jsxs(Z,{className:"mb-6",children:[i.jsx("p",{className:"text-gray-600 mb-4",children:'Hier konfigurieren Sie die automatische Erstellung von Stressfrei-Wechseln E-Mail-Adressen. Wenn beim Anlegen einer Stressfrei-Adresse die Option "Bei Provider anlegen" aktiviert ist, wird die E-Mail-Weiterleitung automatisch erstellt.'}),i.jsxs(I,{onClick:w,children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Provider hinzufügen"]})]}),b?i.jsx("div",{className:"text-center py-8",children:"Laden..."}):T.length===0?i.jsx(Z,{children:i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Noch keine Email-Provider konfiguriert."})}):i.jsx("div",{className:"space-y-4",children:T.map(C=>{const _=p[C.id],K=x===C.id;return i.jsx(Z,{children:i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("h3",{className:"font-semibold text-lg",children:C.name}),i.jsx("span",{className:"px-2 py-1 text-xs rounded bg-blue-100 text-blue-800",children:C.type}),C.isDefault&&i.jsx("span",{className:"px-2 py-1 text-xs rounded bg-green-100 text-green-800",children:"Standard"}),!C.isActive&&i.jsx("span",{className:"px-2 py-1 text-xs rounded bg-gray-100 text-gray-600",children:"Inaktiv"})]}),i.jsxs("dl",{className:"mt-3 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"API-URL"}),i.jsx("dd",{className:"font-mono text-xs truncate",children:C.apiUrl})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"Domain"}),i.jsx("dd",{children:C.domain})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"Benutzer"}),i.jsx("dd",{children:C.username||"-"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-gray-500",children:"Standard-Weiterleitung"}),i.jsx("dd",{className:"truncate",children:C.defaultForwardEmail||"-"})]})]}),_&&i.jsx("div",{className:`mt-3 p-3 rounded-lg text-sm ${_.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:_.success?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Vr,{className:"w-4 h-4 flex-shrink-0"}),i.jsx("span",{children:"Verbindung erfolgreich!"})]}):i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(A1,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),i.jsx("span",{children:z(_)})]})})]}),i.jsxs("div",{className:"flex gap-2 ml-4",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>F(C),disabled:K,title:"Verbindung testen",children:K?i.jsx("span",{className:"w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin"}):i.jsx(Al,{className:"w-4 h-4 text-blue-500"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>S(C),children:i.jsx(rt,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>D(C.id,C.name),children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})]})},C.id)})}),n&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsx("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto",children:i.jsxs("div",{className:"p-6",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h2",{className:"text-xl font-semibold",children:r?"Provider bearbeiten":"Neuer Provider"}),i.jsx("button",{onClick:M,className:"text-gray-400 hover:text-gray-600",children:i.jsx(nn,{className:"w-5 h-5"})})]}),(j.error||k.error)&&i.jsx("div",{className:"mb-4 p-3 rounded-lg bg-red-50 text-red-800 text-sm",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(nn,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),i.jsx("span",{children:j.error instanceof Error?j.error.message:k.error instanceof Error?k.error.message:"Fehler beim Speichern"})]})}),i.jsxs("form",{onSubmit:V,className:"space-y-4",children:[i.jsx(q,{label:"Name *",value:l.name,onChange:C=>o({...l,name:C.target.value}),placeholder:"z.B. Plesk Hauptserver",required:!0}),i.jsx(Fe,{label:"Provider-Typ *",value:l.type,onChange:C=>o({...l,type:C.target.value}),options:Y3}),i.jsx(q,{label:"API-URL *",value:l.apiUrl,onChange:C=>o({...l,apiUrl:C.target.value}),placeholder:"https://server.de:8443",required:!0}),i.jsx(q,{label:"API-Key",value:l.apiKey,onChange:C=>o({...l,apiKey:C.target.value}),placeholder:"Optional - alternativ zu Benutzername/Passwort"}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(q,{label:"Benutzername",value:l.username,onChange:C=>o({...l,username:C.target.value}),placeholder:"admin"}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:r?"Neues Passwort (leer = beibehalten)":"Passwort"}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:c?"text":"password",value:l.password,onChange:C=>o({...l,password:C.target.value}),className:"block w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),i.jsx("button",{type:"button",onClick:()=>d(!c),className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600",children:c?i.jsx(on,{className:"w-4 h-4"}):i.jsx(Oe,{className:"w-4 h-4"})})]})]})]}),i.jsx(q,{label:"Domain *",value:l.domain,onChange:C=>o({...l,domain:C.target.value}),placeholder:"stressfrei-wechseln.de",required:!0}),i.jsx(q,{label:"Standard-Weiterleitungsadresse",value:l.defaultForwardEmail,onChange:C=>o({...l,defaultForwardEmail:C.target.value}),placeholder:"info@meinefirma.de",type:"email"}),i.jsx("p",{className:"text-xs text-gray-500 -mt-2",children:"Diese E-Mail-Adresse wird zusätzlich zur Kunden-E-Mail als Weiterleitungsziel hinzugefügt."}),i.jsxs("div",{className:"pt-4 border-t",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-700 mb-3",children:"E-Mail-Verbindungseinstellungen"}),i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["IMAP Verschlüsselung",i.jsxs("span",{className:"text-gray-400 font-normal ml-1",children:["(Port ",l.imapEncryption==="SSL"?"993":"143",")"]})]}),i.jsx("select",{value:l.imapEncryption,onChange:C=>o({...l,imapEncryption:C.target.value}),className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm",children:tj.map(C=>i.jsxs("option",{value:C.value,children:[C.label," - ",C.description]},C.value))})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["SMTP Verschlüsselung",i.jsxs("span",{className:"text-gray-400 font-normal ml-1",children:["(Port ",l.smtpEncryption==="SSL"?"465":l.smtpEncryption==="STARTTLS"?"587":"25",")"]})]}),i.jsx("select",{value:l.smtpEncryption,onChange:C=>o({...l,smtpEncryption:C.target.value}),className:"block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm",children:tj.map(C=>i.jsxs("option",{value:C.value,children:[C.label," - ",C.description]},C.value))})]})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:l.allowSelfSignedCerts,onChange:C=>o({...l,allowSelfSignedCerts:C.target.checked}),className:"rounded border-gray-300"}),i.jsx("span",{className:"text-sm",children:"Selbstsignierte Zertifikate erlauben"})]}),i.jsx("p",{className:"text-xs text-gray-500",children:"Aktivieren Sie diese Option für Testumgebungen mit selbstsignierten SSL-Zertifikaten."})]})]}),i.jsxs("div",{className:"flex gap-4",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:l.isActive,onChange:C=>o({...l,isActive:C.target.checked}),className:"rounded border-gray-300"}),i.jsx("span",{className:"text-sm",children:"Aktiv"})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:l.isDefault,onChange:C=>o({...l,isDefault:C.target.checked}),className:"rounded border-gray-300"}),i.jsx("span",{className:"text-sm",children:"Als Standard verwenden"})]})]}),i.jsxs("div",{className:"pt-4 border-t",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:R,disabled:m,className:"w-full",children:m?"Teste Verbindung...":i.jsxs(i.Fragment,{children:[i.jsx(Al,{className:"w-4 h-4 mr-2"}),"Verbindung testen"]})}),u&&i.jsx("div",{className:`mt-2 p-3 rounded-lg text-sm ${u.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:u.success?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Vr,{className:"w-4 h-4 flex-shrink-0"}),i.jsx("span",{children:"Verbindung erfolgreich!"})]}):i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(A1,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),i.jsx("span",{children:z(u)})]})})]}),i.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:M,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:j.isPending||k.isPending,children:j.isPending||k.isPending?"Speichern...":"Speichern"})]})]})]})})})]})}function eO(){const[t,e]=N.useState(null),[n,s]=N.useState(null),[r,a]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState(null),u=N.useRef(null),h=ye(),{logout:m}=nt(),{data:f,isLoading:p}=fe({queryKey:["backups"],queryFn:()=>Zi.list()}),g=(f==null?void 0:f.data)||[],x=G({mutationFn:()=>Zi.create(),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]})}}),y=G({mutationFn:S=>Zi.restore(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),e(null)}}),v=G({mutationFn:S=>Zi.delete(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),s(null)}}),b=G({mutationFn:S=>Zi.upload(S),onSuccess:()=>{h.invalidateQueries({queryKey:["backups"]}),d(null),u.current&&(u.current.value="")},onError:S=>{d(S.message||"Upload fehlgeschlagen")}}),j=G({mutationFn:()=>Zi.factoryReset(),onSuccess:()=>{a(!1),o(""),m()}}),k=S=>{var F;const M=(F=S.target.files)==null?void 0:F[0];if(M){if(!M.name.endsWith(".zip")){d("Nur ZIP-Dateien sind erlaubt");return}d(null),b.mutate(M)}},E=async S=>{const M=localStorage.getItem("token"),F=Zi.getDownloadUrl(S);try{const R=await fetch(F,{headers:{Authorization:`Bearer ${M}`}});if(!R.ok)throw new Error("Download fehlgeschlagen");const V=await R.blob(),D=window.URL.createObjectURL(V),z=document.createElement("a");z.href=D,z.download=`opencrm-backup-${S}.zip`,document.body.appendChild(z),z.click(),document.body.removeChild(z),window.URL.revokeObjectURL(D)}catch(R){console.error("Download error:",R)}},T=S=>new Date(S).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),w=S=>S<1024?`${S} B`:S<1024*1024?`${(S/1024).toFixed(1)} KB`:`${(S/(1024*1024)).toFixed(1)} MB`;return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-gray-900 flex items-center gap-2",children:[i.jsx(Rf,{className:"w-5 h-5"}),"Datenbank & Zurücksetzen"]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Backups erstellen, wiederherstellen oder auf Werkseinstellungen zurücksetzen."})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"file",ref:u,accept:".zip",onChange:k,className:"hidden"}),i.jsx(I,{variant:"secondary",onClick:()=>{var S;return(S=u.current)==null?void 0:S.click()},disabled:b.isPending,children:b.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ai,{className:"w-4 h-4 mr-2 animate-spin"}),"Hochladen..."]}):i.jsxs(i.Fragment,{children:[i.jsx(_g,{className:"w-4 h-4 mr-2"}),"Backup hochladen"]})}),i.jsx(I,{onClick:()=>x.mutate(),disabled:x.isPending,children:x.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ai,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird erstellt..."]}):i.jsxs(i.Fragment,{children:[i.jsx(qn,{className:"w-4 h-4 mr-2"}),"Neues Backup"]})})]})]}),c&&i.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-red-700",children:c}),i.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:[i.jsx("h4",{className:"text-sm font-medium text-blue-800 mb-2",children:"Hinweise zur Datensicherung"}),i.jsxs("ul",{className:"text-sm text-blue-700 space-y-1 list-disc list-inside",children:[i.jsx("li",{children:"Backups enthalten alle Datenbankdaten und hochgeladene Dokumente"}),i.jsx("li",{children:"Erstellen Sie vor Datenbankmigrationen immer ein Backup"}),i.jsx("li",{children:"Backups können als ZIP heruntergeladen und auf einem anderen System wiederhergestellt werden"}),i.jsx("li",{children:"Bei der Wiederherstellung werden bestehende Daten mit dem Backup-Stand überschrieben"})]})]}),i.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[i.jsx("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-200",children:i.jsx("h3",{className:"text-sm font-medium text-gray-700",children:"Verfügbare Backups"})}),p?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(ai,{className:"w-6 h-6 animate-spin text-gray-400"})}):g.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-gray-500",children:[i.jsx(S1,{className:"w-12 h-12 mb-2 opacity-30"}),i.jsx("p",{children:"Keine Backups vorhanden"}),i.jsx("p",{className:"text-sm mt-1",children:"Erstellen Sie Ihr erstes Backup"})]}):i.jsx("div",{className:"divide-y divide-gray-200",children:g.map(S=>i.jsx("div",{className:"p-4 hover:bg-gray-50",children:i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[i.jsx("span",{className:"font-mono text-sm bg-gray-100 px-2 py-1 rounded",children:S.name}),i.jsxs("span",{className:"text-sm text-gray-500 flex items-center gap-1",children:[i.jsx(cs,{className:"w-4 h-4"}),T(S.timestamp)]})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-600",children:[i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(We,{className:"w-4 h-4"}),S.totalRecords.toLocaleString("de-DE")," Datensätze"]}),i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(S1,{className:"w-4 h-4"}),w(S.sizeBytes)]}),S.hasUploads&&i.jsxs("span",{className:"flex items-center gap-1 text-green-600",children:[i.jsx(b5,{className:"w-4 h-4"}),"Dokumente (",w(S.uploadSizeBytes),")"]})]}),i.jsxs("details",{className:"mt-2",children:[i.jsxs("summary",{className:"text-xs text-gray-500 cursor-pointer hover:text-gray-700",children:["Tabellen anzeigen (",S.tables.filter(M=>M.count>0).length," mit Daten)"]}),i.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:S.tables.filter(M=>M.count>0).map(M=>i.jsxs("span",{className:"text-xs bg-gray-100 px-2 py-0.5 rounded",children:[M.table,": ",M.count]},M.table))})]})]}),i.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>E(S.name),title:"Als ZIP herunterladen",children:i.jsx(u5,{className:"w-4 h-4"})}),i.jsxs(I,{variant:"secondary",size:"sm",onClick:()=>e(S.name),disabled:y.isPending,children:[i.jsx(_g,{className:"w-4 h-4 mr-1"}),"Wiederherstellen"]}),i.jsx(I,{variant:"danger",size:"sm",onClick:()=>s(S.name),disabled:v.isPending,children:i.jsx(Ee,{className:"w-4 h-4"})})]})]})},S.name))})]}),t&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Backup wiederherstellen?"}),i.jsxs("p",{className:"text-gray-600 mb-4",children:["Möchten Sie das Backup ",i.jsx("strong",{children:t})," wirklich wiederherstellen?"]}),i.jsxs("p",{className:"text-amber-600 text-sm mb-4 bg-amber-50 p-3 rounded-lg",children:[i.jsx("strong",{children:"Achtung:"})," Bestehende Daten und Dokumente werden mit dem Backup-Stand überschrieben. Dies kann nicht rückgängig gemacht werden."]}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:()=>e(null),disabled:y.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"primary",onClick:()=>y.mutate(t),disabled:y.isPending,children:y.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ai,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird wiederhergestellt..."]}):"Ja, wiederherstellen"})]})]})}),n&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md mx-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Backup löschen?"}),i.jsxs("p",{className:"text-gray-600 mb-4",children:["Möchten Sie das Backup ",i.jsx("strong",{children:n})," wirklich löschen? Dies kann nicht rückgängig gemacht werden."]}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:()=>s(null),disabled:v.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"danger",onClick:()=>v.mutate(n),disabled:v.isPending,children:v.isPending?"Wird gelöscht...":"Ja, löschen"})]})]})}),i.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-6 mt-8",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:i.jsx(Mn,{className:"w-6 h-6 text-red-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-red-800 mb-2",children:"Werkseinstellungen"}),i.jsxs("p",{className:"text-sm text-red-700 mb-4",children:["Setzt das System auf den Ausgangszustand zurück. ",i.jsx("strong",{children:"Alle Daten werden unwiderruflich gelöscht"})," - Kunden, Verträge, Benutzer, Dokumente und Einstellungen. Nur die hier gespeicherten Backups bleiben erhalten."]}),i.jsxs("ul",{className:"text-sm text-red-700 mb-4 list-disc list-inside space-y-1",children:[i.jsx("li",{children:"Alle Kunden und Verträge werden gelöscht"}),i.jsx("li",{children:"Alle Benutzer werden gelöscht"}),i.jsx("li",{children:"Alle hochgeladenen Dokumente werden gelöscht"}),i.jsx("li",{children:"Ein neuer Admin-Benutzer wird erstellt (admin@admin.com / admin)"}),i.jsxs("li",{children:[i.jsx("strong",{children:"Backups bleiben erhalten"})," und können danach wiederhergestellt werden"]})]}),i.jsxs(I,{variant:"danger",onClick:()=>a(!0),children:[i.jsx(f5,{className:"w-4 h-4 mr-2"}),"Werkseinstellungen"]})]})]})}),r&&i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-lg mx-4",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-100 rounded-lg",children:i.jsx(Mn,{className:"w-6 h-6 text-red-600"})}),i.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Wirklich auf Werkseinstellungen zurücksetzen?"})]}),i.jsxs("p",{className:"text-gray-600 mb-4",children:["Diese Aktion löscht ",i.jsx("strong",{children:"alle Daten unwiderruflich"}),". Es gibt kein Zurück!"]}),i.jsxs("p",{className:"text-sm text-gray-600 mb-4",children:["Geben Sie zur Bestätigung ",i.jsx("strong",{className:"font-mono bg-gray-100 px-1",children:"LÖSCHEN"})," ein:"]}),i.jsx("input",{type:"text",value:l,onChange:S=>o(S.target.value),placeholder:"LÖSCHEN",className:"w-full px-3 py-2 border border-gray-300 rounded-lg mb-4 focus:ring-2 focus:ring-red-500 focus:border-red-500"}),i.jsxs("div",{className:"flex justify-end gap-3",children:[i.jsx(I,{variant:"secondary",onClick:()=>{a(!1),o("")},disabled:j.isPending,children:"Abbrechen"}),i.jsx(I,{variant:"danger",onClick:()=>j.mutate(),disabled:l!=="LÖSCHEN"||j.isPending,children:j.isPending?i.jsxs(i.Fragment,{children:[i.jsx(ai,{className:"w-4 h-4 mr-2 animate-spin"}),"Wird zurückgesetzt..."]}):"Ja, alles löschen"})]})]})})]})}const tO=[{value:"",label:"Alle Aktionen"},{value:"CREATE",label:"Erstellt"},{value:"READ",label:"Gelesen"},{value:"UPDATE",label:"Aktualisiert"},{value:"DELETE",label:"Gelöscht"},{value:"EXPORT",label:"Exportiert"},{value:"ANONYMIZE",label:"Anonymisiert"},{value:"LOGIN",label:"Login"},{value:"LOGOUT",label:"Logout"},{value:"LOGIN_FAILED",label:"Login fehlgeschlagen"}],nO=[{value:"",label:"Alle Stufen"},{value:"LOW",label:"Niedrig"},{value:"MEDIUM",label:"Mittel"},{value:"HIGH",label:"Hoch"},{value:"CRITICAL",label:"Kritisch"}],sO=[{value:"",label:"Alle Ressourcen"},{value:"Customer",label:"Kunden"},{value:"Contract",label:"Verträge"},{value:"User",label:"Benutzer"},{value:"BankCard",label:"Bankdaten"},{value:"IdentityDocument",label:"Ausweisdokumente"},{value:"Authentication",label:"Authentifizierung"},{value:"CustomerConsent",label:"Einwilligungen"},{value:"GDPR",label:"DSGVO"}];function BC(t){return new Date(t).toLocaleString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}function _C(t){switch(t){case"CREATE":return"bg-green-100 text-green-800";case"READ":return"bg-blue-100 text-blue-800";case"UPDATE":return"bg-yellow-100 text-yellow-800";case"DELETE":return"bg-red-100 text-red-800";case"EXPORT":return"bg-purple-100 text-purple-800";case"ANONYMIZE":return"bg-orange-100 text-orange-800";case"LOGIN":return"bg-teal-100 text-teal-800";case"LOGOUT":return"bg-gray-100 text-gray-800";case"LOGIN_FAILED":return"bg-red-200 text-red-900";default:return"bg-gray-100 text-gray-800"}}function VC(t){switch(t){case"LOW":return i.jsx(lr,{className:"w-4 h-4 text-gray-400"});case"MEDIUM":return i.jsx(lr,{className:"w-4 h-4 text-blue-500"});case"HIGH":return i.jsx(hh,{className:"w-4 h-4 text-orange-500"});case"CRITICAL":return i.jsx(hh,{className:"w-4 h-4 text-red-500"});default:return i.jsx(lr,{className:"w-4 h-4 text-gray-400"})}}function rO({log:t,onClose:e}){const n=a=>{if(!a)return null;try{return JSON.parse(a)}catch{return null}},s=n(t.changesBefore),r=n(t.changesAfter);return i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsx("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-3xl mx-4 max-h-[90vh] overflow-y-auto",children:i.jsxs("div",{className:"p-6",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h2",{className:"text-xl font-semibold",children:"Audit-Log Details"}),i.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-600",children:i.jsx(nn,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Zeitpunkt"}),i.jsx("dd",{className:"font-medium",children:BC(t.createdAt)})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Benutzer"}),i.jsx("dd",{className:"font-medium",children:t.userEmail})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Aktion"}),i.jsx("dd",{children:i.jsx("span",{className:`px-2 py-1 rounded text-xs font-medium ${_C(t.action)}`,children:t.action})})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Ressource"}),i.jsxs("dd",{className:"font-medium",children:[t.resourceType," ",t.resourceId&&`#${t.resourceId}`]})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Endpoint"}),i.jsxs("dd",{className:"font-mono text-sm",children:[t.httpMethod," ",t.endpoint]})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"IP-Adresse"}),i.jsx("dd",{className:"font-mono text-sm",children:t.ipAddress})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Sensitivität"}),i.jsxs("dd",{className:"flex items-center gap-2",children:[VC(t.sensitivity)," ",t.sensitivity]})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Dauer"}),i.jsx("dd",{children:t.durationMs?`${t.durationMs}ms`:"-"})]}),t.resourceLabel&&i.jsxs("div",{className:"col-span-2",children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Ressource-Bezeichnung"}),i.jsx("dd",{className:"font-medium",children:t.resourceLabel})]})]}),t.changesEncrypted&&i.jsx("div",{className:"mb-4 p-3 bg-yellow-50 text-yellow-800 rounded-lg text-sm",children:"Die Änderungsdaten sind verschlüsselt und können nur mit dem Encryption-Key eingesehen werden."}),(s||r)&&!t.changesEncrypted&&i.jsxs("div",{className:"border-t pt-4",children:[i.jsx("h3",{className:"font-medium mb-3",children:"Änderungen"}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Vorher"}),i.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto max-h-64",children:JSON.stringify(s,null,2)})]}),r&&i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Nachher"}),i.jsx("pre",{className:"bg-gray-50 p-3 rounded text-xs overflow-auto max-h-64",children:JSON.stringify(r,null,2)})]})]})]}),t.hash&&i.jsxs("div",{className:"border-t pt-4 mt-4",children:[i.jsx("h3",{className:"font-medium mb-2",children:"Integrität"}),i.jsxs("div",{className:"text-xs font-mono bg-gray-50 p-2 rounded break-all",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-gray-500",children:"Hash:"})," ",t.hash]}),t.previousHash&&i.jsxs("div",{className:"mt-1",children:[i.jsx("span",{className:"text-gray-500",children:"Vorheriger:"})," ",t.previousHash]})]})]}),i.jsx("div",{className:"flex justify-end mt-6 pt-4 border-t",children:i.jsx(I,{variant:"secondary",onClick:e,children:"Schließen"})})]})})})}function iO(){const t=fn(),[e,n]=N.useState(1),[s,r]=N.useState({page:1,limit:50}),[a,l]=N.useState(null),{data:o,isLoading:c,refetch:d}=fe({queryKey:["audit-logs",{...s,page:e}],queryFn:()=>Pm.search({...s,page:e})}),u=G({mutationFn:()=>Pm.verifyIntegrity(),onSuccess:g=>{var x,y,v;(x=g.data)!=null&&x.valid?alert("Hash-Kette ist intakt. Keine Manipulationen festgestellt."):alert(`Integritätsfehler gefunden: +${(v=(y=g.data)==null?void 0:y.errors)==null?void 0:v.join(` +`)}`)},onError:g=>{alert(`Fehler bei der Integritätsprüfung: ${g instanceof Error?g.message:"Unbekannter Fehler"}`)}}),h=(o==null?void 0:o.data)||[],m=o==null?void 0:o.pagination,f=(g,x)=>{r(y=>({...y,[g]:x||void 0})),n(1)},p=async g=>{try{const y=(await Pm.export({...s,format:g})).data,v=new Blob([g==="json"?JSON.stringify(y,null,2):""],{type:g==="json"?"application/json":"text/csv"}),b=URL.createObjectURL(v),j=document.createElement("a");j.href=b,j.download=`audit-logs-${new Date().toISOString().split("T")[0]}.${g}`,j.click(),URL.revokeObjectURL(b)}catch(x){alert(`Export fehlgeschlagen: ${x instanceof Error?x.message:"Unbekannter Fehler"}`)}};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsxs(I,{variant:"ghost",onClick:()=>t("/settings"),children:[i.jsx(Yn,{className:"w-4 h-4 mr-2"}),"Zurück"]}),i.jsx("h1",{className:"text-2xl font-bold",children:"Audit-Protokoll"})]}),i.jsxs(Z,{className:"mb-6",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-4",children:[i.jsx(q,{placeholder:"Suche...",value:s.search||"",onChange:g=>f("search",g.target.value),className:"w-full"}),i.jsx(Fe,{value:s.action||"",onChange:g=>f("action",g.target.value),options:tO}),i.jsx(Fe,{value:s.resourceType||"",onChange:g=>f("resourceType",g.target.value),options:sO}),i.jsx(Fe,{value:s.sensitivity||"",onChange:g=>f("sensitivity",g.target.value),options:nO})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-4",children:[i.jsx(q,{type:"date",label:"Von",value:s.startDate||"",onChange:g=>f("startDate",g.target.value)}),i.jsx(q,{type:"date",label:"Bis",value:s.endDate||"",onChange:g=>f("endDate",g.target.value)}),i.jsx("div",{}),i.jsxs("div",{className:"flex gap-2 justify-end items-end",children:[i.jsxs(I,{variant:"secondary",onClick:()=>d(),children:[i.jsx(ai,{className:"w-4 h-4 mr-2"}),"Aktualisieren"]}),i.jsxs(I,{variant:"secondary",onClick:()=>p("json"),children:[i.jsx(qn,{className:"w-4 h-4 mr-2"}),"Export"]}),i.jsxs(I,{variant:"secondary",onClick:()=>u.mutate(),disabled:u.isPending,children:[i.jsx(SC,{className:"w-4 h-4 mr-2"}),u.isPending?"Prüfe...":"Integrität"]})]})]})]}),i.jsx(Z,{children:c?i.jsx("div",{className:"text-center py-8",children:"Laden..."}):h.length===0?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Audit-Logs gefunden."}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4",children:"Zeitpunkt"}),i.jsx("th",{className:"text-left py-3 px-4",children:"Benutzer"}),i.jsx("th",{className:"text-left py-3 px-4",children:"Aktion"}),i.jsx("th",{className:"text-left py-3 px-4",children:"Ressource"}),i.jsx("th",{className:"text-left py-3 px-4",children:"IP"}),i.jsx("th",{className:"text-center py-3 px-4"}),i.jsx("th",{className:"text-center py-3 px-4"})]})}),i.jsx("tbody",{children:h.map(g=>i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsx("td",{className:"py-3 px-4 whitespace-nowrap",children:BC(g.createdAt)}),i.jsxs("td",{className:"py-3 px-4",children:[i.jsx("div",{className:"truncate max-w-[200px]",title:g.userEmail,children:g.userEmail}),g.userRole&&i.jsx("div",{className:"text-xs text-gray-500",children:g.userRole})]}),i.jsx("td",{className:"py-3 px-4",children:i.jsx("span",{className:`px-2 py-1 rounded text-xs font-medium ${_C(g.action)}`,children:g.action})}),i.jsxs("td",{className:"py-3 px-4",children:[i.jsx("div",{children:g.resourceType}),g.resourceLabel&&i.jsx("div",{className:"text-xs text-gray-500 truncate max-w-[200px]",title:g.resourceLabel,children:g.resourceLabel})]}),i.jsx("td",{className:"py-3 px-4 font-mono text-xs",children:g.ipAddress}),i.jsx("td",{className:"py-3 px-4 text-center",children:VC(g.sensitivity)}),i.jsx("td",{className:"py-3 px-4 text-center",children:i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>l(g),children:i.jsx(Oe,{className:"w-4 h-4"})})})]},g.id))})]})}),m&&m.totalPages>1&&i.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[i.jsxs("div",{className:"text-sm text-gray-500",children:["Seite ",m.page," von ",m.totalPages," (",m.total," Einträge)"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>n(g=>Math.max(1,g-1)),disabled:e===1,children:i.jsx(xC,{className:"w-4 h-4"})}),i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>n(g=>Math.min(m.totalPages,g+1)),disabled:e===m.totalPages,children:i.jsx(At,{className:"w-4 h-4"})})]})]})]})}),a&&i.jsx(rO,{log:a,onClose:()=>l(null)})]})}const aO=[{value:"",label:"Alle Status"},{value:"PENDING",label:"Ausstehend"},{value:"IN_PROGRESS",label:"In Bearbeitung"},{value:"COMPLETED",label:"Abgeschlossen"},{value:"PARTIALLY_COMPLETED",label:"Teilweise abgeschlossen"},{value:"REJECTED",label:"Abgelehnt"}];function lO(t){switch(t){case"PENDING":return i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-yellow-100 text-yellow-800",children:[i.jsx(cs,{className:"w-3 h-3"})," Ausstehend"]});case"IN_PROGRESS":return i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800",children:[i.jsx(cs,{className:"w-3 h-3"})," In Bearbeitung"]});case"COMPLETED":return i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800",children:[i.jsx(Un,{className:"w-3 h-3"})," Abgeschlossen"]});case"PARTIALLY_COMPLETED":return i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-orange-100 text-orange-800",children:[i.jsx(Mn,{className:"w-3 h-3"})," Teilweise"]});case"REJECTED":return i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium bg-red-100 text-red-800",children:[i.jsx(Bg,{className:"w-3 h-3"})," Abgelehnt"]});default:return i.jsx("span",{className:"px-2 py-1 rounded text-xs bg-gray-100",children:t})}}function Hg(t){return new Date(t).toLocaleDateString("de-DE",{day:"2-digit",month:"2-digit",year:"numeric"})}function oO({request:t,onClose:e,onProcess:n,isPending:s}){var c,d,u;const[r,a]=N.useState("complete"),[l,o]=N.useState("");return i.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:i.jsx("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-lg mx-4",children:i.jsxs("div",{className:"p-6",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h2",{className:"text-xl font-semibold",children:"Löschanfrage bearbeiten"}),i.jsx("button",{onClick:e,className:"text-gray-400 hover:text-gray-600",children:i.jsx(nn,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"mb-4 p-4 bg-gray-50 rounded-lg",children:[i.jsx("p",{className:"text-sm text-gray-600",children:"Kunde:"}),i.jsxs("p",{className:"font-medium",children:[(c=t.customer)==null?void 0:c.firstName," ",(d=t.customer)==null?void 0:d.lastName," (",(u=t.customer)==null?void 0:u.customerNumber,")"]}),i.jsxs("p",{className:"text-sm text-gray-600 mt-2",children:["Quelle: ",t.requestSource]}),i.jsxs("p",{className:"text-sm text-gray-600",children:["Angefordert: ",Hg(t.requestedAt)]})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Aktion"}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-3 p-3 border rounded-lg cursor-pointer hover:bg-gray-50",children:[i.jsx("input",{type:"radio",name:"action",checked:r==="complete",onChange:()=>a("complete"),className:"text-blue-600"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"Vollständig löschen"}),i.jsx("div",{className:"text-sm text-gray-500",children:"Alle Kundendaten werden anonymisiert"})]})]}),i.jsxs("label",{className:"flex items-center gap-3 p-3 border rounded-lg cursor-pointer hover:bg-gray-50",children:[i.jsx("input",{type:"radio",name:"action",checked:r==="partial",onChange:()=>a("partial"),className:"text-blue-600"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"Teilweise löschen"}),i.jsx("div",{className:"text-sm text-gray-500",children:"Nur optionale Daten werden gelöscht (aktive Verträge bleiben)"})]})]}),i.jsxs("label",{className:"flex items-center gap-3 p-3 border rounded-lg cursor-pointer hover:bg-gray-50",children:[i.jsx("input",{type:"radio",name:"action",checked:r==="reject",onChange:()=>a("reject"),className:"text-blue-600"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"Ablehnen"}),i.jsx("div",{className:"text-sm text-gray-500",children:"Löschanfrage kann nicht durchgeführt werden"})]})]})]})]}),(r==="partial"||r==="reject")&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Begründung ",r==="reject"&&"*"]}),i.jsx("textarea",{value:l,onChange:h=>o(h.target.value),rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Grund für die teilweise Löschung/Ablehnung...",required:r==="reject"})]})]}),i.jsxs("div",{className:"flex justify-end gap-3 mt-6 pt-4 border-t",children:[i.jsx(I,{variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{onClick:()=>n(r,l||void 0),disabled:s||r==="reject"&&!l,children:s?"Verarbeite...":"Durchführen"})]})]})})})}function cO(){const t=fn(),e=ye(),[n,s]=N.useState(""),[r,a]=N.useState(null),{data:l}=fe({queryKey:["gdpr-stats"],queryFn:()=>Mr.getDashboardStats()}),{data:o,isLoading:c}=fe({queryKey:["deletion-requests",n],queryFn:()=>Mr.getDeletionRequests({status:n||void 0})}),{data:d}=fe({queryKey:["consent-overview"],queryFn:()=>Mr.getConsentOverview()}),u=G({mutationFn:({id:x,data:y})=>Mr.processDeletionRequest(x,y),onSuccess:()=>{e.invalidateQueries({queryKey:["deletion-requests"]}),e.invalidateQueries({queryKey:["gdpr-stats"]}),a(null)}}),h=l==null?void 0:l.data,m=(o==null?void 0:o.data)||[],f=(d==null?void 0:d.data)||{},p=(x,y)=>{if(!r)return;const v=JSON.parse(localStorage.getItem("user")||"{}");u.mutate({id:r.id,data:{processedBy:v.email||"System",action:x,retentionReason:y}})},g={DATA_PROCESSING:"Datenverarbeitung",MARKETING_EMAIL:"E-Mail-Marketing",MARKETING_PHONE:"Telefonmarketing",DATA_SHARING_PARTNER:"Datenweitergabe"};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsxs(I,{variant:"ghost",onClick:()=>t("/settings"),children:[i.jsx(Yn,{className:"w-4 h-4 mr-2"}),"Zurück"]}),i.jsx("h1",{className:"text-2xl font-bold",children:"DSGVO-Dashboard"})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-6",children:[i.jsx(Z,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("div",{className:"p-3 bg-yellow-100 rounded-lg",children:i.jsx(cs,{className:"w-6 h-6 text-yellow-600"})}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold",children:(h==null?void 0:h.deletionRequests.pending)??"-"}),i.jsx("div",{className:"text-sm text-gray-500",children:"Offene Löschanfragen"})]})]})}),i.jsx(Z,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("div",{className:"p-3 bg-green-100 rounded-lg",children:i.jsx(Un,{className:"w-6 h-6 text-green-600"})}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold",children:(h==null?void 0:h.deletionRequests.completedLast30Days)??"-"}),i.jsx("div",{className:"text-sm text-gray-500",children:"Gelöscht (30 Tage)"})]})]})}),i.jsx(Z,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("div",{className:"p-3 bg-purple-100 rounded-lg",children:i.jsx(qn,{className:"w-6 h-6 text-purple-600"})}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold",children:(h==null?void 0:h.dataExports.last30Days)??"-"}),i.jsx("div",{className:"text-sm text-gray-500",children:"Datenexporte (30 Tage)"})]})]})}),i.jsx(Z,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("div",{className:"p-3 bg-blue-100 rounded-lg",children:i.jsx(Ca,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold",children:(h==null?void 0:h.consents.granted)??"-"}),i.jsx("div",{className:"text-sm text-gray-500",children:"Aktive Einwilligungen"})]})]})})]}),Object.keys(f).length>0&&i.jsxs(Z,{className:"mb-6",children:[i.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Einwilligungen nach Typ"}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:Object.entries(f).map(([x,y])=>i.jsxs("div",{className:"p-4 bg-gray-50 rounded-lg",children:[i.jsx("div",{className:"font-medium mb-2",children:g[x]||x}),i.jsxs("div",{className:"flex gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-green-600 font-medium",children:y.granted}),i.jsx("span",{className:"text-gray-500 ml-1",children:"erteilt"})]}),i.jsxs("div",{children:[i.jsx("span",{className:"text-red-600 font-medium",children:y.withdrawn}),i.jsx("span",{className:"text-gray-500 ml-1",children:"widerrufen"})]}),i.jsxs("div",{children:[i.jsx("span",{className:"text-gray-600 font-medium",children:y.pending}),i.jsx("span",{className:"text-gray-500 ml-1",children:"ausstehend"})]})]})]},x))})]}),i.jsxs(Z,{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold",children:"Löschanfragen"}),i.jsx(Fe,{value:n,onChange:x=>s(x.target.value),options:aO,className:"w-48"})]}),c?i.jsx("div",{className:"text-center py-8",children:"Laden..."}):m.length===0?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Löschanfragen gefunden."}):i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4",children:"Kunde"}),i.jsx("th",{className:"text-left py-3 px-4",children:"Status"}),i.jsx("th",{className:"text-left py-3 px-4",children:"Quelle"}),i.jsx("th",{className:"text-left py-3 px-4",children:"Angefordert"}),i.jsx("th",{className:"text-left py-3 px-4",children:"Bearbeitet"}),i.jsx("th",{className:"text-center py-3 px-4"})]})}),i.jsx("tbody",{children:m.map(x=>i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsx("td",{className:"py-3 px-4",children:x.customer?i.jsxs("div",{children:[i.jsxs("div",{className:"font-medium",children:[x.customer.firstName," ",x.customer.lastName]}),i.jsx("div",{className:"text-xs text-gray-500",children:x.customer.customerNumber})]}):i.jsxs("span",{className:"text-gray-400",children:["Kunde #",x.customerId]})}),i.jsx("td",{className:"py-3 px-4",children:lO(x.status)}),i.jsx("td",{className:"py-3 px-4",children:x.requestSource}),i.jsxs("td",{className:"py-3 px-4",children:[i.jsx("div",{children:Hg(x.requestedAt)}),i.jsxs("div",{className:"text-xs text-gray-500",children:["von ",x.requestedBy]})]}),i.jsx("td",{className:"py-3 px-4",children:x.processedAt?i.jsxs("div",{children:[i.jsx("div",{children:Hg(x.processedAt)}),i.jsxs("div",{className:"text-xs text-gray-500",children:["von ",x.processedBy]})]}):i.jsx("span",{className:"text-gray-400",children:"-"})}),i.jsxs("td",{className:"py-3 px-4 text-center",children:[(x.status==="PENDING"||x.status==="IN_PROGRESS")&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>a(x),children:i.jsx(At,{className:"w-4 h-4"})}),x.proofDocument&&i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>window.open(`/api/uploads/${x.proofDocument}`,"_blank"),title:"Löschnachweis anzeigen",children:i.jsx(We,{className:"w-4 h-4 text-blue-500"})})]})]},x.id))})]})})]}),r&&i.jsx(oO,{request:r,onClose:()=>a(null),onProcess:p,isPending:u.isPending})]})}function dO(){var v;const[t,e]=N.useState(""),[n,s]=N.useState(1),[r,a]=N.useState(!1),[l,o]=N.useState(null),c=ye(),{refreshUser:d}=nt(),{data:u,isLoading:h}=fe({queryKey:["users",t,n],queryFn:()=>sc.getAll({search:t||void 0,page:n,limit:20})}),{data:m}=fe({queryKey:["roles"],queryFn:()=>sc.getRoles()}),f=G({mutationFn:sc.delete,onSuccess:()=>{c.invalidateQueries({queryKey:["users"]})},onError:b=>{alert((b==null?void 0:b.message)||"Fehler beim Löschen des Benutzers")}}),p=b=>{var j;return(j=b.roles)==null?void 0:j.some(k=>k.name==="Admin")},g=((v=u==null?void 0:u.data)==null?void 0:v.filter(b=>b.isActive&&p(b)).length)||0,x=b=>{o(b),a(!0)},y=()=>{a(!1),o(null)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(Yn,{className:"w-4 h-4"})})}),i.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Benutzer"}),i.jsxs(I,{onClick:()=>a(!0),children:[i.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Neuer Benutzer"]})]}),i.jsx(Z,{className:"mb-6",children:i.jsxs("div",{className:"flex gap-4",children:[i.jsx("div",{className:"flex-1",children:i.jsx(q,{placeholder:"Suchen...",value:t,onChange:b=>e(b.target.value)})}),i.jsx(I,{variant:"secondary",children:i.jsx(jd,{className:"w-4 h-4"})})]})}),i.jsxs("div",{className:"mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3",children:[i.jsx(bd,{className:"w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-sm text-blue-800",children:[i.jsx("strong",{children:"Hinweis:"})," Bei Änderungen an Rollen oder Berechtigungen wird der betroffene Benutzer automatisch ausgeloggt und muss sich erneut anmelden."]})]}),i.jsx(Z,{children:h?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):u!=null&&u.data&&u.data.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b",children:[i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Name"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"E-Mail"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Rollen"}),i.jsx("th",{className:"text-left py-3 px-4 font-medium text-gray-600",children:"Status"}),i.jsx("th",{className:"text-right py-3 px-4 font-medium text-gray-600",children:"Aktionen"})]})}),i.jsx("tbody",{children:u.data.map(b=>{var j;return i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[i.jsxs("td",{className:"py-3 px-4",children:[b.firstName," ",b.lastName]}),i.jsx("td",{className:"py-3 px-4",children:b.email}),i.jsx("td",{className:"py-3 px-4",children:i.jsx("div",{className:"flex gap-1 flex-wrap",children:(j=b.roles)==null?void 0:j.filter(k=>!["Developer","Kunde","DSGVO"].includes(k.name)).map(k=>i.jsx(je,{variant:"info",children:k.name},k.id||k.name))})}),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(je,{variant:b.isActive?"success":"danger",children:b.isActive?"Aktiv":"Inaktiv"}),b.hasDeveloperAccess&&i.jsxs(je,{variant:"warning",className:"flex items-center gap-1",children:[i.jsx(la,{className:"w-3 h-3"}),"Dev"]}),b.hasGdprAccess&&i.jsxs(je,{variant:"info",className:"flex items-center gap-1",children:[i.jsx(lr,{className:"w-3 h-3"}),"DSGVO"]})]})}),i.jsx("td",{className:"py-3 px-4 text-right",children:i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>x(b),children:i.jsx(rt,{className:"w-4 h-4"})}),(()=>{const k=p(b)&&b.isActive&&g<=1;return i.jsx(I,{variant:"ghost",size:"sm",disabled:k,title:k?"Letzter Administrator kann nicht gelöscht werden":void 0,onClick:()=>{confirm("Benutzer wirklich löschen?")&&f.mutate(b.id)},children:i.jsx(Ee,{className:`w-4 h-4 ${k?"text-gray-300":"text-red-500"}`})})})()]})})]},b.id)})})]})}),u.pagination&&u.pagination.totalPages>1&&i.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[i.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",u.pagination.page," von ",u.pagination.totalPages]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>s(b=>Math.max(1,b-1)),disabled:n===1,children:"Zurück"}),i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>s(b=>b+1),disabled:n>=u.pagination.totalPages,children:"Weiter"})]})]})]}):i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Keine Benutzer gefunden."})}),i.jsx(uO,{isOpen:r,onClose:y,user:l,roles:(m==null?void 0:m.data)||[],onUserUpdated:d})]})}function uO({isOpen:t,onClose:e,user:n,roles:s,onUserUpdated:r}){const a=ye(),[l,o]=N.useState(null),[c,d]=N.useState({email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1,hasGdprAccess:!1,whatsappNumber:"",telegramUsername:"",signalNumber:""});N.useEffect(()=>{var g;t&&(o(null),d(n?{email:n.email,password:"",firstName:n.firstName,lastName:n.lastName,roleIds:((g=n.roles)==null?void 0:g.filter(x=>!["Developer","Kunde","DSGVO"].includes(x.name)).map(x=>x.id))||[],isActive:n.isActive??!0,hasDeveloperAccess:n.hasDeveloperAccess??!1,hasGdprAccess:n.hasGdprAccess??!1,whatsappNumber:n.whatsappNumber||"",telegramUsername:n.telegramUsername||"",signalNumber:n.signalNumber||""}:{email:"",password:"",firstName:"",lastName:"",roleIds:[],isActive:!0,hasDeveloperAccess:!1,hasGdprAccess:!1,whatsappNumber:"",telegramUsername:"",signalNumber:""}))},[t,n]);const u=G({mutationFn:sc.create,onSuccess:()=>{a.invalidateQueries({queryKey:["users"]}),e()},onError:g=>{o((g==null?void 0:g.message)||"Fehler beim Erstellen des Benutzers")}}),h=G({mutationFn:g=>sc.update(n.id,g),onSuccess:async()=>{a.invalidateQueries({queryKey:["users"]}),await r(),e()},onError:g=>{o((g==null?void 0:g.message)||"Fehler beim Aktualisieren des Benutzers")}}),m=g=>{if(g.preventDefault(),n){const x={email:c.email,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,isActive:c.isActive,hasDeveloperAccess:c.hasDeveloperAccess,hasGdprAccess:c.hasGdprAccess,whatsappNumber:c.whatsappNumber||void 0,telegramUsername:c.telegramUsername||void 0,signalNumber:c.signalNumber||void 0};c.password&&(x.password=c.password),h.mutate(x)}else u.mutate({email:c.email,password:c.password,firstName:c.firstName,lastName:c.lastName,roleIds:c.roleIds,hasDeveloperAccess:c.hasDeveloperAccess,hasGdprAccess:c.hasGdprAccess,whatsappNumber:c.whatsappNumber||void 0,telegramUsername:c.telegramUsername||void 0,signalNumber:c.signalNumber||void 0})},f=g=>{d(x=>({...x,roleIds:x.roleIds.includes(g)?x.roleIds.filter(y=>y!==g):[...x.roleIds,g]}))},p=u.isPending||h.isPending;return i.jsx(Xe,{isOpen:t,onClose:e,title:n?"Benutzer bearbeiten":"Neuer Benutzer",children:i.jsxs("form",{onSubmit:m,className:"space-y-4",children:[l&&i.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 flex items-start gap-2",children:[i.jsx(Mn,{className:"w-5 h-5 text-red-500 flex-shrink-0 mt-0.5"}),i.jsx("p",{className:"text-red-700 text-sm",children:l})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(q,{label:"Vorname *",value:c.firstName,onChange:g=>d({...c,firstName:g.target.value}),required:!0}),i.jsx(q,{label:"Nachname *",value:c.lastName,onChange:g=>d({...c,lastName:g.target.value}),required:!0})]}),i.jsx(q,{label:"E-Mail *",type:"email",value:c.email,onChange:g=>d({...c,email:g.target.value}),required:!0}),i.jsx(q,{label:n?"Neues Passwort (leer = unverändert)":"Passwort *",type:"password",value:c.password,onChange:g=>d({...c,password:g.target.value}),required:!n}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Messaging-Kanäle (für Datenschutz-Versand)"}),i.jsxs("div",{className:"space-y-3",children:[i.jsx(q,{label:"WhatsApp-Nummer",placeholder:"+49...",value:c.whatsappNumber,onChange:g=>d({...c,whatsappNumber:g.target.value})}),i.jsx(q,{label:"Telegram-Benutzername",placeholder:"@username",value:c.telegramUsername,onChange:g=>d({...c,telegramUsername:g.target.value})}),i.jsx(q,{label:"Signal-Nummer",placeholder:"+49...",value:c.signalNumber,onChange:g=>d({...c,signalNumber:g.target.value})})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Rollen"}),i.jsx("div",{className:"space-y-2",children:s.filter(g=>!["Developer","Kunde","DSGVO"].includes(g.name)).map(g=>i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:c.roleIds.includes(g.id),onChange:()=>f(g.id),className:"rounded"}),i.jsx("span",{children:g.name}),g.description&&i.jsxs("span",{className:"text-sm text-gray-500",children:["(",g.description,")"]})]},g.id))}),i.jsx("label",{className:"block text-sm font-medium text-gray-700 mt-4 mb-2",children:"Zusätzliche Berechtigungen"}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:c.hasGdprAccess,onChange:g=>d({...c,hasGdprAccess:g.target.checked}),className:"rounded border-blue-300 text-blue-600 focus:ring-blue-500"}),i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(lr,{className:"w-4 h-4 text-blue-600"}),"DSGVO-Zugriff"]}),i.jsx("span",{className:"text-sm text-gray-500",children:"(Audit-Logs, Datenschutz)"})]}),i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:c.hasDeveloperAccess,onChange:g=>d({...c,hasDeveloperAccess:g.target.checked}),className:"rounded border-purple-300 text-purple-600 focus:ring-purple-500"}),i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(la,{className:"w-4 h-4 text-purple-600"}),"Entwicklerzugriff"]}),i.jsx("span",{className:"text-sm text-gray-500",children:"(Datenbanktools)"})]})]}),n&&i.jsxs("p",{className:"mt-2 text-xs text-amber-600 flex items-center gap-1",children:[i.jsx(Mn,{className:"w-3 h-3"}),"Bei Rollenänderung wird der Benutzer automatisch ausgeloggt."]})]}),n&&i.jsx("div",{className:"space-y-3 pt-3 border-t",children:i.jsxs("label",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",checked:c.isActive,onChange:g=>d({...c,isActive:g.target.checked}),className:"rounded"}),"Aktiv"]})}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(I,{type:"button",variant:"secondary",onClick:e,children:"Abbrechen"}),i.jsx(I,{type:"submit",disabled:p,children:p?"Speichern...":"Speichern"})]})]})})}function hO(){const{hasPermission:t,developerMode:e,setDeveloperMode:n}=nt(),s=[{to:"/settings/users",icon:K5,title:"Benutzer",description:"Verwalten Sie Benutzerkonten, Rollen und Berechtigungen.",show:t("users:read")},{to:"/settings/platforms",icon:$5,title:"Vertriebsplattformen",description:"Verwalten Sie die Plattformen, über die Verträge abgeschlossen werden.",show:t("platforms:read")},{to:"/settings/cancellation-periods",icon:cs,title:"Kündigungsfristen",description:"Konfigurieren Sie die verfügbaren Kündigungsfristen für Verträge.",show:t("platforms:read")},{to:"/settings/contract-durations",icon:pC,title:"Vertragslaufzeiten",description:"Konfigurieren Sie die verfügbaren Laufzeiten für Verträge.",show:t("platforms:read")},{to:"/settings/providers",icon:p5,title:"Anbieter & Tarife",description:"Verwalten Sie Anbieter und deren Tarife für Verträge.",show:t("providers:read")||t("platforms:read")},{to:"/settings/contract-categories",icon:v5,title:"Vertragstypen",description:"Konfigurieren Sie die verfügbaren Vertragstypen (Strom, Gas, Mobilfunk, etc.).",show:t("platforms:read")}];return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[i.jsx(kC,{className:"w-6 h-6"}),i.jsx("h1",{className:"text-2xl font-bold",children:"Einstellungen"})]}),i.jsxs("div",{className:"mb-8",children:[i.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"Stammdaten"}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:s.filter(r=>r.show).map(r=>i.jsx(Me,{to:r.to,className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(r.icon,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:[r.title,i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:r.description})]})]})},r.to))})]}),t("settings:update")&&i.jsxs("div",{className:"mb-8",children:[i.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"System"}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsx(Me,{to:"/settings/portal",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(Ly,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Kundenportal",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie das Kundenportal und Support-Anfragen."})]})]})}),i.jsx(Me,{to:"/settings/deadlines",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(cs,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Fristenschwellen",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie die Farbkodierung für Vertragsfristen im Cockpit."})]})]})}),i.jsx(Me,{to:"/settings/email-providers",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(Fs,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Email-Provisionierung",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Konfigurieren Sie die automatische E-Mail-Erstellung für Stressfrei-Wechseln Adressen."})]})]})}),i.jsx(Me,{to:"/settings/database-backup",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(Rf,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Datenbank & Zurücksetzen",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Backups erstellen, wiederherstellen oder auf Werkseinstellungen zurücksetzen."})]})]})}),t("audit:read")&&i.jsx(Me,{to:"/settings/audit-logs",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(We,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Audit-Protokoll",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Protokollierte API-Zugriffe und Änderungen einsehen."}),t("developer:access")&&i.jsxs("p",{className:"text-xs text-purple-500 mt-1 flex items-center gap-1",children:[i.jsx(la,{className:"w-3 h-3"}),"Sichtbar durch Entwicklerzugriff"]})]})]})}),t("gdpr:admin")&&i.jsx(Me,{to:"/settings/gdpr",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(lr,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["DSGVO-Dashboard",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Löschanfragen, Datenexporte und Einwilligungen verwalten."}),t("developer:access")&&i.jsxs("p",{className:"text-xs text-purple-500 mt-1 flex items-center gap-1",children:[i.jsx(la,{className:"w-3 h-3"}),"Sichtbar durch Entwicklerzugriff"]})]})]})}),t("gdpr:admin")&&i.jsx(Me,{to:"/settings/privacy-policy",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(y5,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Datenschutzerklärung",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Datenschutzerklärung bearbeiten mit Platzhaltern für Kundendaten."}),t("developer:access")&&i.jsxs("p",{className:"text-xs text-purple-500 mt-1 flex items-center gap-1",children:[i.jsx(la,{className:"w-3 h-3"}),"Sichtbar durch Entwicklerzugriff"]})]})]})})]})]}),i.jsxs("div",{className:"mb-8",children:[i.jsx("h2",{className:"text-lg font-semibold mb-4 text-gray-700",children:"Persönlich"}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:i.jsx(Me,{to:"/settings/view",className:"block p-4 bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md hover:border-blue-300 transition-all group",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx("div",{className:"p-2 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors",children:i.jsx(Oe,{className:"w-6 h-6 text-blue-600"})}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 group-hover:text-blue-600 transition-colors flex items-center gap-2",children:["Ansicht",i.jsx(At,{className:"w-4 h-4 opacity-0 group-hover:opacity-100 transition-opacity"})]}),i.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Passen Sie die Darstellung der Anwendung an."})]})]})})})]}),t("developer:access")&&i.jsxs(Z,{title:"Entwickleroptionen",className:"mb-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(la,{className:"w-5 h-5 text-gray-500"}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium",children:"Entwicklermodus"}),i.jsx("p",{className:"text-sm text-gray-500",children:"Aktiviert erweiterte Funktionen wie direkten Datenbankzugriff"})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:e,onChange:r=>n(r.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),e&&i.jsx("div",{className:"mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg",children:i.jsxs("p",{className:"text-sm text-yellow-800",children:[i.jsx("strong",{children:"Warnung:"})," Der Entwicklermodus ermöglicht direkten Zugriff auf die Datenbank. Unsachgemäße Änderungen können zu Datenverlust oder Inkonsistenzen führen."]})})]}),i.jsx(Z,{title:"Über",children:i.jsxs("dl",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"Version"}),i.jsx("dd",{children:"1.0.0"})]}),i.jsxs("div",{children:[i.jsx("dt",{className:"text-sm text-gray-500",children:"System"}),i.jsx("dd",{children:"OpenCRM"})]})]})})]})}function fO({onSelectTable:t}){const e=N.useRef(null),[n,s]=N.useState(1),[r,a]=N.useState({x:0,y:0}),[l,o]=N.useState(!1),[c,d]=N.useState({x:0,y:0}),[u,h]=N.useState({}),[m,f]=N.useState(null),{data:p,isLoading:g}=fe({queryKey:["developer-schema"],queryFn:Vo.getSchema}),x=(p==null?void 0:p.data)||[];N.useEffect(()=>{if(x.length>0&&Object.keys(u).length===0){const w=Math.ceil(Math.sqrt(x.length)),S={x:280,y:200},M={};x.forEach((F,R)=>{const V=R%w,D=Math.floor(R/w);M[F.name]={x:50+V*S.x,y:50+D*S.y}}),h(M)}},[x,u]);const y=N.useCallback(w=>{(w.target===w.currentTarget||w.target.tagName==="svg")&&(o(!0),d({x:w.clientX-r.x,y:w.clientY-r.y}))},[r]),v=N.useCallback(w=>{var S;if(l&&!m)a({x:w.clientX-c.x,y:w.clientY-c.y});else if(m){const M=(S=e.current)==null?void 0:S.getBoundingClientRect();M&&h(F=>({...F,[m]:{x:(w.clientX-M.left-r.x)/n-100,y:(w.clientY-M.top-r.y)/n-20}}))}},[l,m,c,r,n]),b=N.useCallback(()=>{o(!1),f(null)},[]),j=w=>{s(S=>Math.min(2,Math.max(.3,S+w)))},k=()=>{s(1),a({x:0,y:0})},E=N.useCallback(()=>{const w=[];return x.forEach(S=>{const M=u[S.name];M&&S.foreignKeys.forEach(F=>{const R=u[F.targetTable];if(!R)return;const V=x.find(z=>z.name===F.targetTable),D=V==null?void 0:V.relations.find(z=>z.targetTable===S.name);w.push({from:{table:S.name,x:M.x+100,y:M.y+60},to:{table:F.targetTable,x:R.x+100,y:R.y+60},type:(D==null?void 0:D.type)||"one",label:F.field})})}),w},[x,u]);if(g)return i.jsx("div",{className:"flex items-center justify-center h-full",children:"Laden..."});const T=E();return i.jsxs("div",{className:"relative h-full w-full bg-gray-50 overflow-hidden",ref:e,children:[i.jsxs("div",{className:"absolute top-4 right-4 z-10 flex gap-2 bg-white rounded-lg shadow-md p-2",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>j(.1),title:"Vergrößern",children:i.jsx(q5,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>j(-.1),title:"Verkleinern",children:i.jsx(H5,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:k,title:"Zurücksetzen",children:i.jsx(R5,{className:"w-4 h-4"})}),i.jsxs("div",{className:"text-xs text-gray-500 flex items-center px-2",children:[Math.round(n*100),"%"]})]}),i.jsxs("div",{className:"absolute top-4 left-4 z-10 bg-white rounded-lg shadow-md p-2 text-xs text-gray-500",children:[i.jsx(O5,{className:"w-3 h-3 inline mr-1"}),"Tabellen ziehen zum Verschieben"]}),i.jsx("svg",{className:"w-full h-full cursor-grab",style:{cursor:l?"grabbing":"grab"},onMouseDown:y,onMouseMove:v,onMouseUp:b,onMouseLeave:b,children:i.jsxs("g",{transform:`translate(${r.x}, ${r.y}) scale(${n})`,children:[i.jsxs("defs",{children:[i.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:i.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"#6b7280"})}),i.jsx("marker",{id:"many-marker",markerWidth:"12",markerHeight:"12",refX:"6",refY:"6",orient:"auto",children:i.jsx("circle",{cx:"6",cy:"6",r:"3",fill:"#6b7280"})})]}),T.map((w,S)=>{const M=w.to.x-w.from.x,F=w.to.y-w.from.y,R=w.from.x+M/2,V=w.from.y+F/2,D=w.from.x+M*.25,z=w.from.y,C=w.from.x+M*.75,_=w.to.y;return i.jsxs("g",{children:[i.jsx("path",{d:`M ${w.from.x} ${w.from.y} C ${D} ${z}, ${C} ${_}, ${w.to.x} ${w.to.y}`,fill:"none",stroke:"#9ca3af",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),i.jsx("text",{x:R,y:V-8,fontSize:"10",fill:"#6b7280",textAnchor:"middle",className:"select-none",children:w.type==="many"?"1:n":"1:1"})]},S)}),x.map(w=>{const S=u[w.name];if(!S)return null;const M=200,F=32,R=20,V=[...new Set([w.primaryKey,...w.foreignKeys.map(z=>z.field)])],D=F+Math.min(V.length,5)*R+8;return i.jsxs("g",{transform:`translate(${S.x}, ${S.y})`,style:{cursor:"move"},onMouseDown:z=>{z.stopPropagation(),f(w.name)},children:[i.jsx("rect",{x:"3",y:"3",width:M,height:D,rx:"6",fill:"rgba(0,0,0,0.1)"}),i.jsx("rect",{x:"0",y:"0",width:M,height:D,rx:"6",fill:"white",stroke:"#e5e7eb",strokeWidth:"1"}),i.jsx("rect",{x:"0",y:"0",width:M,height:F,rx:"6",fill:"#3b82f6",className:"cursor-pointer",onClick:()=>t==null?void 0:t(w.name)}),i.jsx("rect",{x:"0",y:F-6,width:M,height:"6",fill:"#3b82f6"}),i.jsx("text",{x:M/2,y:"21",fontSize:"13",fontWeight:"bold",fill:"white",textAnchor:"middle",className:"select-none pointer-events-none",children:w.name}),V.slice(0,5).map((z,C)=>{const _=z===w.primaryKey||w.primaryKey.includes(z),K=w.foreignKeys.some(B=>B.field===z);return i.jsx("g",{transform:`translate(8, ${F+4+C*R})`,children:i.jsxs("text",{x:"0",y:"14",fontSize:"11",fill:_?"#dc2626":K?"#2563eb":"#374151",fontFamily:"monospace",className:"select-none",children:[_&&"🔑 ",K&&!_&&"🔗 ",z]})},z)}),V.length>5&&i.jsxs("text",{x:M/2,y:D-4,fontSize:"10",fill:"#9ca3af",textAnchor:"middle",className:"select-none",children:["+",V.length-5," mehr..."]})]},w.name)})]})}),i.jsxs("div",{className:"absolute bottom-4 left-4 bg-white rounded-lg shadow-md p-3 text-xs",children:[i.jsx("div",{className:"font-medium mb-2",children:"Legende"}),i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-red-600",children:"🔑"}),i.jsx("span",{children:"Primary Key"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-blue-600",children:"🔗"}),i.jsx("span",{children:"Foreign Key"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"w-6 h-0.5 bg-gray-400"}),i.jsx("span",{children:"Beziehung"})]})]})]})]})}function mO(){var T;const[t,e]=N.useState(null),[n,s]=N.useState(1),[r,a]=N.useState(null),[l,o]=N.useState(!1),c=ye(),{data:d,isLoading:u,error:h}=fe({queryKey:["developer-schema"],queryFn:Vo.getSchema});console.log("Schema data:",d),console.log("Schema error:",h);const{data:m,isLoading:f}=fe({queryKey:["developer-table",t,n],queryFn:()=>Vo.getTableData(t,n),enabled:!!t}),p=G({mutationFn:({tableName:w,id:S,data:M})=>Vo.updateRow(w,S,M),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",t]}),a(null)},onError:w=>{var S,M;alert(((M=(S=w.response)==null?void 0:S.data)==null?void 0:M.error)||"Fehler beim Speichern")}}),g=G({mutationFn:({tableName:w,id:S})=>Vo.deleteRow(w,S),onSuccess:()=>{c.invalidateQueries({queryKey:["developer-table",t]})},onError:w=>{var S,M;alert(((M=(S=w.response)==null?void 0:S.data)==null?void 0:M.error)||"Fehler beim Löschen")}}),x=(d==null?void 0:d.data)||[],y=x.find(w=>w.name===t),v=(w,S)=>S.primaryKey.includes(",")?S.primaryKey.split(",").map(M=>w[M]).join("-"):String(w[S.primaryKey]),b=w=>w==null?"-":typeof w=="boolean"?w?"Ja":"Nein":typeof w=="object"?w instanceof Date||typeof w=="string"&&w.match(/^\d{4}-\d{2}-\d{2}/)?new Date(w).toLocaleString("de-DE"):JSON.stringify(w):String(w),j=()=>{!r||!t||p.mutate({tableName:t,id:r.id,data:r.data})},k=w=>{t&&confirm("Datensatz wirklich löschen?")&&g.mutate({tableName:t,id:w})};if(u)return i.jsx("div",{className:"text-center py-8",children:"Laden..."});const E=w=>{e(w),s(1),o(!1)};return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Rf,{className:"w-6 h-6"}),i.jsx("h1",{className:"text-2xl font-bold",children:"Datenbankstruktur"})]}),i.jsxs(I,{onClick:()=>o(!0),children:[i.jsx(k1,{className:"w-4 h-4 mr-2"}),"ER-Diagramm"]})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6",children:[i.jsx(Z,{title:"Tabellen",className:"lg:col-span-1",children:i.jsx("div",{className:"space-y-1 max-h-[600px] overflow-y-auto",children:x.map(w=>i.jsxs("button",{onClick:()=>{e(w.name),s(1)},className:`w-full text-left px-3 py-2 rounded-lg flex items-center gap-2 transition-colors ${t===w.name?"bg-blue-100 text-blue-700":"hover:bg-gray-100"}`,children:[i.jsx(B5,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm font-mono",children:w.name})]},w.name))})}),i.jsx("div",{className:"lg:col-span-3 space-y-6",children:t&&y?i.jsxs(i.Fragment,{children:[i.jsxs(Z,{title:`${t} - Beziehungen`,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Fremdschlüssel (referenziert)"}),y.foreignKeys.length>0?i.jsx("div",{className:"space-y-1",children:y.foreignKeys.map(w=>i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("span",{className:"font-mono text-gray-600",children:w.field}),i.jsx(fC,{className:"w-4 h-4 text-gray-400"}),i.jsx(je,{variant:"info",className:"cursor-pointer",onClick:()=>{e(w.targetTable),s(1)},children:w.targetTable})]},w.field))}):i.jsx("p",{className:"text-sm text-gray-400",children:"Keine"})]}),i.jsxs("div",{children:[i.jsx("h4",{className:"text-sm font-medium text-gray-500 mb-2",children:"Relationen (wird referenziert von)"}),y.relations.length>0?i.jsx("div",{className:"space-y-1",children:y.relations.map(w=>i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("span",{className:"font-mono text-gray-600",children:w.field}),i.jsx(je,{variant:w.type==="many"?"warning":"default",children:w.type==="many"?"1:n":"1:1"}),i.jsx(je,{variant:"info",className:"cursor-pointer",onClick:()=>{e(w.targetTable),s(1)},children:w.targetTable})]},w.field))}):i.jsx("p",{className:"text-sm text-gray-400",children:"Keine"})]})]}),i.jsx("div",{className:"mt-4 pt-4 border-t",children:i.jsxs("div",{className:"flex gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-gray-500",children:"Primary Key:"})," ",i.jsx("span",{className:"font-mono",children:y.primaryKey})]}),i.jsxs("div",{children:[i.jsx("span",{className:"text-gray-500",children:"Readonly:"})," ",i.jsx("span",{className:"font-mono text-red-600",children:y.readonlyFields.join(", ")||"-"})]}),i.jsxs("div",{children:[i.jsx("span",{className:"text-gray-500",children:"Required:"})," ",i.jsx("span",{className:"font-mono text-green-600",children:y.requiredFields.join(", ")||"-"})]})]})})]}),i.jsx(Z,{title:`${t} - Daten`,children:f?i.jsx("div",{className:"text-center py-4",children:"Laden..."}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b bg-gray-50",children:[(m==null?void 0:m.data)&&m.data.length>0&&Object.keys(m.data[0]).map(w=>i.jsxs("th",{className:"text-left py-2 px-3 font-medium text-gray-600 whitespace-nowrap",children:[w,y.readonlyFields.includes(w)&&i.jsx("span",{className:"ml-1 text-red-400 text-xs",children:"*"}),y.requiredFields.includes(w)&&i.jsx("span",{className:"ml-1 text-green-400 text-xs",children:"!"})]},w)),i.jsx("th",{className:"text-right py-2 px-3 font-medium text-gray-600",children:"Aktionen"})]})}),i.jsxs("tbody",{children:[(T=m==null?void 0:m.data)==null?void 0:T.map(w=>{const S=v(w,y);return i.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[Object.entries(w).map(([M,F])=>i.jsx("td",{className:"py-2 px-3 font-mono text-xs max-w-[200px] truncate",children:b(F)},M)),i.jsx("td",{className:"py-2 px-3 text-right whitespace-nowrap",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>a({id:S,data:{...w}}),children:i.jsx(rt,{className:"w-4 h-4"})}),i.jsx(I,{variant:"ghost",size:"sm",onClick:()=>k(S),children:i.jsx(Ee,{className:"w-4 h-4 text-red-500"})})]})})]},S)}),(!(m!=null&&m.data)||m.data.length===0)&&i.jsx("tr",{children:i.jsx("td",{colSpan:100,className:"py-4 text-center text-gray-500",children:"Keine Daten vorhanden"})})]})]})}),(m==null?void 0:m.pagination)&&m.pagination.totalPages>1&&i.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[i.jsxs("p",{className:"text-sm text-gray-500",children:["Seite ",m.pagination.page," von ",m.pagination.totalPages," (",m.pagination.total," Einträge)"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>s(w=>Math.max(1,w-1)),disabled:n===1,children:i.jsx(xC,{className:"w-4 h-4"})}),i.jsx(I,{variant:"secondary",size:"sm",onClick:()=>s(w=>w+1),disabled:n>=m.pagination.totalPages,children:i.jsx(At,{className:"w-4 h-4"})})]})]})]})})]}):i.jsx(Z,{children:i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Wähle eine Tabelle aus der Liste aus"})})})]}),i.jsx(Xe,{isOpen:!!r,onClose:()=>a(null),title:`${t} bearbeiten`,children:r&&y&&i.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-y-auto",children:[Object.entries(r.data).map(([w,S])=>{const M=y.readonlyFields.includes(w),F=y.requiredFields.includes(w);return i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[w,M&&i.jsx("span",{className:"ml-1 text-red-400",children:"(readonly)"}),F&&i.jsx("span",{className:"ml-1 text-green-600",children:"*"})]}),M?i.jsx("div",{className:"px-3 py-2 bg-gray-100 rounded-lg font-mono text-sm",children:b(S)}):typeof S=="boolean"?i.jsxs("select",{value:String(r.data[w]),onChange:R=>a({...r,data:{...r.data,[w]:R.target.value==="true"}}),className:"w-full px-3 py-2 border rounded-lg",children:[i.jsx("option",{value:"true",children:"Ja"}),i.jsx("option",{value:"false",children:"Nein"})]}):i.jsx("input",{type:typeof S=="number"?"number":"text",value:r.data[w]??"",onChange:R=>a({...r,data:{...r.data,[w]:typeof S=="number"?R.target.value?Number(R.target.value):null:R.target.value||null}}),className:"w-full px-3 py-2 border rounded-lg font-mono text-sm",disabled:M})]},w)}),i.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[i.jsxs(I,{variant:"secondary",onClick:()=>a(null),children:[i.jsx(nn,{className:"w-4 h-4 mr-2"}),"Abbrechen"]}),i.jsxs(I,{onClick:j,disabled:p.isPending,children:[i.jsx(zy,{className:"w-4 h-4 mr-2"}),p.isPending?"Speichern...":"Speichern"]})]})]})}),l&&i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>o(!1)}),i.jsxs("div",{className:"relative bg-white rounded-xl shadow-2xl w-[90vw] h-[85vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(k1,{className:"w-5 h-5 text-blue-600"}),i.jsx("h2",{className:"text-lg font-semibold",children:"ER-Diagramm - Datenbankbeziehungen"})]}),i.jsx("button",{onClick:()=>o(!1),className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:i.jsx(nn,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 overflow-hidden",children:i.jsx(fO,{onSelectTable:E})})]})]})]})}function pO(){const{hash:t}=md(),e=ye(),[n,s]=N.useState(!1),[r,a]=N.useState({}),{data:l,isLoading:o,error:c}=fe({queryKey:["public-consent",t],queryFn:()=>Im.getConsentPage(t),enabled:!!t}),d=G({mutationFn:()=>Im.grantAllConsents(t),onSuccess:()=>{e.invalidateQueries({queryKey:["public-consent",t]})}});if(o)return i.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:i.jsxs("div",{className:"flex items-center gap-3 text-gray-500",children:[i.jsx(E1,{className:"w-5 h-5 animate-spin"}),"Laden..."]})});if(c||!(l!=null&&l.data))return i.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center",children:i.jsxs("div",{className:"bg-white p-8 rounded-lg shadow-sm border max-w-md text-center",children:[i.jsx(lr,{className:"w-12 h-12 text-red-400 mx-auto mb-4"}),i.jsx("h1",{className:"text-xl font-bold text-gray-900 mb-2",children:"Ungültiger Link"}),i.jsx("p",{className:"text-gray-500",children:"Dieser Datenschutz-Link ist ungültig oder abgelaufen. Bitte kontaktieren Sie Ihren Berater."})]})});const{customer:u,consents:h,privacyPolicyHtml:m}=l.data,f=h.every(b=>b.status==="GRANTED"),p=h.map(b=>b.consentType),g=p.every(b=>r[b]),x=b=>{a(j=>({...j,[b]:!j[b]}))},y=()=>{const b=!n;s(b);const j={};p.forEach(k=>{j[k]=b}),a(j)},v=()=>{g&&d.mutate()};return i.jsxs("div",{className:"min-h-screen bg-gray-50",children:[i.jsx("div",{className:"bg-white border-b",children:i.jsx("div",{className:"max-w-3xl mx-auto px-4 py-6",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(lr,{className:"w-8 h-8 text-blue-600"}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-xl font-bold text-gray-900",children:"Datenschutzerklärung"}),i.jsxs("p",{className:"text-sm text-gray-500",children:[u.firstName," ",u.lastName," (Nr. ",u.customerNumber,")"]})]})]})})}),i.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-8",children:[f?i.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-6 mb-6",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx(Om,{className:"w-8 h-8 text-green-600 flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-green-800 mb-1",children:"Einwilligungen bereits erteilt"}),i.jsx("p",{className:"text-green-700 text-sm mb-3",children:"Sie haben allen Einwilligungen zugestimmt. Vielen Dank!"}),i.jsx("div",{className:"space-y-1",children:h.map(b=>i.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-700",children:[i.jsx(Om,{className:"w-4 h-4"}),i.jsx("span",{children:b.label}),b.grantedAt&&i.jsxs("span",{className:"text-green-500",children:["(am ",new Date(b.grantedAt).toLocaleDateString("de-DE"),")"]})]},b.consentType))})]})]})}):d.isSuccess?i.jsx("div",{className:"bg-green-50 border border-green-200 rounded-lg p-6 mb-6",children:i.jsxs("div",{className:"flex items-start gap-4",children:[i.jsx(Om,{className:"w-8 h-8 text-green-600 flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-green-800 mb-1",children:"Vielen Dank!"}),i.jsx("p",{className:"text-green-700 text-sm",children:"Ihre Einwilligungen wurden erfolgreich gespeichert."})]})]})}):null,i.jsxs("div",{className:"bg-white border rounded-lg shadow-sm mb-6",children:[i.jsxs("div",{className:"p-6 border-b flex items-center justify-between",children:[i.jsx("h2",{className:"font-semibold text-gray-900",children:"Datenschutzerklärung"}),i.jsxs("a",{href:Im.getConsentPdfUrl(t),target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-blue-600 hover:text-blue-800",children:[i.jsx(yC,{className:"w-4 h-4"}),"Als PDF herunterladen"]})]}),i.jsx("div",{className:"p-6 prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:m}})]}),!f&&!d.isSuccess&&i.jsxs("div",{className:"bg-white border rounded-lg shadow-sm",children:[i.jsxs("div",{className:"p-6 border-b",children:[i.jsx("h2",{className:"font-semibold text-gray-900 mb-1",children:"Einwilligungen"}),i.jsx("p",{className:"text-sm text-gray-500",children:"Bitte stimmen Sie allen Punkten zu, damit wir Sie beraten können."})]}),i.jsxs("div",{className:"p-6 space-y-4",children:[i.jsxs("label",{className:"flex items-start gap-3 p-3 rounded-lg bg-blue-50 border border-blue-200 cursor-pointer hover:bg-blue-100 transition-colors",children:[i.jsx("input",{type:"checkbox",checked:n&&g,onChange:y,className:"mt-0.5 rounded border-blue-300 text-blue-600 focus:ring-blue-500"}),i.jsx("div",{children:i.jsx("span",{className:"font-medium text-blue-900",children:"Allen zustimmen"})})]}),i.jsx("div",{className:"border-t pt-4 space-y-3",children:h.map(b=>i.jsxs("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${r[b.consentType]?"bg-green-50 border-green-200":"bg-white border-gray-200 hover:bg-gray-50"}`,children:[i.jsx("input",{type:"checkbox",checked:r[b.consentType]||!1,onChange:()=>x(b.consentType),className:"mt-0.5 rounded border-gray-300 text-green-600 focus:ring-green-500"}),i.jsxs("div",{children:[i.jsxs("span",{className:"font-medium text-gray-900",children:[b.label," *"]}),i.jsx("p",{className:"text-sm text-gray-500 mt-0.5",children:b.description})]})]},b.consentType))}),i.jsx("p",{className:"text-xs text-gray-400",children:"* Pflichtfeld"}),d.isError&&i.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700",children:"Fehler beim Speichern. Bitte versuchen Sie es erneut."}),i.jsx("button",{onClick:v,disabled:!g||d.isPending,className:`w-full py-3 px-4 rounded-lg font-medium text-white transition-colors ${g&&!d.isPending?"bg-blue-600 hover:bg-blue-700":"bg-gray-300 cursor-not-allowed"}`,children:d.isPending?i.jsxs("span",{className:"flex items-center justify-center gap-2",children:[i.jsx(E1,{className:"w-4 h-4 animate-spin"}),"Wird gespeichert..."]}):"Zustimmen"})]})]})]})]})}var KC={exports:{}},UC={};/** + * @license React + * use-sync-external-store-shim.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var no=N;function gO(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var xO=typeof Object.is=="function"?Object.is:gO,yO=no.useState,vO=no.useEffect,bO=no.useLayoutEffect,jO=no.useDebugValue;function NO(t,e){var n=e(),s=yO({inst:{value:n,getSnapshot:e}}),r=s[0].inst,a=s[1];return bO(function(){r.value=n,r.getSnapshot=e,_m(r)&&a({inst:r})},[t,n,e]),vO(function(){return _m(r)&&a({inst:r}),t(function(){_m(r)&&a({inst:r})})},[t]),jO(n),n}function _m(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!xO(t,n)}catch{return!0}}function wO(t,e){return e()}var kO=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?wO:NO;UC.useSyncExternalStore=no.useSyncExternalStore!==void 0?no.useSyncExternalStore:kO;KC.exports=UC;var Wy=KC.exports;function rn(t){this.content=t}rn.prototype={constructor:rn,find:function(t){for(var e=0;e>1}};rn.from=function(t){if(t instanceof rn)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new rn(e)};function qC(t,e,n){for(let s=0;;s++){if(s==t.childCount||s==e.childCount)return t.childCount==e.childCount?null:n;let r=t.child(s),a=e.child(s);if(r==a){n+=r.nodeSize;continue}if(!r.sameMarkup(a))return n;if(r.isText&&r.text!=a.text){for(let l=0;r.text[l]==a.text[l];l++)n++;return n}if(r.content.size||a.content.size){let l=qC(r.content,a.content,n+1);if(l!=null)return l}n+=r.nodeSize}}function HC(t,e,n,s){for(let r=t.childCount,a=e.childCount;;){if(r==0||a==0)return r==a?null:{a:n,b:s};let l=t.child(--r),o=e.child(--a),c=l.nodeSize;if(l==o){n-=c,s-=c;continue}if(!l.sameMarkup(o))return{a:n,b:s};if(l.isText&&l.text!=o.text){let d=0,u=Math.min(l.text.length,o.text.length);for(;de&&s(c,r+o,a||null,l)!==!1&&c.content.size){let u=o+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,n-u),s,r+u)}o=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,s,r){let a="",l=!0;return this.nodesBetween(e,n,(o,c)=>{let d=o.isText?o.text.slice(Math.max(e,c)-c,n-c):o.isLeaf?r?typeof r=="function"?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&d||o.isTextblock)&&s&&(l?l=!1:a+=s),a+=d},0),a}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,s=e.firstChild,r=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(s)&&(r[r.length-1]=n.withText(n.text+s.text),a=1);ae)for(let a=0,l=0;le&&((ln)&&(o.isText?o=o.cut(Math.max(0,e-l),Math.min(o.text.length,n-l)):o=o.cut(Math.max(0,e-l-1),Math.min(o.content.size,n-l-1))),s.push(o),r+=o.nodeSize),l=c}return new X(s,r)}cutByIndex(e,n){return e==n?X.empty:e==0&&n==this.content.length?this:new X(this.content.slice(e,n))}replaceChild(e,n){let s=this.content[e];if(s==n)return this;let r=this.content.slice(),a=this.size+n.nodeSize-s.nodeSize;return r[e]=n,new X(r,a)}addToStart(e){return new X([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new X(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,s=0;;n++){let r=this.child(n),a=s+r.nodeSize;if(a>=e)return a==e?Zd(n+1,a):Zd(n,s);s=a}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return X.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new X(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return X.empty;let n,s=0;for(let r=0;rthis.type.rank&&(n||(n=e.slice(0,r)),n.push(this),s=!0),n&&n.push(a)}}return n||(n=e.slice()),s||n.push(this),n}removeFromSet(e){for(let n=0;ns.type.rank-r.type.rank),n}};tt.none=[];class gh extends Error{}class me{constructor(e,n,s){this.content=e,this.openStart=n,this.openEnd=s}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let s=QC(this.content,e+this.openStart,n);return s&&new me(s,this.openStart,this.openEnd)}removeBetween(e,n){return new me(WC(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return me.empty;let s=n.openStart||0,r=n.openEnd||0;if(typeof s!="number"||typeof r!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new me(X.fromJSON(e,n.content),s,r)}static maxOpen(e,n=!0){let s=0,r=0;for(let a=e.firstChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.firstChild)s++;for(let a=e.lastChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.lastChild)r++;return new me(e,s,r)}}me.empty=new me(X.empty,0,0);function WC(t,e,n){let{index:s,offset:r}=t.findIndex(e),a=t.maybeChild(s),{index:l,offset:o}=t.findIndex(n);if(r==e||a.isText){if(o!=n&&!t.child(l).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(s!=l)throw new RangeError("Removing non-flat range");return t.replaceChild(s,a.copy(WC(a.content,e-r-1,n-r-1)))}function QC(t,e,n,s){let{index:r,offset:a}=t.findIndex(e),l=t.maybeChild(r);if(a==e||l.isText)return s&&!s.canReplace(r,r,n)?null:t.cut(0,e).append(n).append(t.cut(e));let o=QC(l.content,e-a-1,n,l);return o&&t.replaceChild(r,l.copy(o))}function SO(t,e,n){if(n.openStart>t.depth)throw new gh("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new gh("Inconsistent open depths");return GC(t,e,n,0)}function GC(t,e,n,s){let r=t.index(s),a=t.node(s);if(r==e.index(s)&&s=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function ac(t,e,n,s){let r=(e||t).node(n),a=0,l=e?e.index(n):r.childCount;t&&(a=t.index(n),t.depth>n?a++:t.textOffset&&(Ea(t.nodeAfter,s),a++));for(let o=a;or&&Qg(t,e,r+1),l=s.depth>r&&Qg(n,s,r+1),o=[];return ac(null,t,r,o),a&&l&&e.index(r)==n.index(r)?(JC(a,l),Ea(Aa(a,ZC(t,e,n,s,r+1)),o)):(a&&Ea(Aa(a,xh(t,e,r+1)),o),ac(e,n,r,o),l&&Ea(Aa(l,xh(n,s,r+1)),o)),ac(s,null,r,o),new X(o)}function xh(t,e,n){let s=[];if(ac(null,t,n,s),t.depth>n){let r=Qg(t,e,n+1);Ea(Aa(r,xh(t,e,n+1)),s)}return ac(e,null,n,s),new X(s)}function CO(t,e){let n=e.depth-t.openStart,r=e.node(n).copy(t.content);for(let a=n-1;a>=0;a--)r=e.node(a).copy(X.from(r));return{start:r.resolveNoCache(t.openStart+n),end:r.resolveNoCache(r.content.size-t.openEnd-n)}}class Kc{constructor(e,n,s){this.pos=e,this.path=n,this.parentOffset=s,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let s=this.pos-this.path[this.path.length-1],r=e.child(n);return s?e.child(n).cut(s):r}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let s=this.path[n*3],r=n==0?0:this.path[n*3-1]+1;for(let a=0;a0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;s--)if(e.pos<=this.end(s)&&(!n||n(this.node(s))))return new yh(this,e,s);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let s=[],r=0,a=n;for(let l=e;;){let{index:o,offset:c}=l.content.findIndex(a),d=a-c;if(s.push(l,o,r+c),!d||(l=l.child(o),l.isText))break;a=d-1,r+=c+1}return new Kc(n,s,a)}static resolveCached(e,n){let s=nj.get(e);if(s)for(let a=0;ae&&this.nodesBetween(e,n,a=>(s.isInSet(a.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),YC(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,s=X.empty,r=0,a=s.childCount){let l=this.contentMatchAt(e).matchFragment(s,r,a),o=l&&l.matchFragment(this.content,n);if(!o||!o.validEnd)return!1;for(let c=r;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let s;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");s=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,s)}let r=X.fromJSON(e,n.content),a=e.nodeType(n.type).create(n.attrs,r,s);return a.type.checkAttrs(a.attrs),a}}_s.prototype.text=void 0;class vh extends _s{constructor(e,n,s,r){if(super(e,n,null,r),!s)throw new RangeError("Empty text nodes are not allowed");this.text=s}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):YC(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new vh(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new vh(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function YC(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class _a{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let s=new MO(e,n);if(s.next==null)return _a.empty;let r=XC(s);s.next&&s.err("Unexpected trailing text");let a=FO(LO(r));return zO(a,s),a}matchType(e){for(let n=0;nd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(s){e.push(s);for(let r=0;r{let a=r+(s.validEnd?"*":" ")+" ";for(let l=0;l"+e.indexOf(s.next[l].next);return a}).join(` +`)}}_a.empty=new _a(!0);class MO{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function XC(t){let e=[];do e.push(TO(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function TO(t){let e=[];do e.push(PO(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function PO(t){let e=OO(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=IO(t,e);else break;return e}function sj(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function IO(t,e){let n=sj(t),s=n;return t.eat(",")&&(t.next!="}"?s=sj(t):s=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:s,expr:e}}function RO(t,e){let n=t.nodeTypes,s=n[e];if(s)return[s];let r=[];for(let a in n){let l=n[a];l.isInGroup(e)&&r.push(l)}return r.length==0&&t.err("No node type or group '"+e+"' found"),r}function OO(t){if(t.eat("(")){let e=XC(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=RO(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function LO(t){let e=[[]];return r(a(t,0),n()),e;function n(){return e.push([])-1}function s(l,o,c){let d={term:c,to:o};return e[l].push(d),d}function r(l,o){l.forEach(c=>c.to=o)}function a(l,o){if(l.type=="choice")return l.exprs.reduce((c,d)=>c.concat(a(d,o)),[]);if(l.type=="seq")for(let c=0;;c++){let d=a(l.exprs[c],o);if(c==l.exprs.length-1)return d;r(d,o=n())}else if(l.type=="star"){let c=n();return s(o,c),r(a(l.expr,c),c),[s(c)]}else if(l.type=="plus"){let c=n();return r(a(l.expr,o),c),r(a(l.expr,c),c),[s(c)]}else{if(l.type=="opt")return[s(o)].concat(a(l.expr,o));if(l.type=="range"){let c=o;for(let d=0;d{t[l].forEach(({term:o,to:c})=>{if(!o)return;let d;for(let u=0;u{d||r.push([o,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let a=e[s.join(",")]=new _a(s.indexOf(t.length-1)>-1);for(let l=0;l-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:n2(this.attrs,e)}create(e=null,n,s){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new _s(this,this.computeAttrs(e),X.from(n),tt.setFrom(s))}createChecked(e=null,n,s){return n=X.from(n),this.checkContent(n),new _s(this,this.computeAttrs(e),n,tt.setFrom(s))}createAndFill(e=null,n,s){if(e=this.computeAttrs(e),n=X.from(n),n.size){let l=this.contentMatch.fillBefore(n);if(!l)return null;n=l.append(n)}let r=this.contentMatch.matchFragment(n),a=r&&r.fillBefore(X.empty,!0);return a?new _s(this,e,n.append(a),tt.setFrom(s)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let s=0;s-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;ns[a]=new i2(a,n,l));let r=n.spec.topNode||"doc";if(!s[r])throw new RangeError("Schema is missing its top node type ('"+r+"')");if(!s.text)throw new RangeError("Every schema needs a 'text' type");for(let a in s.text.attrs)throw new RangeError("The text node type should not have attributes");return s}};function $O(t,e,n){let s=n.split("|");return r=>{let a=r===null?"null":typeof r;if(s.indexOf(a)<0)throw new RangeError(`Expected value of type ${s} for attribute ${e} on type ${t}, got ${a}`)}}class BO{constructor(e,n,s){this.hasDefault=Object.prototype.hasOwnProperty.call(s,"default"),this.default=s.default,this.validate=typeof s.validate=="string"?$O(e,n,s.validate):s.validate}get isRequired(){return!this.hasDefault}}class Ff{constructor(e,n,s,r){this.name=e,this.rank=n,this.schema=s,this.spec=r,this.attrs=r2(e,r.attrs),this.excluded=null;let a=t2(this.attrs);this.instance=a?new tt(this,a):null}create(e=null){return!e&&this.instance?this.instance:new tt(this,n2(this.attrs,e))}static compile(e,n){let s=Object.create(null),r=0;return e.forEach((a,l)=>s[a]=new Ff(a,r++,n,l)),s}removeFromSet(e){for(var n=0;n-1}}class a2{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let r in e)n[r]=e[r];n.nodes=rn.from(e.nodes),n.marks=rn.from(e.marks||{}),this.nodes=ij.compile(this.spec.nodes,this),this.marks=Ff.compile(this.spec.marks,this);let s=Object.create(null);for(let r in this.nodes){if(r in this.marks)throw new RangeError(r+" can not be both a node and a mark");let a=this.nodes[r],l=a.spec.content||"",o=a.spec.marks;if(a.contentMatch=s[l]||(s[l]=_a.parse(l,this.nodes)),a.inlineContent=a.contentMatch.inlineContent,a.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!a.isInline||!a.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=a}a.markSet=o=="_"?null:o?aj(this,o.split(" ")):o==""||!a.inlineContent?[]:null}for(let r in this.marks){let a=this.marks[r],l=a.spec.excludes;a.excluded=l==null?[a]:l==""?[]:aj(this,l.split(" "))}this.nodeFromJSON=r=>_s.fromJSON(this,r),this.markFromJSON=r=>tt.fromJSON(this,r),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,s,r){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof ij){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,s,r)}text(e,n){let s=this.nodes.text;return new vh(s,s.defaultAttrs,e,tt.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function aj(t,e){let n=[];for(let s=0;s-1)&&n.push(l=c)}if(!l)throw new SyntaxError("Unknown mark type: '"+e[s]+"'")}return n}function _O(t){return t.tag!=null}function VO(t){return t.style!=null}class Li{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let s=this.matchedStyles=[];n.forEach(r=>{if(_O(r))this.tags.push(r);else if(VO(r)){let a=/[^=]*/.exec(r.style)[0];s.indexOf(a)<0&&s.push(a),this.styles.push(r)}}),this.normalizeLists=!this.tags.some(r=>{if(!/^(ul|ol)\b/.test(r.tag)||!r.node)return!1;let a=e.nodes[r.node];return a.contentMatch.matchType(a)})}parse(e,n={}){let s=new oj(this,n,!1);return s.addAll(e,tt.none,n.from,n.to),s.finish()}parseSlice(e,n={}){let s=new oj(this,n,!0);return s.addAll(e,tt.none,n.from,n.to),me.maxOpen(s.finish())}matchTag(e,n,s){for(let r=s?this.tags.indexOf(s)+1:0;re.length&&(o.charCodeAt(e.length)!=61||o.slice(e.length+1)!=n))){if(l.getAttrs){let c=l.getAttrs(n);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(e){let n=[];function s(r){let a=r.priority==null?50:r.priority,l=0;for(;l{s(l=cj(l)),l.mark||l.ignore||l.clearMark||(l.mark=r)})}for(let r in e.nodes){let a=e.nodes[r].spec.parseDOM;a&&a.forEach(l=>{s(l=cj(l)),l.node||l.ignore||l.mark||(l.node=r)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Li(e,Li.schemaRules(e)))}}const l2={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},KO={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},o2={ol:!0,ul:!0},Uc=1,Gg=2,lc=4;function lj(t,e,n){return e!=null?(e?Uc:0)|(e==="full"?Gg:0):t&&t.whitespace=="pre"?Uc|Gg:n&~lc}class Yd{constructor(e,n,s,r,a,l){this.type=e,this.attrs=n,this.marks=s,this.solid=r,this.options=l,this.content=[],this.activeMarks=tt.none,this.match=a||(l&lc?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(X.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let s=this.type.contentMatch,r;return(r=s.findWrapping(e.type))?(this.match=s,r):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Uc)){let s=this.content[this.content.length-1],r;if(s&&s.isText&&(r=/[ \t\r\n\u000c]+$/.exec(s.text))){let a=s;s.text.length==r[0].length?this.content.pop():this.content[this.content.length-1]=a.withText(a.text.slice(0,a.text.length-r[0].length))}}let n=X.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(X.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!l2.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class oj{constructor(e,n,s){this.parser=e,this.options=n,this.isOpen=s,this.open=0,this.localPreserveWS=!1;let r=n.topNode,a,l=lj(null,n.preserveWhitespace,0)|(s?lc:0);r?a=new Yd(r.type,r.attrs,tt.none,!0,n.topMatch||r.type.contentMatch,l):s?a=new Yd(null,null,tt.none,!0,null,l):a=new Yd(e.schema.topNodeType,null,tt.none,!0,null,l),this.nodes=[a],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let s=e.nodeValue,r=this.top,a=r.options&Gg?"full":this.localPreserveWS||(r.options&Uc)>0,{schema:l}=this.parser;if(a==="full"||r.inlineContext(e)||/[^ \t\r\n\u000c]/.test(s)){if(a)if(a==="full")s=s.replace(/\r\n?/g,` +`);else if(l.linebreakReplacement&&/[\r\n]/.test(s)&&this.top.findWrapping(l.linebreakReplacement.create())){let o=s.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)o=c;else break}}return n}addElementByRule(e,n,s,r){let a,l;if(n.node)if(l=this.parser.schema.nodes[n.node],l.isLeaf)this.insertNode(l.create(n.attrs),s,e.nodeName=="BR")||this.leafFallback(e,s);else{let c=this.enter(l,n.attrs||null,s,n.preserveWhitespace);c&&(a=!0,s=c)}else{let c=this.parser.schema.marks[n.mark];s=s.concat(c.create(n.attrs))}let o=this.top;if(l&&l.isLeaf)this.findInside(e);else if(r)this.addElement(e,s,r);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,s,!1));else{let c=e;typeof n.contentElement=="string"?c=e.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(e):n.contentElement&&(c=n.contentElement),this.findAround(e,c,!0),this.addAll(c,s),this.findAround(e,c,!1)}a&&this.sync(o)&&this.open--}addAll(e,n,s,r){let a=s||0;for(let l=s?e.childNodes[s]:e.firstChild,o=r==null?null:e.childNodes[r];l!=o;l=l.nextSibling,++a)this.findAtPoint(e,a),this.addDOM(l,n);this.findAtPoint(e,a)}findPlace(e,n,s){let r,a;for(let l=this.open,o=0;l>=0;l--){let c=this.nodes[l],d=c.findWrapping(e);if(d&&(!r||r.length>d.length+o)&&(r=d,a=c,!d.length))break;if(c.solid){if(s)break;o+=2}}if(!r)return null;this.sync(a);for(let l=0;l(l.type?l.type.allowsMarkType(d.type):dj(d.type,e))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Yd(e,n,c,r,null,o)),this.open++,s}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Uc)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let s=this.nodes[n].content;for(let r=s.length-1;r>=0;r--)e+=s[r].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let s=0;s-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),s=this.options.context,r=!this.isOpen&&(!s||s.parent.type==this.nodes[0].type),a=-(s?s.depth+1:0)+(r?0:1),l=(o,c)=>{for(;o>=0;o--){let d=n[o];if(d==""){if(o==n.length-1||o==0)continue;for(;c>=a;c--)if(l(o-1,c))return!0;return!1}else{let u=c>0||c==0&&r?this.nodes[c].type:s&&c>=a?s.node(c-a).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let s=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(s&&s.isTextblock&&s.defaultAttrs)return s}for(let n in this.parser.schema.nodes){let s=this.parser.schema.nodes[n];if(s.isTextblock&&s.defaultAttrs)return s}}}function UO(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let s=e.nodeType==1?e.nodeName.toLowerCase():null;s&&o2.hasOwnProperty(s)&&n?(n.appendChild(e),e=n):s=="li"?n=e:s&&(n=null)}}function qO(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function cj(t){let e={};for(let n in t)e[n]=t[n];return e}function dj(t,e){let n=e.schema.nodes;for(let s in n){let r=n[s];if(!r.allowsMarkType(t))continue;let a=[],l=o=>{a.push(o);for(let c=0;c{if(a.length||l.marks.length){let o=0,c=0;for(;o=0;r--){let a=this.serializeMark(e.marks[r],e.isInline,n);a&&((a.contentDOM||a.dom).appendChild(s),s=a.dom)}return s}serializeMark(e,n,s={}){let r=this.marks[e.type.name];return r&&Au(Km(s),r(e,n),null,e.attrs)}static renderSpec(e,n,s=null,r){return Au(e,n,s,r)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Ga(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=uj(e.nodes);return n.text||(n.text=s=>s.text),n}static marksFromSchema(e){return uj(e.marks)}}function uj(t){let e={};for(let n in t){let s=t[n].spec.toDOM;s&&(e[n]=s)}return e}function Km(t){return t.document||window.document}const hj=new WeakMap;function HO(t){let e=hj.get(t);return e===void 0&&hj.set(t,e=WO(t)),e}function WO(t){let e=null;function n(s){if(s&&typeof s=="object")if(Array.isArray(s))if(typeof s[0]=="string")e||(e=[]),e.push(s);else for(let r=0;r-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=r.indexOf(" ");l>0&&(n=r.slice(0,l),r=r.slice(l+1));let o,c=n?t.createElementNS(n,r):t.createElement(r),d=e[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let m=h.indexOf(" ");m>0?c.setAttributeNS(h.slice(0,m),h.slice(m+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:p}=Au(t,m,n,s);if(c.appendChild(f),p){if(o)throw new RangeError("Multiple content holes");o=p}}}return{dom:c,contentDOM:o}}const c2=65535,d2=Math.pow(2,16);function QO(t,e){return t+e*d2}function fj(t){return t&c2}function GO(t){return(t-(t&c2))/d2}const u2=1,h2=2,Du=4,f2=8;class Jg{constructor(e,n,s){this.pos=e,this.delInfo=n,this.recover=s}get deleted(){return(this.delInfo&f2)>0}get deletedBefore(){return(this.delInfo&(u2|Du))>0}get deletedAfter(){return(this.delInfo&(h2|Du))>0}get deletedAcross(){return(this.delInfo&Du)>0}}class ss{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&ss.empty)return ss.empty}recover(e){let n=0,s=fj(e);if(!this.inverted)for(let r=0;re)break;let d=this.ranges[o+a],u=this.ranges[o+l],h=c+d;if(e<=h){let m=d?e==c?-1:e==h?1:n:n,f=c+r+(m<0?0:u);if(s)return f;let p=e==(n<0?c:h)?null:QO(o/3,e-c),g=e==c?h2:e==h?u2:Du;return(n<0?e!=c:e!=h)&&(g|=f2),new Jg(f,g,p)}r+=u-d}return s?e+r:new Jg(e+r,0,null)}touches(e,n){let s=0,r=fj(n),a=this.inverted?2:1,l=this.inverted?1:2;for(let o=0;oe)break;let d=this.ranges[o+a],u=c+d;if(e<=u&&o==r*3)return!0;s+=this.ranges[o+l]-d}return!1}forEach(e){let n=this.inverted?2:1,s=this.inverted?1:2;for(let r=0,a=0;r=0;n--){let r=e.getMirror(n);this.appendMap(e._maps[n].invert(),r!=null&&r>n?s-r-1:void 0)}}invert(){let e=new qc;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let s=this.from;sa&&c!l.isAtom||!o.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),r),n.openStart,n.openEnd);return zt.fromReplace(e,this.from,this.to,a)}invert(){return new zs(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),s=e.mapResult(this.to,-1);return n.deleted&&s.deleted||n.pos>=s.pos?null:new wi(n.pos,s.pos,this.mark)}merge(e){return e instanceof wi&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new wi(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new wi(n.from,n.to,e.markFromJSON(n.mark))}}Nn.jsonID("addMark",wi);class zs extends Nn{constructor(e,n,s){super(),this.from=e,this.to=n,this.mark=s}apply(e){let n=e.slice(this.from,this.to),s=new me(Qy(n.content,r=>r.mark(this.mark.removeFromSet(r.marks)),e),n.openStart,n.openEnd);return zt.fromReplace(e,this.from,this.to,s)}invert(){return new wi(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),s=e.mapResult(this.to,-1);return n.deleted&&s.deleted||n.pos>=s.pos?null:new zs(n.pos,s.pos,this.mark)}merge(e){return e instanceof zs&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new zs(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new zs(n.from,n.to,e.markFromJSON(n.mark))}}Nn.jsonID("removeMark",zs);class ki extends Nn{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return zt.fail("No node at mark step's position");let s=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return zt.fromReplace(e,this.pos,this.pos+1,new me(X.from(s),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let s=this.mark.addToSet(n.marks);if(s.length==n.marks.length){for(let r=0;rs.pos?null:new en(n.pos,s.pos,r,a,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new en(n.from,n.to,n.gapFrom,n.gapTo,me.fromJSON(e,n.slice),n.insert,!!n.structure)}}Nn.jsonID("replaceAround",en);function Zg(t,e,n){let s=t.resolve(e),r=n-e,a=s.depth;for(;r>0&&a>0&&s.indexAfter(a)==s.node(a).childCount;)a--,r--;if(r>0){let l=s.node(a).maybeChild(s.indexAfter(a));for(;r>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,r--}}return!1}function JO(t,e,n,s){let r=[],a=[],l,o;t.doc.nodesBetween(e,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!s.isInSet(h)&&u.type.allowsMarkType(s.type)){let m=Math.max(d,e),f=Math.min(d+c.nodeSize,n),p=s.addToSet(h);for(let g=0;gt.step(c)),a.forEach(c=>t.step(c))}function ZO(t,e,n,s){let r=[],a=0;t.doc.nodesBetween(e,n,(l,o)=>{if(!l.isInline)return;a++;let c=null;if(s instanceof Ff){let d=l.marks,u;for(;u=s.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else s?s.isInSet(l.marks)&&(c=[s]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,n);for(let u=0;ut.step(new zs(l.from,l.to,l.style)))}function Gy(t,e,n,s=n.contentMatch,r=!0){let a=t.doc.nodeAt(e),l=[],o=e+1;for(let c=0;c=0;c--)t.step(l[c])}function YO(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function vo(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let s=t.depth,r=0,a=0;;--s){let l=t.$from.node(s),o=t.$from.index(s)+r,c=t.$to.indexAfter(s)-a;if(sn;p--)g||s.index(p)>0?(g=!0,u=X.from(s.node(p).copy(u)),h++):c--;let m=X.empty,f=0;for(let p=a,g=!1;p>n;p--)g||r.after(p+1)=0;l--){if(s.size){let o=n[l].type.contentMatch.matchFragment(s);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}s=X.from(n[l].type.create(n[l].attrs,s))}let r=e.start,a=e.end;t.step(new en(r,a,r,a,new me(s,0,0),n.length,!0))}function sL(t,e,n,s,r){if(!s.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let a=t.steps.length;t.doc.nodesBetween(e,n,(l,o)=>{let c=typeof r=="function"?r(l):r;if(l.isTextblock&&!l.hasMarkup(s,c)&&rL(t.doc,t.mapping.slice(a).map(o),s)){let d=null;if(s.schema.linebreakReplacement){let f=s.whitespace=="pre",p=!!s.contentMatch.matchType(s.schema.linebreakReplacement);f&&!p?d=!1:!f&&p&&(d=!0)}d===!1&&p2(t,l,o,a),Gy(t,t.mapping.slice(a).map(o,1),s,void 0,d===null);let u=t.mapping.slice(a),h=u.map(o,1),m=u.map(o+l.nodeSize,1);return t.step(new en(h,m,h+1,m-1,new me(X.from(s.create(c,null,l.marks)),0,0),1,!0)),d===!0&&m2(t,l,o,a),!1}})}function m2(t,e,n,s){e.forEach((r,a)=>{if(r.isText){let l,o=/\r?\n|\r/g;for(;l=o.exec(r.text);){let c=t.mapping.slice(s).map(n+1+a+l.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function p2(t,e,n,s){e.forEach((r,a)=>{if(r.type==r.type.schema.linebreakReplacement){let l=t.mapping.slice(s).map(n+1+a);t.replaceWith(l,l+1,e.type.schema.text(` +`))}})}function rL(t,e,n){let s=t.resolve(e),r=s.index();return s.parent.canReplaceWith(r,r+1,n)}function iL(t,e,n,s,r){let a=t.doc.nodeAt(e);if(!a)throw new RangeError("No node at given position");n||(n=a.type);let l=n.create(s,null,r||a.marks);if(a.isLeaf)return t.replaceWith(e,e+a.nodeSize,l);if(!n.validContent(a.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new en(e,e+a.nodeSize,e+1,e+a.nodeSize-1,new me(X.from(l),0,0),1,!0))}function Rr(t,e,n=1,s){let r=t.resolve(e),a=r.depth-n,l=s&&s[s.length-1]||r.parent;if(a<0||r.parent.type.spec.isolating||!r.parent.canReplace(r.index(),r.parent.childCount)||!l.type.validContent(r.parent.content.cutByIndex(r.index(),r.parent.childCount)))return!1;for(let d=r.depth-1,u=n-2;d>a;d--,u--){let h=r.node(d),m=r.index(d);if(h.type.spec.isolating)return!1;let f=h.content.cutByIndex(m,h.childCount),p=s&&s[u+1];p&&(f=f.replaceChild(0,p.type.create(p.attrs)));let g=s&&s[u]||h;if(!h.canReplace(m+1,h.childCount)||!g.type.validContent(f))return!1}let o=r.indexAfter(a),c=s&&s[0];return r.node(a).canReplaceWith(o,o,c?c.type:r.node(a+1).type)}function aL(t,e,n=1,s){let r=t.doc.resolve(e),a=X.empty,l=X.empty;for(let o=r.depth,c=r.depth-n,d=n-1;o>c;o--,d--){a=X.from(r.node(o).copy(a));let u=s&&s[d];l=X.from(u?u.type.create(u.attrs,l):r.node(o).copy(l))}t.step(new Yt(e,e,new me(a.append(l),n,n),!0))}function Qi(t,e){let n=t.resolve(e),s=n.index();return g2(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(s,s+1)}function lL(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:s}=t.type.schema;for(let r=0;r0?(a=s.node(r+1),o++,l=s.node(r).maybeChild(o)):(a=s.node(r).maybeChild(o-1),l=s.node(r+1)),a&&!a.isTextblock&&g2(a,l)&&s.node(r).canReplace(o,o+1))return e;if(r==0)break;e=n<0?s.before(r):s.after(r)}}function oL(t,e,n){let s=null,{linebreakReplacement:r}=t.doc.type.schema,a=t.doc.resolve(e-n),l=a.node().type;if(r&&l.inlineContent){let u=l.whitespace=="pre",h=!!l.contentMatch.matchType(r);u&&!h?s=!1:!u&&h&&(s=!0)}let o=t.steps.length;if(s===!1){let u=t.doc.resolve(e+n);p2(t,u.node(),u.before(),o)}l.inlineContent&&Gy(t,e+n-1,l,a.node().contentMatchAt(a.index()),s==null);let c=t.mapping.slice(o),d=c.map(e-n);if(t.step(new Yt(d,c.map(e+n,-1),me.empty,!0)),s===!0){let u=t.doc.resolve(d);m2(t,u.node(),u.before(),t.steps.length)}return t}function cL(t,e,n){let s=t.resolve(e);if(s.parent.canReplaceWith(s.index(),s.index(),n))return e;if(s.parentOffset==0)for(let r=s.depth-1;r>=0;r--){let a=s.index(r);if(s.node(r).canReplaceWith(a,a,n))return s.before(r+1);if(a>0)return null}if(s.parentOffset==s.parent.content.size)for(let r=s.depth-1;r>=0;r--){let a=s.indexAfter(r);if(s.node(r).canReplaceWith(a,a,n))return s.after(r+1);if(a=0;l--){let o=l==s.depth?0:s.pos<=(s.start(l+1)+s.end(l+1))/2?-1:1,c=s.index(l)+(o>0?1:0),d=s.node(l),u=!1;if(a==1)u=d.canReplace(c,c,r);else{let h=d.contentMatchAt(c).findWrapping(r.firstChild.type);u=h&&d.canReplaceWith(c,c,h[0])}if(u)return o==0?s.pos:o<0?s.before(l+1):s.after(l+1)}return null}function $f(t,e,n=e,s=me.empty){if(e==n&&!s.size)return null;let r=t.resolve(e),a=t.resolve(n);return y2(r,a,s)?new Yt(e,n,s):new dL(r,a,s).fit()}function y2(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}class dL{constructor(e,n,s){this.$from=e,this.$to=n,this.unplaced=s,this.frontier=[],this.placed=X.empty;for(let r=0;r<=e.depth;r++){let a=e.node(r);this.frontier.push({type:a.type,match:a.contentMatchAt(e.indexAfter(r))})}for(let r=e.depth;r>0;r--)this.placed=X.from(e.node(r).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,s=this.$from,r=this.close(e<0?this.$to:s.doc.resolve(e));if(!r)return null;let a=this.placed,l=s.depth,o=r.depth;for(;l&&o&&a.childCount==1;)a=a.firstChild.content,l--,o--;let c=new me(a,l,o);return e>-1?new en(s.pos,e,this.$to.pos,this.$to.end(),c,n):c.size||s.pos!=this.$to.pos?new Yt(s.pos,r.pos,c):null}findFittable(){let e=this.unplaced.openStart;for(let n=this.unplaced.content,s=0,r=this.unplaced.openEnd;s1&&(r=0),a.type.spec.isolating&&r<=s){e=s;break}n=a.content}for(let n=1;n<=2;n++)for(let s=n==1?e:this.unplaced.openStart;s>=0;s--){let r,a=null;s?(a=qm(this.unplaced.content,s-1).firstChild,r=a.content):r=this.unplaced.content;let l=r.firstChild;for(let o=this.depth;o>=0;o--){let{type:c,match:d}=this.frontier[o],u,h=null;if(n==1&&(l?d.matchType(l.type)||(h=d.fillBefore(X.from(l),!1)):a&&c.compatibleContent(a.type)))return{sliceDepth:s,frontierDepth:o,parent:a,inject:h};if(n==2&&l&&(u=d.findWrapping(l.type)))return{sliceDepth:s,frontierDepth:o,parent:a,wrap:u};if(a&&d.matchType(a.type))break}}}openMore(){let{content:e,openStart:n,openEnd:s}=this.unplaced,r=qm(e,n);return!r.childCount||r.firstChild.isLeaf?!1:(this.unplaced=new me(e,n+1,Math.max(s,r.size+n>=e.size-s?n+1:0)),!0)}dropNode(){let{content:e,openStart:n,openEnd:s}=this.unplaced,r=qm(e,n);if(r.childCount<=1&&n>0){let a=e.size-n<=n+r.size;this.unplaced=new me(Ko(e,n-1,1),n-1,a?n-1:s)}else this.unplaced=new me(Ko(e,n,1),n,s)}placeNodes({sliceDepth:e,frontierDepth:n,parent:s,inject:r,wrap:a}){for(;this.depth>n;)this.closeFrontierNode();if(a)for(let g=0;g1||c==0||g.content.size)&&(h=x,u.push(v2(g.mark(m.allowedMarks(g.marks)),d==1?c:0,d==o.childCount?f:-1)))}let p=d==o.childCount;p||(f=-1),this.placed=Uo(this.placed,n,X.from(u)),this.frontier[n].match=h,p&&f<0&&s&&s.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let g=0,x=o;g1&&r==this.$to.end(--s);)++r;return r}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:s,type:r}=this.frontier[n],a=n=0;o--){let{match:c,type:d}=this.frontier[o],u=Hm(e,o,d,c,!0);if(!u||u.childCount)continue e}return{depth:n,fit:l,move:a?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Uo(this.placed,n.depth,n.fit)),e=n.move;for(let s=n.depth+1;s<=e.depth;s++){let r=e.node(s),a=r.type.contentMatch.fillBefore(r.content,!0,e.index(s));this.openFrontierNode(r.type,r.attrs,a)}return e}openFrontierNode(e,n=null,s){let r=this.frontier[this.depth];r.match=r.match.matchType(e),this.placed=Uo(this.placed,this.depth,X.from(e.create(n,s))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(X.empty,!0);n.childCount&&(this.placed=Uo(this.placed,this.frontier.length,n))}}function Ko(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Ko(t.firstChild.content,e-1,n)))}function Uo(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Uo(t.lastChild.content,e-1,n)))}function qm(t,e){for(let n=0;n1&&(s=s.replaceChild(0,v2(s.firstChild,e-1,s.childCount==1?n-1:0))),e>0&&(s=t.type.contentMatch.fillBefore(s).append(s),n<=0&&(s=s.append(t.type.contentMatch.matchFragment(s).fillBefore(X.empty,!0)))),t.copy(s)}function Hm(t,e,n,s,r){let a=t.node(e),l=r?t.indexAfter(e):t.index(e);if(l==a.childCount&&!n.compatibleContent(a.type))return null;let o=s.fillBefore(a.content,!0,l);return o&&!uL(n,a.content,l)?o:null}function uL(t,e,n){for(let s=n;s0;m--,f--){let p=r.node(m).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;l.indexOf(m)>-1?o=m:r.before(m)==f&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=s.openStart;for(let m=s.content,f=0;;f++){let p=m.firstChild;if(d.push(p),f==s.openStart)break;m=p.content}for(let m=u-1;m>=0;m--){let f=d[m],p=hL(f.type);if(p&&!f.sameMarkup(r.node(Math.abs(o)-1)))u=m;else if(p||!f.type.isTextblock)break}for(let m=s.openStart;m>=0;m--){let f=(m+u+1)%(s.openStart+1),p=d[f];if(p)for(let g=0;g=0&&(t.replace(e,n,s),!(t.steps.length>h));m--){let f=l[m];f<0||(e=r.before(f),n=a.after(f))}}function b2(t,e,n,s,r){if(es){let a=r.contentMatchAt(0),l=a.fillBefore(t).append(t);t=l.append(a.matchFragment(l).fillBefore(X.empty,!0))}return t}function mL(t,e,n,s){if(!s.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let r=cL(t.doc,e,s.type);r!=null&&(e=n=r)}t.replaceRange(e,n,new me(X.from(s),0,0))}function pL(t,e,n){let s=t.doc.resolve(e),r=t.doc.resolve(n),a=j2(s,r);for(let l=0;l0&&(c||s.node(o-1).canReplace(s.index(o-1),r.indexAfter(o-1))))return t.delete(s.before(o),r.after(o))}for(let l=1;l<=s.depth&&l<=r.depth;l++)if(e-s.start(l)==s.depth-l&&n>s.end(l)&&r.end(l)-n!=r.depth-l&&s.start(l-1)==r.start(l-1)&&s.node(l-1).canReplace(s.index(l-1),r.index(l-1)))return t.delete(s.before(l),n);t.delete(e,n)}function j2(t,e){let n=[],s=Math.min(t.depth,e.depth);for(let r=s;r>=0;r--){let a=t.start(r);if(ae.pos+(e.depth-r)||t.node(r).type.spec.isolating||e.node(r).type.spec.isolating)break;(a==e.start(r)||r==t.depth&&r==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&r&&e.start(r-1)==a-1)&&n.push(r)}return n}class Dl extends Nn{constructor(e,n,s){super(),this.pos=e,this.attr=n,this.value=s}apply(e){let n=e.nodeAt(this.pos);if(!n)return zt.fail("No node at attribute step's position");let s=Object.create(null);for(let a in n.attrs)s[a]=n.attrs[a];s[this.attr]=this.value;let r=n.type.create(s,null,n.marks);return zt.fromReplace(e,this.pos,this.pos+1,new me(X.from(r),0,n.isLeaf?0:1))}getMap(){return ss.empty}invert(e){return new Dl(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new Dl(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Dl(n.pos,n.attr,n.value)}}Nn.jsonID("attr",Dl);class Hc extends Nn{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let r in e.attrs)n[r]=e.attrs[r];n[this.attr]=this.value;let s=e.type.create(n,e.content,e.marks);return zt.ok(s)}getMap(){return ss.empty}invert(e){return new Hc(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Hc(n.attr,n.value)}}Nn.jsonID("docAttr",Hc);let so=class extends Error{};so=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};so.prototype=Object.create(Error.prototype);so.prototype.constructor=so;so.prototype.name="TransformError";class N2{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new qc}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new so(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let s=0;s{e=Math.min(e,o),n=Math.max(n,c)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,s=me.empty){let r=$f(this.doc,e,n,s);return r&&this.step(r),this}replaceWith(e,n,s){return this.replace(e,n,new me(X.from(s),0,0))}delete(e,n){return this.replace(e,n,me.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,s){return fL(this,e,n,s),this}replaceRangeWith(e,n,s){return mL(this,e,n,s),this}deleteRange(e,n){return pL(this,e,n),this}lift(e,n){return XO(this,e,n),this}join(e,n=1){return oL(this,e,n),this}wrap(e,n){return nL(this,e,n),this}setBlockType(e,n=e,s,r=null){return sL(this,e,n,s,r),this}setNodeMarkup(e,n,s=null,r){return iL(this,e,n,s,r),this}setNodeAttribute(e,n,s){return this.step(new Dl(e,n,s)),this}setDocAttribute(e,n){return this.step(new Hc(e,n)),this}addNodeMark(e,n){return this.step(new ki(e,n)),this}removeNodeMark(e,n){let s=this.doc.nodeAt(e);if(!s)throw new RangeError("No node at position "+e);if(n instanceof tt)n.isInSet(s.marks)&&this.step(new Va(e,n));else{let r=s.marks,a,l=[];for(;a=n.isInSet(r);)l.push(new Va(e,a)),r=a.removeFromSet(r);for(let o=l.length-1;o>=0;o--)this.step(l[o])}return this}split(e,n=1,s){return aL(this,e,n,s),this}addMark(e,n,s){return JO(this,e,n,s),this}removeMark(e,n,s){return ZO(this,e,n,s),this}clearIncompatible(e,n,s){return Gy(this,e,n,s),this}}const Wm=Object.create(null);class Ie{constructor(e,n,s){this.$anchor=e,this.$head=n,this.ranges=s||[new gL(e.min(n),e.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let n=0;n=0;a--){let l=n<0?il(e.node(0),e.node(a),e.before(a+1),e.index(a),n,s):il(e.node(0),e.node(a),e.after(a+1),e.index(a)+1,n,s);if(l)return l}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new as(e.node(0))}static atStart(e){return il(e,e,0,0,1)||new as(e)}static atEnd(e){return il(e,e,e.content.size,e.childCount,-1)||new as(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let s=Wm[n.type];if(!s)throw new RangeError(`No selection type ${n.type} defined`);return s.fromJSON(e,n)}static jsonID(e,n){if(e in Wm)throw new RangeError("Duplicate use of selection JSON ID "+e);return Wm[e]=n,n.prototype.jsonID=e,n}getBookmark(){return De.between(this.$anchor,this.$head).getBookmark()}}Ie.prototype.visible=!0;class gL{constructor(e,n){this.$from=e,this.$to=n}}let pj=!1;function gj(t){!pj&&!t.parent.inlineContent&&(pj=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class De extends Ie{constructor(e,n=e){gj(e),gj(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let s=e.resolve(n.map(this.head));if(!s.parent.inlineContent)return Ie.near(s);let r=e.resolve(n.map(this.anchor));return new De(r.parent.inlineContent?r:s,s)}replace(e,n=me.empty){if(super.replace(e,n),n==me.empty){let s=this.$from.marksAcross(this.$to);s&&e.ensureMarks(s)}}eq(e){return e instanceof De&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Bf(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new De(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,s=n){let r=e.resolve(n);return new this(r,s==n?r:e.resolve(s))}static between(e,n,s){let r=e.pos-n.pos;if((!s||r)&&(s=r>=0?1:-1),!n.parent.inlineContent){let a=Ie.findFrom(n,s,!0)||Ie.findFrom(n,-s,!0);if(a)n=a.$head;else return Ie.near(n,s)}return e.parent.inlineContent||(r==0?e=n:(e=(Ie.findFrom(e,-s,!0)||Ie.findFrom(e,s,!0)).$anchor,e.pos0?0:1);r>0?l=0;l+=r){let o=e.child(l);if(o.isAtom){if(!a&&ke.isSelectable(o))return ke.create(t,n-(r<0?o.nodeSize:0))}else{let c=il(t,o,n+r,r<0?o.childCount:0,r,a);if(c)return c}n+=o.nodeSize*r}return null}function xj(t,e,n){let s=t.steps.length-1;if(s{l==null&&(l=u)}),t.setSelection(Ie.near(t.doc.resolve(l),n))}const yj=1,Xd=2,vj=4;class yL extends N2{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Xd,this}ensureMarks(e){return tt.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Xd)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~Xd,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let s=this.selection;return n&&(e=e.mark(this.storedMarks||(s.empty?s.$from.marks():s.$from.marksAcross(s.$to)||tt.none))),s.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,s){let r=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(r.text(e),!0):this.deleteSelection();{if(s==null&&(s=n),!e)return this.deleteRange(n,s);let a=this.storedMarks;if(!a){let l=this.doc.resolve(n);a=s==n?l.marks():l.marksAcross(this.doc.resolve(s))}return this.replaceRangeWith(n,s,r.text(e,a)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(Ie.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=vj,this}get scrolledIntoView(){return(this.updated&vj)>0}}function bj(t,e){return!e||!t?t:t.bind(e)}class qo{constructor(e,n,s){this.name=e,this.init=bj(n.init,s),this.apply=bj(n.apply,s)}}const vL=[new qo("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new qo("selection",{init(t,e){return t.selection||Ie.atStart(e.doc)},apply(t){return t.selection}}),new qo("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,s){return s.selection.$cursor?t.storedMarks:null}}),new qo("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class Qm{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=vL.slice(),n&&n.forEach(s=>{if(this.pluginsByKey[s.key])throw new RangeError("Adding different instances of a keyed plugin ("+s.key+")");this.plugins.push(s),this.pluginsByKey[s.key]=s,s.spec.state&&this.fields.push(new qo(s.key,s.spec.state,s))})}}class jl{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let s=0;ss.toJSON())),e&&typeof e=="object")for(let s in e){if(s=="doc"||s=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let r=e[s],a=r.spec.state;a&&a.toJSON&&(n[s]=a.toJSON.call(r,this[r.key]))}return n}static fromJSON(e,n,s){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let r=new Qm(e.schema,e.plugins),a=new jl(r);return r.fields.forEach(l=>{if(l.name=="doc")a.doc=_s.fromJSON(e.schema,n.doc);else if(l.name=="selection")a.selection=Ie.fromJSON(a.doc,n.selection);else if(l.name=="storedMarks")n.storedMarks&&(a.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(s)for(let o in s){let c=s[o],d=c.spec.state;if(c.key==l.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(n,o)){a[l.name]=d.fromJSON.call(c,e,n[o],a);return}}a[l.name]=l.init(e,a)}}),a}}function w2(t,e,n){for(let s in t){let r=t[s];r instanceof Function?r=r.bind(e):s=="handleDOMEvents"&&(r=w2(r,e,{})),n[s]=r}return n}class Nt{constructor(e){this.spec=e,this.props={},e.props&&w2(e.props,this,this.props),this.key=e.key?e.key.key:k2("plugin")}getState(e){return e[this.key]}}const Gm=Object.create(null);function k2(t){return t in Gm?t+"$"+ ++Gm[t]:(Gm[t]=0,t+"$")}class Ht{constructor(e="key"){this.key=k2(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const Yy=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function S2(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const C2=(t,e,n)=>{let s=S2(t,n);if(!s)return!1;let r=Xy(s);if(!r){let l=s.blockRange(),o=l&&vo(l);return o==null?!1:(e&&e(t.tr.lift(l,o).scrollIntoView()),!0)}let a=r.nodeBefore;if(O2(t,r,e,-1))return!0;if(s.parent.content.size==0&&(ro(a,"end")||ke.isSelectable(a)))for(let l=s.depth;;l--){let o=$f(t.doc,s.before(l),s.after(l),me.empty);if(o&&o.slice.size1)break}return a.isAtom&&r.depth==s.depth-1?(e&&e(t.tr.delete(r.pos-a.nodeSize,r.pos).scrollIntoView()),!0):!1},bL=(t,e,n)=>{let s=S2(t,n);if(!s)return!1;let r=Xy(s);return r?E2(t,r,e):!1},jL=(t,e,n)=>{let s=D2(t,n);if(!s)return!1;let r=e0(s);return r?E2(t,r,e):!1};function E2(t,e,n){let s=e.nodeBefore,r=s,a=e.pos-1;for(;!r.isTextblock;a--){if(r.type.spec.isolating)return!1;let u=r.lastChild;if(!u)return!1;r=u}let l=e.nodeAfter,o=l,c=e.pos+1;for(;!o.isTextblock;c++){if(o.type.spec.isolating)return!1;let u=o.firstChild;if(!u)return!1;o=u}let d=$f(t.doc,a,c,me.empty);if(!d||d.from!=a||d instanceof Yt&&d.slice.size>=c-a)return!1;if(n){let u=t.tr.step(d);u.setSelection(De.create(u.doc,a)),n(u.scrollIntoView())}return!0}function ro(t,e,n=!1){for(let s=t;s;s=e=="start"?s.firstChild:s.lastChild){if(s.isTextblock)return!0;if(n&&s.childCount!=1)return!1}return!1}const A2=(t,e,n)=>{let{$head:s,empty:r}=t.selection,a=s;if(!r)return!1;if(s.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):s.parentOffset>0)return!1;a=Xy(s)}let l=a&&a.nodeBefore;return!l||!ke.isSelectable(l)?!1:(e&&e(t.tr.setSelection(ke.create(t.doc,a.pos-l.nodeSize)).scrollIntoView()),!0)};function Xy(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function D2(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let s=D2(t,n);if(!s)return!1;let r=e0(s);if(!r)return!1;let a=r.nodeAfter;if(O2(t,r,e,1))return!0;if(s.parent.content.size==0&&(ro(a,"start")||ke.isSelectable(a))){let l=$f(t.doc,s.before(),s.after(),me.empty);if(l&&l.slice.size{let{$head:s,empty:r}=t.selection,a=s;if(!r)return!1;if(s.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):s.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let n=t.selection,s=n instanceof ke,r;if(s){if(n.node.isTextblock||!Qi(t.doc,n.from))return!1;r=n.from}else if(r=zf(t.doc,n.from,-1),r==null)return!1;if(e){let a=t.tr.join(r);s&&a.setSelection(ke.create(a.doc,r-t.doc.resolve(r).nodeBefore.nodeSize)),e(a.scrollIntoView())}return!0},wL=(t,e)=>{let n=t.selection,s;if(n instanceof ke){if(n.node.isTextblock||!Qi(t.doc,n.to))return!1;s=n.to}else if(s=zf(t.doc,n.to,1),s==null)return!1;return e&&e(t.tr.join(s).scrollIntoView()),!0},kL=(t,e)=>{let{$from:n,$to:s}=t.selection,r=n.blockRange(s),a=r&&vo(r);return a==null?!1:(e&&e(t.tr.lift(r,a).scrollIntoView()),!0)},P2=(t,e)=>{let{$head:n,$anchor:s}=t.selection;return!n.parent.type.spec.code||!n.sameParent(s)?!1:(e&&e(t.tr.insertText(` +`).scrollIntoView()),!0)};function t0(t){for(let e=0;e{let{$head:n,$anchor:s}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(s))return!1;let r=n.node(-1),a=n.indexAfter(-1),l=t0(r.contentMatchAt(a));if(!l||!r.canReplaceWith(a,a,l))return!1;if(e){let o=n.after(),c=t.tr.replaceWith(o,o,l.createAndFill());c.setSelection(Ie.near(c.doc.resolve(o),1)),e(c.scrollIntoView())}return!0},I2=(t,e)=>{let n=t.selection,{$from:s,$to:r}=n;if(n instanceof as||s.parent.inlineContent||r.parent.inlineContent)return!1;let a=t0(r.parent.contentMatchAt(r.indexAfter()));if(!a||!a.isTextblock)return!1;if(e){let l=(!s.parentOffset&&r.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let a=n.before();if(Rr(t.doc,a))return e&&e(t.tr.split(a).scrollIntoView()),!0}let s=n.blockRange(),r=s&&vo(s);return r==null?!1:(e&&e(t.tr.lift(s,r).scrollIntoView()),!0)};function CL(t){return(e,n)=>{let{$from:s,$to:r}=e.selection;if(e.selection instanceof ke&&e.selection.node.isBlock)return!s.parentOffset||!Rr(e.doc,s.pos)?!1:(n&&n(e.tr.split(s.pos).scrollIntoView()),!0);if(!s.depth)return!1;let a=[],l,o,c=!1,d=!1;for(let f=s.depth;;f--)if(s.node(f).isBlock){c=s.end(f)==s.pos+(s.depth-f),d=s.start(f)==s.pos-(s.depth-f),o=t0(s.node(f-1).contentMatchAt(s.indexAfter(f-1))),a.unshift(c&&o?{type:o}:null),l=f;break}else{if(f==1)return!1;a.unshift(null)}let u=e.tr;(e.selection instanceof De||e.selection instanceof as)&&u.deleteSelection();let h=u.mapping.map(s.pos),m=Rr(u.doc,h,a.length,a);if(m||(a[0]=o?{type:o}:null,m=Rr(u.doc,h,a.length,a)),!m)return!1;if(u.split(h,a.length,a),!c&&d&&s.node(l).type!=o){let f=u.mapping.map(s.before(l)),p=u.doc.resolve(f);o&&s.node(l-1).canReplaceWith(p.index(),p.index()+1,o)&&u.setNodeMarkup(u.mapping.map(s.before(l)),o)}return n&&n(u.scrollIntoView()),!0}}const EL=CL(),AL=(t,e)=>{let{$from:n,to:s}=t.selection,r,a=n.sharedDepth(s);return a==0?!1:(r=n.before(a),e&&e(t.tr.setSelection(ke.create(t.doc,r))),!0)};function DL(t,e,n){let s=e.nodeBefore,r=e.nodeAfter,a=e.index();return!s||!r||!s.type.compatibleContent(r.type)?!1:!s.content.size&&e.parent.canReplace(a-1,a)?(n&&n(t.tr.delete(e.pos-s.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(a,a+1)||!(r.isTextblock||Qi(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function O2(t,e,n,s){let r=e.nodeBefore,a=e.nodeAfter,l,o,c=r.type.spec.isolating||a.type.spec.isolating;if(!c&&DL(t,e,n))return!0;let d=!c&&e.parent.canReplace(e.index(),e.index()+1);if(d&&(l=(o=r.contentMatchAt(r.childCount)).findWrapping(a.type))&&o.matchType(l[0]||a.type).validEnd){if(n){let f=e.pos+a.nodeSize,p=X.empty;for(let y=l.length-1;y>=0;y--)p=X.from(l[y].create(null,p));p=X.from(r.copy(p));let g=t.tr.step(new en(e.pos-1,f,e.pos,f,new me(p,1,0),l.length,!0)),x=g.doc.resolve(f+2*l.length);x.nodeAfter&&x.nodeAfter.type==r.type&&Qi(g.doc,x.pos)&&g.join(x.pos),n(g.scrollIntoView())}return!0}let u=a.type.spec.isolating||s>0&&c?null:Ie.findFrom(e,1),h=u&&u.$from.blockRange(u.$to),m=h&&vo(h);if(m!=null&&m>=e.depth)return n&&n(t.tr.lift(h,m).scrollIntoView()),!0;if(d&&ro(a,"start",!0)&&ro(r,"end")){let f=r,p=[];for(;p.push(f),!f.isTextblock;)f=f.lastChild;let g=a,x=1;for(;!g.isTextblock;g=g.firstChild)x++;if(f.canReplace(f.childCount,f.childCount,g.content)){if(n){let y=X.empty;for(let b=p.length-1;b>=0;b--)y=X.from(p[b].copy(y));let v=t.tr.step(new en(e.pos-p.length,e.pos+a.nodeSize,e.pos+x,e.pos+a.nodeSize-x,new me(y,p.length,0),0,!0));n(v.scrollIntoView())}return!0}}return!1}function L2(t){return function(e,n){let s=e.selection,r=t<0?s.$from:s.$to,a=r.depth;for(;r.node(a).isInline;){if(!a)return!1;a--}return r.node(a).isTextblock?(n&&n(e.tr.setSelection(De.create(e.doc,t<0?r.start(a):r.end(a)))),!0):!1}}const ML=L2(-1),TL=L2(1);function PL(t,e=null){return function(n,s){let{$from:r,$to:a}=n.selection,l=r.blockRange(a),o=l&&Jy(l,t,e);return o?(s&&s(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function jj(t,e=null){return function(n,s){let r=!1;for(let a=0;a{if(r)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)r=!0;else{let u=n.doc.resolve(d),h=u.index();r=u.parent.canReplaceWith(h,h+1,t)}})}if(!r)return!1;if(s){let a=n.tr;for(let l=0;l=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=l.resolve(e.start-2);a=new yh(c,c,e.depth),e.endIndex=0;u--)a=X.from(n[u].type.create(n[u].attrs,a));t.step(new en(e.start-(s?2:0),e.end,e.start,e.end,new me(a,0,0),n.length,!0));let l=0;for(let u=0;ul.childCount>0&&l.firstChild.type==t);return a?n?s.node(a.depth-1).type==t?FL(e,n,t,a):zL(e,n,a):!0:!1}}function FL(t,e,n,s){let r=t.tr,a=s.end,l=s.$to.end(s.depth);ag;p--)f-=r.child(p).nodeSize,s.delete(f-1,f+1);let a=s.doc.resolve(n.start),l=a.nodeAfter;if(s.mapping.map(n.end)!=n.start+a.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==r.childCount,d=a.node(-1),u=a.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?X.empty:X.from(r))))return!1;let h=a.pos,m=h+l.nodeSize;return s.step(new en(h-(o?1:0),m+(c?1:0),h+1,m-1,new me((o?X.empty:X.from(r.copy(X.empty))).append(c?X.empty:X.from(r.copy(X.empty))),o?0:1,c?0:1),o?0:1)),e(s.scrollIntoView()),!0}function $L(t){return function(e,n){let{$from:s,$to:r}=e.selection,a=s.blockRange(r,d=>d.childCount>0&&d.firstChild.type==t);if(!a)return!1;let l=a.startIndex;if(l==0)return!1;let o=a.parent,c=o.child(l-1);if(c.type!=t)return!1;if(n){let d=c.lastChild&&c.lastChild.type==o.type,u=X.from(d?t.create():null),h=new me(X.from(t.create(null,X.from(o.type.create(null,u)))),d?3:1,0),m=a.start,f=a.end;n(e.tr.step(new en(m-(d?3:1),f,m,f,h,1,!0)).scrollIntoView())}return!0}}const an=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},io=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let Yg=null;const jr=function(t,e,n){let s=Yg||(Yg=document.createRange());return s.setEnd(t,n??t.nodeValue.length),s.setStart(t,e||0),s},BL=function(){Yg=null},Ka=function(t,e,n,s){return n&&(Nj(t,e,n,s,-1)||Nj(t,e,n,s,1))},_L=/^(img|br|input|textarea|hr)$/i;function Nj(t,e,n,s,r){for(var a;;){if(t==n&&e==s)return!0;if(e==(r<0?0:js(t))){let l=t.parentNode;if(!l||l.nodeType!=1||kd(t)||_L.test(t.nodeName)||t.contentEditable=="false")return!1;e=an(t)+(r<0?0:1),t=l}else if(t.nodeType==1){let l=t.childNodes[e+(r<0?-1:0)];if(l.nodeType==1&&l.contentEditable=="false")if(!((a=l.pmViewDesc)===null||a===void 0)&&a.ignoreForSelection)e+=r;else return!1;else t=l,e=r<0?js(t):0}else return!1}}function js(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function VL(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=js(t)}else if(t.parentNode&&!kd(t))e=an(t),t=t.parentNode;else return null}}function KL(t,e){for(;;){if(t.nodeType==3&&e2),ys=ao||(or?/Mac/.test(or.platform):!1),$2=or?/Win/.test(or.platform):!1,Pr=/Android \d/.test(Gi),Sd=!!wj&&"webkitFontSmoothing"in wj.documentElement.style,WL=Sd?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function QL(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function pr(t,e){return typeof t=="number"?t:t[e]}function GL(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,s=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*s}}function kj(t,e,n){let s=t.someProp("scrollThreshold")||0,r=t.someProp("scrollMargin")||5,a=t.dom.ownerDocument;for(let l=n||t.dom;l;){if(l.nodeType!=1){l=io(l);continue}let o=l,c=o==a.body,d=c?QL(a):GL(o),u=0,h=0;if(e.topd.bottom-pr(s,"bottom")&&(h=e.bottom-e.top>d.bottom-d.top?e.top+pr(r,"top")-d.top:e.bottom-d.bottom+pr(r,"bottom")),e.leftd.right-pr(s,"right")&&(u=e.right-d.right+pr(r,"right")),u||h)if(c)a.defaultView.scrollBy(u,h);else{let f=o.scrollLeft,p=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let g=o.scrollLeft-f,x=o.scrollTop-p;e={left:e.left-g,top:e.top-x,right:e.right-g,bottom:e.bottom-x}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:io(l)}}function JL(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),s,r;for(let a=(e.left+e.right)/2,l=n+1;l=n-20){s=o,r=c.top;break}}return{refDOM:s,refTop:r,stack:B2(t.dom)}}function B2(t){let e=[],n=t.ownerDocument;for(let s=t;s&&(e.push({dom:s,top:s.scrollTop,left:s.scrollLeft}),t!=n);s=io(s));return e}function ZL({refDOM:t,refTop:e,stack:n}){let s=t?t.getBoundingClientRect().top:0;_2(n,s==0?0:s-e)}function _2(t,e){for(let n=0;n=o){l=Math.max(p.bottom,l),o=Math.min(p.top,o);let g=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!c&&p.left<=e.left&&p.right>=e.left&&(c=u,d={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!n&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(a=h+1)}}return!n&&c&&(n=c,r=d,s=0),n&&n.nodeType==3?XL(n,r):!n||s&&n.nodeType==1?{node:t,offset:a}:V2(n,r)}function XL(t,e){let n=t.nodeValue.length,s=document.createRange(),r;for(let a=0;a=(l.left+l.right)/2?1:0)};break}}return s.detach(),r||{node:t,offset:0}}function s0(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function eF(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left(l.left+l.right)/2?1:-1}return t.docView.posFromDOM(s,r,a)}function nF(t,e,n,s){let r=-1;for(let a=e,l=!1;a!=t.dom;){let o=t.docView.nearestDesc(a,!0),c;if(!o)return null;if(o.dom.nodeType==1&&(o.node.isBlock&&o.parent||!o.contentDOM)&&((c=o.dom.getBoundingClientRect()).width||c.height)&&(o.node.isBlock&&o.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(o.dom.nodeName)&&(!l&&c.left>s.left||c.top>s.top?r=o.posBefore:(!l&&c.right-1?r:t.docView.posFromDOM(e,n,-1)}function K2(t,e,n){let s=t.childNodes.length;if(s&&n.tope.top&&r++}let d;Sd&&r&&s.nodeType==1&&(d=s.childNodes[r-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=e.top&&r--,s==t.dom&&r==s.childNodes.length-1&&s.lastChild.nodeType==1&&e.top>s.lastChild.getBoundingClientRect().bottom?o=t.state.doc.content.size:(r==0||s.nodeType!=1||s.childNodes[r-1].nodeName!="BR")&&(o=nF(t,s,r,e))}o==null&&(o=tF(t,l,e));let c=t.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function Sj(t){return t.top=0&&r==s.nodeValue.length?(c--,u=1):n<0?c--:d++,Ro(Zr(jr(s,c,d),u),u<0)}if(!t.state.doc.resolve(e-(a||0)).parent.inlineContent){if(a==null&&r&&(n<0||r==js(s))){let c=s.childNodes[r-1];if(c.nodeType==1)return Jm(c.getBoundingClientRect(),!1)}if(a==null&&r=0)}if(a==null&&r&&(n<0||r==js(s))){let c=s.childNodes[r-1],d=c.nodeType==3?jr(c,js(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return Ro(Zr(d,1),!1)}if(a==null&&r=0)}function Ro(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function Jm(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function q2(t,e,n){let s=t.state,r=t.root.activeElement;s!=e&&t.updateState(e),r!=t.dom&&t.focus();try{return n()}finally{s!=e&&t.updateState(s),r!=t.dom&&r&&r.focus()}}function iF(t,e,n){let s=e.selection,r=n=="up"?s.$from:s.$to;return q2(t,e,()=>{let{node:a}=t.docView.domFromPos(r.pos,n=="up"?-1:1);for(;;){let o=t.docView.nearestDesc(a,!0);if(!o)break;if(o.node.isBlock){a=o.contentDOM||o.dom;break}a=o.dom.parentNode}let l=U2(t,r.pos,1);for(let o=a.firstChild;o;o=o.nextSibling){let c;if(o.nodeType==1)c=o.getClientRects();else if(o.nodeType==3)c=jr(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;du.top+1&&(n=="up"?l.top-u.top>(u.bottom-l.top)*2:u.bottom-l.bottom>(l.bottom-u.top)*2))return!1}}return!0})}const aF=/[\u0590-\u08ac]/;function lF(t,e,n){let{$head:s}=e.selection;if(!s.parent.isTextblock)return!1;let r=s.parentOffset,a=!r,l=r==s.parent.content.size,o=t.domSelection();return o?!aF.test(s.parent.textContent)||!o.modify?n=="left"||n=="backward"?a:l:q2(t,e,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=t.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let f=s.depth?t.docView.domAfterPos(s.before()):t.dom,{focusNode:p,focusOffset:g}=t.domSelectionRange(),x=p&&!f.contains(p.nodeType==1?p:p.parentNode)||c==p&&d==g;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return m!=null&&(o.caretBidiLevel=m),x}):s.pos==s.start()||s.pos==s.end()}let Cj=null,Ej=null,Aj=!1;function oF(t,e,n){return Cj==e&&Ej==n?Aj:(Cj=e,Ej=n,Aj=n=="up"||n=="down"?iF(t,e,n):lF(t,e,n))}const Ss=0,Dj=1,ca=2,cr=3;class Cd{constructor(e,n,s,r){this.parent=e,this.children=n,this.dom=s,this.contentDOM=r,this.dirty=Ss,s.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,s){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;nan(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))r=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let a=e;;a=a.parentNode){if(a==this.dom){r=!1;break}if(a.previousSibling)break}if(r==null&&n==e.childNodes.length)for(let a=e;;a=a.parentNode){if(a==this.dom){r=!0;break}if(a.nextSibling)break}}return r??s>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let s=!0,r=e;r;r=r.parentNode){let a=this.getDesc(r),l;if(a&&(!n||a.node))if(s&&(l=a.nodeDOM)&&!(l.nodeType==1?l.contains(e.nodeType==1?e:e.parentNode):l==e))s=!1;else return a}}getDesc(e){let n=e.pmViewDesc;for(let s=n;s;s=s.parent)if(s==this)return n}posFromDOM(e,n,s){for(let r=e;r;r=r.parentNode){let a=this.getDesc(r);if(a)return a.localPosFromDOM(e,n,s)}return-1}descAt(e){for(let n=0,s=0;ne||l instanceof W2){r=e-a;break}a=o}if(r)return this.children[s].domFromPos(r-this.children[s].border,n);for(let a;s&&!(a=this.children[s-1]).size&&a instanceof H2&&a.side>=0;s--);if(n<=0){let a,l=!0;for(;a=s?this.children[s-1]:null,!(!a||a.dom.parentNode==this.contentDOM);s--,l=!1);return a&&n&&l&&!a.border&&!a.domAtom?a.domFromPos(a.size,n):{node:this.contentDOM,offset:a?an(a.dom)+1:0}}else{let a,l=!0;for(;a=s=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,n,u);e=l;for(let h=o;h>0;h--){let m=this.children[h-1];if(m.size&&m.dom.parentNode==this.contentDOM&&!m.emptyChildAt(1)){r=an(m.dom)+1;break}e-=m.size}r==-1&&(r=0)}if(r>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;up&&ln){let p=o;o=c,c=p}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(f)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let s=0,r=0;r=s:es){let o=s+a.border,c=l-a.border;if(e>=o&&n<=c){this.dirty=e==s||n==l?ca:Dj,e==o&&n==c&&(a.contentLost||a.dom.parentNode!=this.contentDOM)?a.dirty=cr:a.markDirty(e-o,n-o);return}else a.dirty=a.dom==a.contentDOM&&a.dom.parentNode==this.contentDOM&&!a.children.length?ca:cr}s=l}this.dirty=ca}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let s=e==1?ca:Dj;n.dirty{if(!a)return r;if(a.parent)return a.parent.posBeforeChild(a)})),!n.type.spec.raw){if(l.nodeType!=1){let o=document.createElement("span");o.appendChild(l),l=o}l.contentEditable="false",l.classList.add("ProseMirror-widget")}super(e,[],l,null),this.widget=n,this.widget=n,a=this}matchesWidget(e){return this.dirty==Ss&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class cF extends Cd{constructor(e,n,s,r){super(e,[],n,null),this.textDOM=s,this.text=r}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Ua extends Cd{constructor(e,n,s,r,a){super(e,[],s,r),this.mark=n,this.spec=a}static create(e,n,s,r){let a=r.nodeViews[n.type.name],l=a&&a(n,r,s);return(!l||!l.dom)&&(l=Ga.renderSpec(document,n.type.spec.toDOM(n,s),null,n.attrs)),new Ua(e,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&cr||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=cr&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=Ss){let s=this.parent;for(;!s.node;)s=s.parent;s.dirty0&&(a=sx(a,0,e,s));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},s,r),u=d&&d.dom,h=d&&d.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:h}=Ga.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let m=u;return u=J2(u,s,n),d?c=new dF(e,n,s,r,u,h||null,m,d,a,l+1):n.isText?new Vf(e,n,s,r,u,m,a):new zi(e,n,s,r,u,h||null,m,a,l+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let s=this.children[n];if(this.dom.contains(s.dom.parentNode)){e.contentElement=s.dom.parentNode;break}}e.contentElement||(e.getContent=()=>X.empty)}return e}matchesNode(e,n,s){return this.dirty==Ss&&e.eq(this.node)&&bh(n,this.outerDeco)&&s.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let s=this.node.inlineContent,r=n,a=e.composing?this.localCompositionInfo(e,n):null,l=a&&a.pos>-1?a:null,o=a&&a.pos<0,c=new hF(this,l&&l.node,e);pF(this.node,this.innerDeco,(d,u,h)=>{d.spec.marks?c.syncToMarks(d.spec.marks,s,e,u):d.type.side>=0&&!h&&c.syncToMarks(u==this.node.childCount?tt.none:this.node.child(u).marks,s,e,u),c.placeWidget(d,e,r)},(d,u,h,m)=>{c.syncToMarks(d.marks,s,e,m);let f;c.findNodeMatch(d,u,h,m)||o&&e.state.selection.from>r&&e.state.selection.to-1&&c.updateNodeAt(d,u,h,f,e)||c.updateNextNode(d,u,h,e,m,r)||c.addNode(d,u,h,e,r),r+=d.nodeSize}),c.syncToMarks([],s,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==ca)&&(l&&this.protectLocalComposition(e,l),Q2(this.contentDOM,this.children,e),ao&&gF(this.dom))}localCompositionInfo(e,n){let{from:s,to:r}=e.state.selection;if(!(e.state.selection instanceof De)||sn+this.node.content.size)return null;let a=e.input.compositionNode;if(!a||!this.dom.contains(a.parentNode))return null;if(this.node.inlineContent){let l=a.nodeValue,o=xF(this.node.content,l,s-n,r-n);return o<0?null:{node:a,pos:o,text:l}}else return{node:a,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:s,text:r}){if(this.getDesc(n))return;let a=n;for(;a.parentNode!=this.contentDOM;a=a.parentNode){for(;a.previousSibling;)a.parentNode.removeChild(a.previousSibling);for(;a.nextSibling;)a.parentNode.removeChild(a.nextSibling);a.pmViewDesc&&(a.pmViewDesc=void 0)}let l=new cF(this,a,n,r);e.input.compositionNodes.push(l),this.children=sx(this.children,s,s+r.length,e,l)}update(e,n,s,r){return this.dirty==cr||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,s,r),!0)}updateInner(e,n,s,r){this.updateOuterDeco(n),this.node=e,this.innerDeco=s,this.contentDOM&&this.updateChildren(r,this.posAtStart),this.dirty=Ss}updateOuterDeco(e){if(bh(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,s=this.dom;this.dom=G2(this.dom,this.nodeDOM,nx(this.outerDeco,this.node,n),nx(e,this.node,n)),this.dom!=s&&(s.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function Mj(t,e,n,s,r){J2(s,e,t);let a=new zi(void 0,t,e,n,s,s,s,r,0);return a.contentDOM&&a.updateChildren(r,0),a}class Vf extends zi{constructor(e,n,s,r,a,l,o){super(e,n,s,r,a,null,l,o,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,s,r){return this.dirty==cr||this.dirty!=Ss&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Ss||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,r.trackWrites==this.nodeDOM&&(r.trackWrites=null)),this.node=e,this.dirty=Ss,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,s){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,s)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,s){let r=this.node.cut(e,n),a=document.createTextNode(r.text);return new Vf(this.parent,r,this.outerDeco,this.innerDeco,a,a,s)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=cr)}get domAtom(){return!1}isText(e){return this.node.text==e}}class W2 extends Cd{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Ss&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class dF extends zi{constructor(e,n,s,r,a,l,o,c,d,u){super(e,n,s,r,a,l,o,d,u),this.spec=c}update(e,n,s,r){if(this.dirty==cr)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let a=this.spec.update(e,n,s);return a&&this.updateInner(e,n,s,r),a}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,s,r)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,s,r){this.spec.setSelection?this.spec.setSelection(e,n,s.root):super.setSelection(e,n,s,r)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Q2(t,e,n){let s=t.firstChild,r=!1;for(let a=0;a>1,o=Math.min(l,e.length);for(;a-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let u=Ua.create(this.top,e[l],n,s);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,l++}}findNodeMatch(e,n,s,r){let a=-1,l;if(r>=this.preMatch.index&&(l=this.preMatch.matches[r-this.preMatch.index]).parent==this.top&&l.matchesNode(e,n,s))a=this.top.children.indexOf(l,this.index);else for(let o=this.index,c=Math.min(this.top.children.length,o+5);o0;){let o;for(;;)if(s){let d=n.children[s-1];if(d instanceof Ua)n=d,s=d.children.length;else{o=d,s--;break}}else{if(n==e)break e;s=n.parent.children.indexOf(n),n=n.parent}let c=o.node;if(c){if(c!=t.child(r-1))break;--r,a.set(o,r),l.push(o)}}return{index:r,matched:a,matches:l.reverse()}}function mF(t,e){return t.type.side-e.type.side}function pF(t,e,n,s){let r=e.locals(t),a=0;if(r.length==0){for(let d=0;da;)o.push(r[l++]);let p=a+m.nodeSize;if(m.isText){let x=p;l!x.inline):o.slice();s(m,g,e.forChild(a,m),f),a=p}}function gF(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function xF(t,e,n,s){for(let r=0,a=0;r=n){if(a>=s&&c.slice(s-e.length-o,s-o)==e)return s-e.length;let d=o=0&&d+e.length+o>=n)return o+d;if(n==s&&c.length>=s+e.length-o&&c.slice(s-o,s-o+e.length)==e)return s}}return-1}function sx(t,e,n,s,r){let a=[];for(let l=0,o=0;l=n||u<=e?a.push(c):(dn&&a.push(c.slice(n-d,c.size,s)))}return a}function r0(t,e=null){let n=t.domSelectionRange(),s=t.state.doc;if(!n.focusNode)return null;let r=t.docView.nearestDesc(n.focusNode),a=r&&r.size==0,l=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(l<0)return null;let o=s.resolve(l),c,d;if(_f(n)){for(c=l;r&&!r.node;)r=r.parent;let h=r.node;if(r&&h.isAtom&&ke.isSelectable(h)&&r.parent&&!(h.isInline&&UL(n.focusNode,n.focusOffset,r.dom))){let m=r.posBefore;d=new ke(l==m?o:s.resolve(m))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,m=l;for(let f=0;f{(n.anchorNode!=s||n.anchorOffset!=r)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Z2(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function vF(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,s=n.nodeName=="IMG";s?e.collapse(n.parentNode,an(n)+1):e.collapse(n,0),!s&&!t.state.selection.visible&&Zn&&Fi<=11&&(n.disabled=!0,n.disabled=!1)}function Y2(t,e){if(e instanceof ke){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(Oj(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else Oj(t)}function Oj(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function i0(t,e,n,s){return t.someProp("createSelectionBetween",r=>r(t,e,n))||De.between(e,n,s)}function Lj(t){return t.editable&&!t.hasFocus()?!1:X2(t)}function X2(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function bF(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Ka(e.node,e.offset,n.anchorNode,n.anchorOffset)}function rx(t,e){let{$anchor:n,$head:s}=t.selection,r=e>0?n.max(s):n.min(s),a=r.parent.inlineContent?r.depth?t.doc.resolve(e>0?r.after():r.before()):null:r;return a&&Ie.findFrom(a,e)}function ei(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function Fj(t,e,n){let s=t.state.selection;if(s instanceof De)if(n.indexOf("s")>-1){let{$head:r}=s,a=r.textOffset?null:e<0?r.nodeBefore:r.nodeAfter;if(!a||a.isText||!a.isLeaf)return!1;let l=t.state.doc.resolve(r.pos+a.nodeSize*(e<0?-1:1));return ei(t,new De(s.$anchor,l))}else if(s.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let r=rx(t.state,e);return r&&r instanceof ke?ei(t,r):!1}else if(!(ys&&n.indexOf("m")>-1)){let r=s.$head,a=r.textOffset?null:e<0?r.nodeBefore:r.nodeAfter,l;if(!a||a.isText)return!1;let o=e<0?r.pos-a.nodeSize:r.pos;return a.isAtom||(l=t.docView.descAt(o))&&!l.contentDOM?ke.isSelectable(a)?ei(t,new ke(e<0?t.state.doc.resolve(r.pos-a.nodeSize):r)):Sd?ei(t,new De(t.state.doc.resolve(e<0?o:o+a.nodeSize))):!1:!1}}else return!1;else{if(s instanceof ke&&s.node.isInline)return ei(t,new De(e>0?s.$to:s.$from));{let r=rx(t.state,e);return r?ei(t,r):!1}}}function jh(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function cc(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function nl(t,e){return e<0?jF(t):NF(t)}function jF(t){let e=t.domSelectionRange(),n=e.focusNode,s=e.focusOffset;if(!n)return;let r,a,l=!1;for(ks&&n.nodeType==1&&s0){if(n.nodeType!=1)break;{let o=n.childNodes[s-1];if(cc(o,-1))r=n,a=--s;else if(o.nodeType==3)n=o,s=n.nodeValue.length;else break}}else{if(eE(n))break;{let o=n.previousSibling;for(;o&&cc(o,-1);)r=n.parentNode,a=an(o),o=o.previousSibling;if(o)n=o,s=jh(n);else{if(n=n.parentNode,n==t.dom)break;s=0}}}l?ix(t,n,s):r&&ix(t,r,a)}function NF(t){let e=t.domSelectionRange(),n=e.focusNode,s=e.focusOffset;if(!n)return;let r=jh(n),a,l;for(;;)if(s{t.state==r&&Or(t)},50)}function zj(t,e){let n=t.state.doc.resolve(e);if(!(cn||$2)&&n.parent.inlineContent){let r=t.coordsAtPos(e);if(e>n.start()){let a=t.coordsAtPos(e-1),l=(a.top+a.bottom)/2;if(l>r.top&&l1)return a.leftr.top&&l1)return a.left>r.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function $j(t,e,n){let s=t.state.selection;if(s instanceof De&&!s.empty||n.indexOf("s")>-1||ys&&n.indexOf("m")>-1)return!1;let{$from:r,$to:a}=s;if(!r.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let l=rx(t.state,e);if(l&&l instanceof ke)return ei(t,l)}if(!r.parent.inlineContent){let l=e<0?r:a,o=s instanceof as?Ie.near(l,e):Ie.findFrom(l,e);return o?ei(t,o):!1}return!1}function Bj(t,e){if(!(t.state.selection instanceof De))return!0;let{$head:n,$anchor:s,empty:r}=t.state.selection;if(!n.sameParent(s))return!0;if(!r)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let a=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(a&&!a.isText){let l=t.state.tr;return e<0?l.delete(n.pos-a.nodeSize,n.pos):l.delete(n.pos,n.pos+a.nodeSize),t.dispatch(l),!0}return!1}function _j(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function SF(t){if(!jn||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let s=e.firstChild;_j(t,s,"true"),setTimeout(()=>_j(t,s,"false"),20)}return!1}function CF(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function EF(t,e){let n=e.keyCode,s=CF(e);if(n==8||ys&&n==72&&s=="c")return Bj(t,-1)||nl(t,-1);if(n==46&&!e.shiftKey||ys&&n==68&&s=="c")return Bj(t,1)||nl(t,1);if(n==13||n==27)return!0;if(n==37||ys&&n==66&&s=="c"){let r=n==37?zj(t,t.state.selection.from)=="ltr"?-1:1:-1;return Fj(t,r,s)||nl(t,r)}else if(n==39||ys&&n==70&&s=="c"){let r=n==39?zj(t,t.state.selection.from)=="ltr"?1:-1:1;return Fj(t,r,s)||nl(t,r)}else{if(n==38||ys&&n==80&&s=="c")return $j(t,-1,s)||nl(t,-1);if(n==40||ys&&n==78&&s=="c")return SF(t)||$j(t,1,s)||nl(t,1);if(s==(ys?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function a0(t,e){t.someProp("transformCopied",f=>{e=f(e,t)});let n=[],{content:s,openStart:r,openEnd:a}=e;for(;r>1&&a>1&&s.childCount==1&&s.firstChild.childCount==1;){r--,a--;let f=s.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),s=f.content}let l=t.someProp("clipboardSerializer")||Ga.fromSchema(t.state.schema),o=aE(),c=o.createElement("div");c.appendChild(l.serializeFragment(s,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=iE[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let p=o.createElement(u[f]);for(;c.firstChild;)p.appendChild(c.firstChild);c.appendChild(p),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${r} ${a}${h?` -${h}`:""} ${JSON.stringify(n)}`);let m=t.someProp("clipboardTextSerializer",f=>f(e,t))||e.content.textBetween(0,e.content.size,` + +`);return{dom:c,text:m,slice:e}}function tE(t,e,n,s,r){let a=r.parent.type.spec.code,l,o;if(!n&&!e)return null;let c=!!e&&(s||a||!n);if(c){if(t.someProp("transformPastedText",m=>{e=m(e,a||s,t)}),a)return o=new me(X.from(t.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),t.someProp("transformPasted",m=>{o=m(o,t,!0)}),o;let h=t.someProp("clipboardTextParser",m=>m(e,r,s,t));if(h)o=h;else{let m=r.marks(),{schema:f}=t.state,p=Ga.fromSchema(f);l=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(g=>{let x=l.appendChild(document.createElement("p"));g&&x.appendChild(p.serializeNode(f.text(g,m)))})}}else t.someProp("transformPastedHTML",h=>{n=h(n,t)}),l=TF(n),Sd&&PF(l);let d=l&&l.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let h=+u[3];h>0;h--){let m=l.firstChild;for(;m&&m.nodeType!=1;)m=m.nextSibling;if(!m)break;l=m}if(o||(o=(t.someProp("clipboardParser")||t.someProp("domParser")||Li.fromSchema(t.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:r,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!AF.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=IF(Vj(o,+u[1],+u[2]),u[4]);else if(o=me.maxOpen(DF(o.content,r),!0),o.openStart||o.openEnd){let h=0,m=0;for(let f=o.content.firstChild;h{o=h(o,t,c)}),o}const AF=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function DF(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.index(n)),a,l=[];if(t.forEach(o=>{if(!l)return;let c=r.findWrapping(o.type),d;if(!c)return l=null;if(d=l.length&&a.length&&sE(c,a,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=rE(l[l.length-1],a.length));let u=nE(o,c);l.push(u),r=r.matchType(u.type),a=c}}),l)return X.from(l)}return t}function nE(t,e,n=0){for(let s=e.length-1;s>=n;s--)t=e[s].create(null,X.from(t));return t}function sE(t,e,n,s,r){if(r1&&(a=0),r=n&&(o=e<0?l.contentMatchAt(0).fillBefore(o,a<=r).append(o):o.append(l.contentMatchAt(l.childCount).fillBefore(X.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,l.copy(o))}function Vj(t,e,n){return en})),Ym.createHTML(t)):t}function TF(t){let e=/^(\s*]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n=aE().createElement("div"),s=/<([a-z][^>\s]+)/i.exec(t),r;if((r=s&&iE[s[1].toLowerCase()])&&(t=r.map(a=>"<"+a+">").join("")+t+r.map(a=>"").reverse().join("")),n.innerHTML=MF(t),r)for(let a=0;a=0;o-=2){let c=n.nodes[s[o]];if(!c||c.hasRequiredAttrs())break;r=X.from(c.create(s[o+1],r)),a++,l++}return new me(r,a,l)}const Tn={},Pn={},RF={touchstart:!0,touchmove:!0};class OF{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function LF(t){for(let e in Tn){let n=Tn[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=s=>{zF(t,s)&&!l0(t,s)&&(t.editable||!(s.type in Pn))&&n(t,s)},RF[e]?{passive:!0}:void 0)}jn&&t.dom.addEventListener("input",()=>null),lx(t)}function Si(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function FF(t){t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}function lx(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=s=>l0(t,s))})}function l0(t,e){return t.someProp("handleDOMEvents",n=>{let s=n[e.type];return s?s(t,e)||e.defaultPrevented:!1})}function zF(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function $F(t,e){!l0(t,e)&&Tn[e.type]&&(t.editable||!(e.type in Pn))&&Tn[e.type](t,e)}Pn.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=n.keyCode==16||n.shiftKey,!oE(t,n)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!(Pr&&cn&&n.keyCode==13)))if(n.keyCode!=229&&t.domObserver.forceFlush(),ao&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let s=Date.now();t.input.lastIOSEnter=s,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==s&&(t.someProp("handleKeyDown",r=>r(t,ta(13,"Enter"))),t.input.lastIOSEnter=0)},200)}else t.someProp("handleKeyDown",s=>s(t,n))||EF(t,n)?n.preventDefault():Si(t,"key")};Pn.keyup=(t,e)=>{e.keyCode==16&&(t.input.shiftKey=!1)};Pn.keypress=(t,e)=>{let n=e;if(oE(t,n)||!n.charCode||n.ctrlKey&&!n.altKey||ys&&n.metaKey)return;if(t.someProp("handleKeyPress",r=>r(t,n))){n.preventDefault();return}let s=t.state.selection;if(!(s instanceof De)||!s.$from.sameParent(s.$to)){let r=String.fromCharCode(n.charCode),a=()=>t.state.tr.insertText(r).scrollIntoView();!/[\r\n]/.test(r)&&!t.someProp("handleTextInput",l=>l(t,s.$from.pos,s.$to.pos,r,a))&&t.dispatch(a()),n.preventDefault()}};function Kf(t){return{left:t.clientX,top:t.clientY}}function BF(t,e){let n=e.x-t.clientX,s=e.y-t.clientY;return n*n+s*s<100}function o0(t,e,n,s,r){if(s==-1)return!1;let a=t.state.doc.resolve(s);for(let l=a.depth+1;l>0;l--)if(t.someProp(e,o=>l>a.depth?o(t,n,a.nodeAfter,a.before(l),r,!0):o(t,n,a.node(l),a.before(l),r,!1)))return!0;return!1}function Ml(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let s=t.state.tr.setSelection(e);s.setMeta("pointer",!0),t.dispatch(s)}function _F(t,e){if(e==-1)return!1;let n=t.state.doc.resolve(e),s=n.nodeAfter;return s&&s.isAtom&&ke.isSelectable(s)?(Ml(t,new ke(n)),!0):!1}function VF(t,e){if(e==-1)return!1;let n=t.state.selection,s,r;n instanceof ke&&(s=n.node);let a=t.state.doc.resolve(e);for(let l=a.depth+1;l>0;l--){let o=l>a.depth?a.nodeAfter:a.node(l);if(ke.isSelectable(o)){s&&n.$from.depth>0&&l>=n.$from.depth&&a.before(n.$from.depth+1)==n.$from.pos?r=a.before(n.$from.depth):r=a.before(l);break}}return r!=null?(Ml(t,ke.create(t.state.doc,r)),!0):!1}function KF(t,e,n,s,r){return o0(t,"handleClickOn",e,n,s)||t.someProp("handleClick",a=>a(t,e,s))||(r?VF(t,n):_F(t,n))}function UF(t,e,n,s){return o0(t,"handleDoubleClickOn",e,n,s)||t.someProp("handleDoubleClick",r=>r(t,e,s))}function qF(t,e,n,s){return o0(t,"handleTripleClickOn",e,n,s)||t.someProp("handleTripleClick",r=>r(t,e,s))||HF(t,n,s)}function HF(t,e,n){if(n.button!=0)return!1;let s=t.state.doc;if(e==-1)return s.inlineContent?(Ml(t,De.create(s,0,s.content.size)),!0):!1;let r=s.resolve(e);for(let a=r.depth+1;a>0;a--){let l=a>r.depth?r.nodeAfter:r.node(a),o=r.before(a);if(l.inlineContent)Ml(t,De.create(s,o+1,o+1+l.content.size));else if(ke.isSelectable(l))Ml(t,ke.create(s,o));else continue;return!0}}function c0(t){return Nh(t)}const lE=ys?"metaKey":"ctrlKey";Tn.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let s=c0(t),r=Date.now(),a="singleClick";r-t.input.lastClick.time<500&&BF(n,t.input.lastClick)&&!n[lE]&&t.input.lastClick.button==n.button&&(t.input.lastClick.type=="singleClick"?a="doubleClick":t.input.lastClick.type=="doubleClick"&&(a="tripleClick")),t.input.lastClick={time:r,x:n.clientX,y:n.clientY,type:a,button:n.button};let l=t.posAtCoords(Kf(n));l&&(a=="singleClick"?(t.input.mouseDown&&t.input.mouseDown.done(),t.input.mouseDown=new WF(t,l,n,!!s)):(a=="doubleClick"?UF:qF)(t,l.pos,l.inside,n)?n.preventDefault():Si(t,"pointer"))};class WF{constructor(e,n,s,r){this.view=e,this.pos=n,this.event=s,this.flushed=r,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!s[lE],this.allowDefault=s.shiftKey;let a,l;if(n.inside>-1)a=e.state.doc.nodeAt(n.inside),l=n.inside;else{let u=e.state.doc.resolve(n.pos);a=u.parent,l=u.depth?u.before():0}const o=r?null:s.target,c=o?e.docView.nearestDesc(o,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=e.state;(s.button==0&&a.type.spec.draggable&&a.type.spec.selectable!==!1||d instanceof ke&&d.from<=l&&d.to>l)&&(this.mightDrag={node:a,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&ks&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),Si(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>Or(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Kf(e))),this.updateAllowDefault(e),this.allowDefault||!n?Si(this.view,"pointer"):KF(this.view,n.pos,n.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||jn&&this.mightDrag&&!this.mightDrag.node.isAtom||cn&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(Ml(this.view,Ie.near(this.view.state.doc.resolve(n.pos))),e.preventDefault()):Si(this.view,"pointer")}move(e){this.updateAllowDefault(e),Si(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}Tn.touchstart=t=>{t.input.lastTouch=Date.now(),c0(t),Si(t,"pointer")};Tn.touchmove=t=>{t.input.lastTouch=Date.now(),Si(t,"pointer")};Tn.contextmenu=t=>c0(t);function oE(t,e){return t.composing?!0:jn&&Math.abs(e.timeStamp-t.input.compositionEndedAt)<500?(t.input.compositionEndedAt=-2e8,!0):!1}const QF=Pr?5e3:-1;Pn.compositionstart=Pn.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof De&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(s=>s.type.spec.inclusive===!1)||cn&&$2&&GF(t)))t.markCursor=t.state.storedMarks||n.marks(),Nh(t,!0),t.markCursor=null;else if(Nh(t,!e.selection.empty),ks&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let s=t.domSelectionRange();for(let r=s.focusNode,a=s.focusOffset;r&&r.nodeType==1&&a!=0;){let l=a<0?r.lastChild:r.childNodes[a-1];if(!l)break;if(l.nodeType==3){let o=t.domSelection();o&&o.collapse(l,l.nodeValue.length);break}else r=l,a=-1}}t.input.composing=!0}cE(t,QF)};function GF(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||e.nodeType!=1||n>=e.childNodes.length)return!1;let s=e.childNodes[n];return s.nodeType==1&&s.contentEditable=="false"}Pn.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=e.timeStamp,t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,cE(t,20))};function cE(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>Nh(t),e))}function dE(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=ZF());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function JF(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=VL(e.focusNode,e.focusOffset),s=KL(e.focusNode,e.focusOffset);if(n&&s&&n!=s){let r=s.pmViewDesc,a=t.domObserver.lastChangedTextNode;if(n==a||s==a)return a;if(!r||!r.isText(s.nodeValue))return s;if(t.input.compositionNode==s){let l=n.pmViewDesc;if(!(!l||!l.isText(n.nodeValue)))return s}}return n||s}function ZF(){let t=document.createEvent("Event");return t.initEvent("event",!0,!0),t.timeStamp}function Nh(t,e=!1){if(!(Pr&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),dE(t),e||t.docView&&t.docView.dirty){let n=r0(t),s=t.state.selection;return n&&!n.eq(s)?t.dispatch(t.state.tr.setSelection(n)):(t.markCursor||e)&&!s.$from.node(s.$from.sharedDepth(s.to)).inlineContent?t.dispatch(t.state.tr.deleteSelection()):t.updateState(t.state),!0}return!1}}function YF(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let s=getSelection(),r=document.createRange();r.selectNodeContents(e),t.dom.blur(),s.removeAllRanges(),s.addRange(r),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}const Wc=Zn&&Fi<15||ao&&WL<604;Tn.copy=Pn.cut=(t,e)=>{let n=e,s=t.state.selection,r=n.type=="cut";if(s.empty)return;let a=Wc?null:n.clipboardData,l=s.content(),{dom:o,text:c}=a0(t,l);a?(n.preventDefault(),a.clearData(),a.setData("text/html",o.innerHTML),a.setData("text/plain",c)):YF(t,o),r&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function XF(t){return t.openStart==0&&t.openEnd==0&&t.content.childCount==1?t.content.firstChild:null}function e6(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,s=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(s.contentEditable="true"),s.style.cssText="position: fixed; left: -10000px; top: 10px",s.focus();let r=t.input.shiftKey&&t.input.lastKeyCode!=45;setTimeout(()=>{t.focus(),s.parentNode&&s.parentNode.removeChild(s),n?Qc(t,s.value,null,r,e):Qc(t,s.textContent,s.innerHTML,r,e)},50)}function Qc(t,e,n,s,r){let a=tE(t,e,n,s,t.state.selection.$from);if(t.someProp("handlePaste",c=>c(t,r,a||me.empty)))return!0;if(!a)return!1;let l=XF(a),o=l?t.state.tr.replaceSelectionWith(l,s):t.state.tr.replaceSelection(a);return t.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function uE(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Pn.paste=(t,e)=>{let n=e;if(t.composing&&!Pr)return;let s=Wc?null:n.clipboardData,r=t.input.shiftKey&&t.input.lastKeyCode!=45;s&&Qc(t,uE(s),s.getData("text/html"),r,n)?n.preventDefault():e6(t,n)};class hE{constructor(e,n,s){this.slice=e,this.move=n,this.node=s}}const t6=ys?"altKey":"ctrlKey";function fE(t,e){let n=t.someProp("dragCopies",s=>!s(e));return n??!e[t6]}Tn.dragstart=(t,e)=>{let n=e,s=t.input.mouseDown;if(s&&s.done(),!n.dataTransfer)return;let r=t.state.selection,a=r.empty?null:t.posAtCoords(Kf(n)),l;if(!(a&&a.pos>=r.from&&a.pos<=(r instanceof ke?r.to-1:r.to))){if(s&&s.mightDrag)l=ke.create(t.state.doc,s.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let h=t.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=t.docView&&(l=ke.create(t.state.doc,h.posBefore))}}let o=(l||t.state.selection).content(),{dom:c,text:d,slice:u}=a0(t,o);(!n.dataTransfer.files.length||!cn||z2>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(Wc?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",Wc||n.dataTransfer.setData("text/plain",d),t.dragging=new hE(u,fE(t,n),l)};Tn.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)};Pn.dragover=Pn.dragenter=(t,e)=>e.preventDefault();Pn.drop=(t,e)=>{try{n6(t,e,t.dragging)}finally{t.dragging=null}};function n6(t,e,n){if(!e.dataTransfer)return;let s=t.posAtCoords(Kf(e));if(!s)return;let r=t.state.doc.resolve(s.pos),a=n&&n.slice;a?t.someProp("transformPasted",f=>{a=f(a,t,!1)}):a=tE(t,uE(e.dataTransfer),Wc?null:e.dataTransfer.getData("text/html"),!1,r);let l=!!(n&&fE(t,e));if(t.someProp("handleDrop",f=>f(t,e,a||me.empty,l))){e.preventDefault();return}if(!a)return;e.preventDefault();let o=a?x2(t.state.doc,r.pos,a):r.pos;o==null&&(o=r.pos);let c=t.state.tr;if(l){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=a.openStart==0&&a.openEnd==0&&a.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,a.content.firstChild):c.replaceRange(d,d,a),c.doc.eq(h))return;let m=c.doc.resolve(d);if(u&&ke.isSelectable(a.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(a.content.firstChild))c.setSelection(new ke(m));else{let f=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((p,g,x,y)=>f=y),c.setSelection(i0(t,m,c.doc.resolve(f)))}t.focus(),t.dispatch(c.setMeta("uiEvent","drop"))}Tn.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Or(t)},20))};Tn.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)};Tn.beforeinput=(t,e)=>{if(cn&&Pr&&e.inputType=="deleteContentBackward"){t.domObserver.flushSoon();let{domChangeCount:s}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=s||(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",a=>a(t,ta(8,"Backspace")))))return;let{$cursor:r}=t.state.selection;r&&r.pos>0&&t.dispatch(t.state.tr.delete(r.pos-1,r.pos).scrollIntoView())},50)}};for(let t in Pn)Tn[t]=Pn[t];function Gc(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}class wh{constructor(e,n){this.toDOM=e,this.spec=n||Da,this.side=this.spec.side||0}map(e,n,s,r){let{pos:a,deleted:l}=e.mapResult(n.from+r,this.side<0?-1:1);return l?null:new An(a-s,a-s,this)}valid(){return!0}eq(e){return this==e||e instanceof wh&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Gc(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class $i{constructor(e,n){this.attrs=e,this.spec=n||Da}map(e,n,s,r){let a=e.map(n.from+r,this.spec.inclusiveStart?-1:1)-s,l=e.map(n.to+r,this.spec.inclusiveEnd?1:-1)-s;return a>=l?null:new An(a,l,this)}valid(e,n){return n.from=e&&(!a||a(o.spec))&&s.push(o.copy(o.from+r,o.to+r))}for(let l=0;le){let o=this.children[l]+1;this.children[l+2].findInner(e-o,n-o,s,r+o,a)}}map(e,n,s){return this==gn||e.maps.length==0?this:this.mapInner(e,n,0,0,s||Da)}mapInner(e,n,s,r,a){let l;for(let o=0;o{let d=c+s,u;if(u=pE(n,o,d)){for(r||(r=this.children.slice());ao&&h.to=e){this.children[o]==e&&(s=this.children[o+2]);break}let a=e+1,l=a+n.content.size;for(let o=0;oa&&c.type instanceof $i){let d=Math.max(a,c.from)-a,u=Math.min(l,c.to)-a;dr.map(e,n,Da));return oi.from(s)}forChild(e,n){if(n.isLeaf)return yt.empty;let s=[];for(let r=0;rn instanceof yt)?e:e.reduce((n,s)=>n.concat(s instanceof yt?s:s.members),[]))}}forEachSet(e){for(let n=0;n{let x=g-p-(f-m);for(let y=0;yv+u-h)continue;let b=o[y]+u-h;f>=b?o[y+1]=m<=b?-2:-1:m>=u&&x&&(o[y]+=x,o[y+1]+=x)}h+=x}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=s.content.size){c=!0;continue}let m=n.map(t[d+1]+a,-1),f=m-r,{index:p,offset:g}=s.content.findIndex(h),x=s.maybeChild(p);if(x&&g==h&&g+x.nodeSize==f){let y=o[d+2].mapInner(n,x,u+1,t[d]+a+1,l);y!=gn?(o[d]=h,o[d+1]=f,o[d+2]=y):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=r6(o,t,e,n,r,a,l),u=kh(d,s,0,l);e=u.local;for(let h=0;hn&&l.to{let d=pE(t,o,c+n);if(d){a=!0;let u=kh(d,o,n+c+1,s);u!=gn&&r.push(c,c+o.nodeSize,u)}});let l=mE(a?gE(t):t,-n).sort(Ma);for(let o=0;o0;)e++;t.splice(e,0,n)}function Xm(t){let e=[];return t.someProp("decorations",n=>{let s=n(t.state);s&&s!=gn&&e.push(s)}),t.cursorWrapper&&e.push(yt.create(t.state.doc,[t.cursorWrapper.deco])),oi.from(e)}const i6={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},a6=Zn&&Fi<=11;class l6{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class o6{constructor(e,n){this.view=e,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new l6,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(s=>{for(let r=0;rr.type=="childList"&&r.removedNodes.length||r.type=="characterData"&&r.oldValue.length>r.target.nodeValue.length)?this.flushSoon():jn&&e.composing&&s.some(r=>r.type=="childList"&&r.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),a6&&(this.onCharData=s=>{this.queue.push({target:s.target,type:"characterData",oldValue:s.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,i6)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let n=0;nthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Lj(this.view)){if(this.suppressingSelectionUpdates)return Or(this.view);if(Zn&&Fi<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ka(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let n=new Set,s;for(let a=e.focusNode;a;a=io(a))n.add(a);for(let a=e.anchorNode;a;a=io(a))if(n.has(a)){s=a;break}let r=s&&this.view.docView.nearestDesc(s);if(r&&r.ignoreMutation({type:"selection",target:s.nodeType==3?s.parentNode:s}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let s=e.domSelectionRange(),r=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(s)&&Lj(e)&&!this.ignoreSelectionChange(s),a=-1,l=-1,o=!1,c=[];if(e.editable)for(let u=0;uu.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let h=u.nextSibling;h&&h.nodeType==1&&h.contentEditable=="false"&&u.parentNode.removeChild(u)}}else if(ks&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,m]=u;h.parentNode&&h.parentNode.parentNode==m.parentNode?m.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let m of u){let f=m.parentNode;f&&f.nodeName=="LI"&&(!h||u6(e,h)!=f)&&m.remove()}}}let d=null;a<0&&r&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||r)&&(a>-1&&(e.docView.markDirty(a,l),c6(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,h6(e,c)),this.handleDOMChange(a,l,o,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(s)||Or(e),this.currentSelection.set(s))}registerMutation(e,n){if(n.indexOf(e.target)>-1)return null;let s=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(s==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!s||s.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;ur;x--){let y=s.childNodes[x-1],v=y.pmViewDesc;if(y.nodeName=="BR"&&!v){a=x;break}if(!v||v.size)break}let h=t.state.doc,m=t.someProp("domParser")||Li.fromSchema(t.state.schema),f=h.resolve(l),p=null,g=m.parse(s,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:r,to:a,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:m6,context:f});if(d&&d[0].pos!=null){let x=d[0].pos,y=d[1]&&d[1].pos;y==null&&(y=x),p={anchor:x+l,head:y+l}}return{doc:g,sel:p,from:l,to:o}}function m6(t){let e=t.pmViewDesc;if(e)return e.parseRule();if(t.nodeName=="BR"&&t.parentNode){if(jn&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(t.parentNode.lastChild==t||jn&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}const p6=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function g6(t,e,n,s,r){let a=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let T=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,w=r0(t,T);if(w&&!t.state.selection.eq(w)){if(cn&&Pr&&t.input.lastKeyCode===13&&Date.now()-100M(t,ta(13,"Enter"))))return;let S=t.state.tr.setSelection(w);T=="pointer"?S.setMeta("pointer",!0):T=="key"&&S.scrollIntoView(),a&&S.setMeta("composition",a),t.dispatch(S)}return}let l=t.state.doc.resolve(e),o=l.sharedDepth(n);e=l.before(o+1),n=t.state.doc.resolve(n).after(o+1);let c=t.state.selection,d=f6(t,e,n),u=t.state.doc,h=u.slice(d.from,d.to),m,f;t.input.lastKeyCode===8&&Date.now()-100Date.now()-225||Pr)&&r.some(T=>T.nodeType==1&&!p6.test(T.nodeName))&&(!p||p.endA>=p.endB)&&t.someProp("handleKeyDown",T=>T(t,ta(13,"Enter")))){t.input.lastIOSEnter=0;return}if(!p)if(s&&c instanceof De&&!c.empty&&c.$head.sameParent(c.$anchor)&&!t.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))p={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let T=Qj(t,t.state.doc,d.sel);if(T&&!T.eq(t.state.selection)){let w=t.state.tr.setSelection(T);a&&w.setMeta("composition",a),t.dispatch(w)}}return}t.state.selection.fromt.state.selection.from&&p.start<=t.state.selection.from+2&&t.state.selection.from>=d.from?p.start=t.state.selection.from:p.endA=t.state.selection.to-2&&t.state.selection.to<=d.to&&(p.endB+=t.state.selection.to-p.endA,p.endA=t.state.selection.to)),Zn&&Fi<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>d.from&&d.doc.textBetween(p.start-d.from-1,p.start-d.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let g=d.doc.resolveNoCache(p.start-d.from),x=d.doc.resolveNoCache(p.endB-d.from),y=u.resolve(p.start),v=g.sameParent(x)&&g.parent.inlineContent&&y.end()>=p.endA;if((ao&&t.input.lastIOSEnter>Date.now()-225&&(!v||r.some(T=>T.nodeName=="DIV"||T.nodeName=="P"))||!v&&g.posT(t,ta(13,"Enter")))){t.input.lastIOSEnter=0;return}if(t.state.selection.anchor>p.start&&y6(u,p.start,p.endA,g,x)&&t.someProp("handleKeyDown",T=>T(t,ta(8,"Backspace")))){Pr&&cn&&t.domObserver.suppressSelectionUpdates();return}cn&&p.endB==p.start&&(t.input.lastChromeDelete=Date.now()),Pr&&!v&&g.start()!=x.start()&&x.parentOffset==0&&g.depth==x.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==p.endA&&(p.endB-=2,x=d.doc.resolveNoCache(p.endB-d.from),setTimeout(()=>{t.someProp("handleKeyDown",function(T){return T(t,ta(13,"Enter"))})},20));let b=p.start,j=p.endA,k=T=>{let w=T||t.state.tr.replace(b,j,d.doc.slice(p.start-d.from,p.endB-d.from));if(d.sel){let S=Qj(t,w.doc,d.sel);S&&!(cn&&t.composing&&S.empty&&(p.start!=p.endB||t.input.lastChromeDeleteOr(t),20));let T=k(t.state.tr.delete(b,j)),w=u.resolve(p.start).marksAcross(u.resolve(p.endA));w&&T.ensureMarks(w),t.dispatch(T)}else if(p.endA==p.endB&&(E=x6(g.parent.content.cut(g.parentOffset,x.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let T=k(t.state.tr);E.type=="add"?T.addMark(b,j,E.mark):T.removeMark(b,j,E.mark),t.dispatch(T)}else if(g.parent.child(g.index()).isText&&g.index()==x.index()-(x.textOffset?0:1)){let T=g.parent.textBetween(g.parentOffset,x.parentOffset),w=()=>k(t.state.tr.insertText(T,b,j));t.someProp("handleTextInput",S=>S(t,b,j,T,w))||t.dispatch(w())}else t.dispatch(k());else t.dispatch(k())}function Qj(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:i0(t,e.resolve(n.anchor),e.resolve(n.head))}function x6(t,e){let n=t.firstChild.marks,s=e.firstChild.marks,r=n,a=s,l,o,c;for(let u=0;uu.mark(o.addToSet(u.marks));else if(r.length==0&&a.length==1)o=a[0],l="remove",c=u=>u.mark(o.removeFromSet(u.marks));else return null;let d=[];for(let u=0;un||ep(l,!0,!1)0&&(e||t.indexAfter(s)==t.node(s).childCount);)s--,r++,e=!1;if(n){let a=t.node(s).maybeChild(t.indexAfter(s));for(;a&&!a.isLeaf;)a=a.firstChild,r++}return r}function v6(t,e,n,s,r){let a=t.findDiffStart(e,n);if(a==null)return null;let{a:l,b:o}=t.findDiffEnd(e,n+t.size,n+e.size);if(r=="end"){let c=Math.max(0,a-Math.min(l,o));s-=l+c-a}if(l=l?a-s:0;a-=c,a&&a=o?a-s:0;a-=c,a&&a=56320&&e<=57343&&n>=55296&&n<=56319}class xE{constructor(e,n){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new OF,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(eN),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=Yj(this),Zj(this),this.nodeViews=Xj(this),this.docView=Mj(this.state.doc,Jj(this),Xm(this),this.dom,this),this.domObserver=new o6(this,(s,r,a,l)=>g6(this,s,r,a,l)),this.domObserver.start(),LF(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let n in e)this._props[n]=e[n];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&lx(this);let n=this._props;this._props=e,e.plugins&&(e.plugins.forEach(eN),this.directPlugins=e.plugins),this.updateStateInner(e.state,n)}setProps(e){let n={};for(let s in this._props)n[s]=this._props[s];n.state=this.state;for(let s in e)n[s]=e[s];this.update(n)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,n){var s;let r=this.state,a=!1,l=!1;e.storedMarks&&this.composing&&(dE(this),l=!0),this.state=e;let o=r.plugins!=e.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=Xj(this);j6(f,this.nodeViews)&&(this.nodeViews=f,a=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&lx(this),this.editable=Yj(this),Zj(this);let c=Xm(this),d=Jj(this),u=r.plugins!=e.plugins&&!r.doc.eq(e.doc)?"reset":e.scrollToSelection>r.scrollToSelection?"to selection":"preserve",h=a||!this.docView.matchesNode(e.doc,d,c);(h||!e.selection.eq(r.selection))&&(l=!0);let m=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&JL(this);if(l){this.domObserver.stop();let f=h&&(Zn||cn)&&!this.composing&&!r.selection.empty&&!e.selection.empty&&b6(r.selection,e.selection);if(h){let p=cn?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=JF(this)),(a||!this.docView.update(e.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Mj(e.doc,d,c,this.dom,this)),p&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&bF(this))?Or(this,f):(Y2(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(r),!((s=this.dragging)===null||s===void 0)&&s.node&&!r.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,r),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():m&&ZL(m)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof ke){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&kj(this,n.getBoundingClientRect(),e)}else kj(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n0&&this.state.doc.nodeAt(a))==s.node&&(r=a)}this.dragging=new hE(e.slice,e.move,r<0?void 0:ke.create(this.state.doc,r))}someProp(e,n){let s=this._props&&this._props[e],r;if(s!=null&&(r=n?n(s):s))return r;for(let l=0;ln.ownerDocument.getSelection()),this._root=n}return e||document}updateRoot(){this._root=null}posAtCoords(e){return sF(this,e)}coordsAtPos(e,n=1){return U2(this,e,n)}domAtPos(e,n=0){return this.docView.domFromPos(e,n)}nodeDOM(e){let n=this.docView.descAt(e);return n?n.nodeDOM:null}posAtDOM(e,n,s=-1){let r=this.docView.posFromDOM(e,n,s);if(r==null)throw new RangeError("DOM position not inside the editor");return r}endOfTextblock(e,n){return oF(this,n||this.state,e)}pasteHTML(e,n){return Qc(this,"",e,!1,n||new ClipboardEvent("paste"))}pasteText(e,n){return Qc(this,e,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(e){return a0(this,e)}destroy(){this.docView&&(FF(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Xm(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,BL())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return $F(this,e)}domSelectionRange(){let e=this.domSelection();return e?jn&&this.root.nodeType===11&&qL(this.dom.ownerDocument)==this.dom&&d6(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}xE.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};function Jj(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(t.state)),n)for(let s in n)s=="class"?e.class+=" "+n[s]:s=="style"?e.style=(e.style?e.style+";":"")+n[s]:!e[s]&&s!="contenteditable"&&s!="nodeName"&&(e[s]=String(n[s]))}),e.translate||(e.translate="no"),[An.node(0,t.state.doc.content.size,e)]}function Zj(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:An.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Yj(t){return!t.someProp("editable",e=>e(t.state)===!1)}function b6(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}function Xj(t){let e=Object.create(null);function n(s){for(let r in s)Object.prototype.hasOwnProperty.call(e,r)||(e[r]=s[r])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function j6(t,e){let n=0,s=0;for(let r in t){if(t[r]!=e[r])return!0;n++}for(let r in e)s++;return n!=s}function eN(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var Vi={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},Sh={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},N6=typeof navigator<"u"&&/Mac/.test(navigator.platform),w6=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var ln=0;ln<10;ln++)Vi[48+ln]=Vi[96+ln]=String(ln);for(var ln=1;ln<=24;ln++)Vi[ln+111]="F"+ln;for(var ln=65;ln<=90;ln++)Vi[ln]=String.fromCharCode(ln+32),Sh[ln]=String.fromCharCode(ln);for(var tp in Vi)Sh.hasOwnProperty(tp)||(Sh[tp]=Vi[tp]);function k6(t){var e=N6&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||w6&&t.shiftKey&&t.key&&t.key.length==1||t.key=="Unidentified",n=!e&&t.key||(t.shiftKey?Sh:Vi)[t.keyCode]||t.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const S6=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),C6=typeof navigator<"u"&&/Win/.test(navigator.platform);function E6(t){let e=t.split(/-(?!$)/),n=e[e.length-1];n=="Space"&&(n=" ");let s,r,a,l;for(let o=0;o{for(var n in e)M6(t,n,{get:e[n],enumerable:!0})};function Uf(t){const{state:e,transaction:n}=t;let{selection:s}=n,{doc:r}=n,{storedMarks:a}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return a},get selection(){return s},get doc(){return r},get tr(){return s=n.selection,r=n.doc,a=n.storedMarks,n}}}var qf=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:s}=e,{tr:r}=n,a=this.buildProps(r);return Object.fromEntries(Object.entries(t).map(([l,o])=>[l,(...d)=>{const u=o(...d)(a);return!r.getMeta("preventDispatch")&&!this.hasCustomState&&s.dispatch(r),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:s,state:r}=this,{view:a}=s,l=[],o=!!t,c=t||r.tr,d=()=>(!o&&e&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(c),l.every(h=>h===!0)),u={...Object.fromEntries(Object.entries(n).map(([h,m])=>[h,(...p)=>{const g=this.buildProps(c,e),x=m(...p)(g);return l.push(x),u}])),run:d};return u}createCan(t){const{rawCommands:e,state:n}=this,s=!1,r=t||n.tr,a=this.buildProps(r,s);return{...Object.fromEntries(Object.entries(e).map(([o,c])=>[o,(...d)=>c(...d)({...a,dispatch:void 0})])),chain:()=>this.createChain(r,s)}}buildProps(t,e=!0){const{rawCommands:n,editor:s,state:r}=this,{view:a}=s,l={tr:t,editor:s,view:a,state:Uf({state:r,transaction:t}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(t,e),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([o,c])=>[o,(...d)=>c(...d)(l)]))}};return l}},vE={};h0(vE,{blur:()=>T6,clearContent:()=>P6,clearNodes:()=>I6,command:()=>R6,createParagraphNear:()=>O6,cut:()=>L6,deleteCurrentNode:()=>F6,deleteNode:()=>z6,deleteRange:()=>$6,deleteSelection:()=>B6,enter:()=>_6,exitCode:()=>V6,extendMarkRange:()=>K6,first:()=>U6,focus:()=>H6,forEach:()=>W6,insertContent:()=>Q6,insertContentAt:()=>Z6,joinBackward:()=>ez,joinDown:()=>X6,joinForward:()=>tz,joinItemBackward:()=>nz,joinItemForward:()=>sz,joinTextblockBackward:()=>rz,joinTextblockForward:()=>iz,joinUp:()=>Y6,keyboardShortcut:()=>lz,lift:()=>oz,liftEmptyBlock:()=>cz,liftListItem:()=>dz,newlineInCode:()=>uz,resetAttributes:()=>hz,scrollIntoView:()=>fz,selectAll:()=>mz,selectNodeBackward:()=>pz,selectNodeForward:()=>gz,selectParentNode:()=>xz,selectTextblockEnd:()=>yz,selectTextblockStart:()=>vz,setContent:()=>bz,setMark:()=>Bz,setMeta:()=>_z,setNode:()=>Vz,setNodeSelection:()=>Kz,setTextDirection:()=>Uz,setTextSelection:()=>qz,sinkListItem:()=>Hz,splitBlock:()=>Wz,splitListItem:()=>Qz,toggleList:()=>Gz,toggleMark:()=>Jz,toggleNode:()=>Zz,toggleWrap:()=>Yz,undoInputRule:()=>Xz,unsetAllMarks:()=>e$,unsetMark:()=>t$,unsetTextDirection:()=>n$,updateAttributes:()=>s$,wrapIn:()=>r$,wrapInList:()=>i$});var T6=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),(n=window==null?void 0:window.getSelection())==null||n.removeAllRanges())}),!0),P6=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),I6=()=>({state:t,tr:e,dispatch:n})=>{const{selection:s}=e,{ranges:r}=s;return n&&r.forEach(({$from:a,$to:l})=>{t.doc.nodesBetween(a.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=e,h=d.resolve(u.map(c)),m=d.resolve(u.map(c+o.nodeSize)),f=h.blockRange(m);if(!f)return;const p=vo(f);if(o.type.isTextblock){const{defaultType:g}=h.parent.contentMatchAt(h.index());e.setNodeMarkup(f.start,g)}(p||p===0)&&e.lift(f,p)})}),!0},R6=t=>e=>t(e),O6=()=>({state:t,dispatch:e})=>I2(t,e),L6=(t,e)=>({editor:n,tr:s})=>{const{state:r}=n,a=r.doc.slice(t.from,t.to);s.deleteRange(t.from,t.to);const l=s.mapping.map(e);return s.insert(l,a.content),s.setSelection(new De(s.doc.resolve(Math.max(l-1,0)))),!0},F6=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,s=n.$anchor.node();if(s.content.size>0)return!1;const r=t.selection.$anchor;for(let a=r.depth;a>0;a-=1)if(r.node(a).type===s.type){if(e){const o=r.before(a),c=r.after(a);t.delete(o,c).scrollIntoView()}return!0}return!1};function Bt(t,e){if(typeof t=="string"){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}var z6=t=>({tr:e,state:n,dispatch:s})=>{const r=Bt(t,n.schema),a=e.selection.$anchor;for(let l=a.depth;l>0;l-=1)if(a.node(l).type===r){if(s){const c=a.before(l),d=a.after(l);e.delete(c,d).scrollIntoView()}return!0}return!1},$6=t=>({tr:e,dispatch:n})=>{const{from:s,to:r}=t;return n&&e.delete(s,r),!0},B6=()=>({state:t,dispatch:e})=>Yy(t,e),_6=()=>({commands:t})=>t.keyboardShortcut("Enter"),V6=()=>({state:t,dispatch:e})=>SL(t,e);function f0(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function Ch(t,e,n={strict:!0}){const s=Object.keys(e);return s.length?s.every(r=>n.strict?e[r]===t[r]:f0(e[r])?e[r].test(t[r]):e[r]===t[r]):!0}function bE(t,e,n={}){return t.find(s=>s.type===e&&Ch(Object.fromEntries(Object.keys(n).map(r=>[r,s.attrs[r]])),n))}function tN(t,e,n={}){return!!bE(t,e,n)}function m0(t,e,n){var s;if(!t||!e)return;let r=t.parent.childAfter(t.parentOffset);if((!r.node||!r.node.marks.some(u=>u.type===e))&&(r=t.parent.childBefore(t.parentOffset)),!r.node||!r.node.marks.some(u=>u.type===e)||(n=n||((s=r.node.marks[0])==null?void 0:s.attrs),!bE([...r.node.marks],e,n)))return;let l=r.index,o=t.start()+r.offset,c=l+1,d=o+r.node.nodeSize;for(;l>0&&tN([...t.parent.child(l-1).marks],e,n);)l-=1,o-=t.parent.child(l).nodeSize;for(;c({tr:n,state:s,dispatch:r})=>{const a=Hr(t,s.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(r){const h=m0(c,a,e);if(h&&h.from<=d&&h.to>=u){const m=De.create(l,h.from,h.to);n.setSelection(m)}}return!0},U6=t=>e=>{const n=typeof t=="function"?t(e):t;for(let s=0;s({editor:n,view:s,tr:r,dispatch:a})=>{e={scrollIntoView:!0,...e};const l=()=>{(Eh()||nN())&&s.dom.focus(),q6()&&!Eh()&&!nN()&&s.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(s.focus(),e!=null&&e.scrollIntoView&&n.commands.scrollIntoView())})};try{if(s.hasFocus()&&t===null||t===!1)return!0}catch{return!1}if(a&&t===null&&!jE(n.state.selection))return l(),!0;const o=NE(r.doc,t)||n.state.selection,c=n.state.selection.eq(o);return a&&(c||r.setSelection(o),c&&r.storedMarks&&r.setStoredMarks(r.storedMarks),l()),!0},W6=(t,e)=>n=>t.every((s,r)=>e(s,{...n,index:r})),Q6=(t,e)=>({tr:n,commands:s})=>s.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),wE=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const s=e[n];s.nodeType===3&&s.nodeValue&&/^(\n\s\s|\n)$/.test(s.nodeValue)?t.removeChild(s):s.nodeType===1&&wE(s)}return t};function eu(t){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${t}`,n=new window.DOMParser().parseFromString(e,"text/html").body;return wE(n)}function Jc(t,e,n){if(t instanceof _s||t instanceof X)return t;n={slice:!0,parseOptions:{},...n};const s=typeof t=="object"&&t!==null,r=typeof t=="string";if(s)try{if(Array.isArray(t)&&t.length>0)return X.fromArray(t.map(o=>e.nodeFromJSON(o)));const l=e.nodeFromJSON(t);return n.errorOnInvalidContent&&l.check(),l}catch(a){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:a});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",a),Jc("",e,n)}if(r){if(n.errorOnInvalidContent){let l=!1,o="";const c=new a2({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:d=>(l=!0,o=typeof d=="string"?d:d.outerHTML,null)}]}})});if(n.slice?Li.fromSchema(c).parseSlice(eu(t),n.parseOptions):Li.fromSchema(c).parse(eu(t),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const a=Li.fromSchema(e);return n.slice?a.parseSlice(eu(t),n.parseOptions).content:a.parse(eu(t),n.parseOptions)}return Jc("",e,n)}function G6(t,e,n){const s=t.steps.length-1;if(s{l===0&&(l=u)}),t.setSelection(Ie.near(t.doc.resolve(l),n))}var J6=t=>!("type"in t),Z6=(t,e,n)=>({tr:s,dispatch:r,editor:a})=>{var l;if(r){n={parseOptions:a.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=x=>{a.emit("contentError",{editor:a,error:x,disableCollaboration:()=>{"collaboration"in a.storage&&typeof a.storage.collaboration=="object"&&a.storage.collaboration&&(a.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!a.options.enableContentCheck&&a.options.emitContentError)try{Jc(e,a.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(x){c(x)}try{o=Jc(e,a.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!=null?l:a.options.enableContentCheck})}catch(x){return c(x),!1}let{from:u,to:h}=typeof t=="number"?{from:t,to:t}:{from:t.from,to:t.to},m=!0,f=!0;if((J6(o)?o:[o]).forEach(x=>{x.check(),m=m?x.isText&&x.marks.length===0:!1,f=f?x.isBlock:!1}),u===h&&f){const{parent:x}=s.doc.resolve(u);x.isTextblock&&!x.type.spec.code&&!x.childCount&&(u-=1,h+=1)}let g;if(m){if(Array.isArray(e))g=e.map(x=>x.text||"").join("");else if(e instanceof X){let x="";e.forEach(y=>{y.text&&(x+=y.text)}),g=x}else typeof e=="object"&&e&&e.text?g=e.text:g=e;s.insertText(g,u,h)}else{g=o;const x=s.doc.resolve(u),y=x.node(),v=x.parentOffset===0,b=y.isText||y.isTextblock,j=y.content.size>0;v&&b&&j&&(u=Math.max(0,u-1)),s.replaceWith(u,h,g)}n.updateSelection&&G6(s,s.steps.length-1,-1),n.applyInputRules&&s.setMeta("applyInputRules",{from:u,text:g}),n.applyPasteRules&&s.setMeta("applyPasteRules",{from:u,text:g})}return!0},Y6=()=>({state:t,dispatch:e})=>NL(t,e),X6=()=>({state:t,dispatch:e})=>wL(t,e),ez=()=>({state:t,dispatch:e})=>C2(t,e),tz=()=>({state:t,dispatch:e})=>M2(t,e),nz=()=>({state:t,dispatch:e,tr:n})=>{try{const s=zf(t.doc,t.selection.$from.pos,-1);return s==null?!1:(n.join(s,2),e&&e(n),!0)}catch{return!1}},sz=()=>({state:t,dispatch:e,tr:n})=>{try{const s=zf(t.doc,t.selection.$from.pos,1);return s==null?!1:(n.join(s,2),e&&e(n),!0)}catch{return!1}},rz=()=>({state:t,dispatch:e})=>bL(t,e),iz=()=>({state:t,dispatch:e})=>jL(t,e);function kE(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function az(t){const e=t.split(/-(?!$)/);let n=e[e.length-1];n==="Space"&&(n=" ");let s,r,a,l;for(let o=0;o({editor:e,view:n,tr:s,dispatch:r})=>{const a=az(t).split(/-(?!$)/),l=a.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),o=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:a.includes("Alt"),ctrlKey:a.includes("Ctrl"),metaKey:a.includes("Meta"),shiftKey:a.includes("Shift"),bubbles:!0,cancelable:!0}),c=e.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,o))});return c==null||c.steps.forEach(d=>{const u=d.map(s.mapping);u&&r&&s.maybeStep(u)}),!0};function Ki(t,e,n={}){const{from:s,to:r,empty:a}=t.selection,l=e?Bt(e,t.schema):null,o=[];t.doc.nodesBetween(s,r,(h,m)=>{if(h.isText)return;const f=Math.max(s,m),p=Math.min(r,m+h.nodeSize);o.push({node:h,from:f,to:p})});const c=r-s,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>Ch(h.node.attrs,n,{strict:!1}));return a?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}var oz=(t,e={})=>({state:n,dispatch:s})=>{const r=Bt(t,n.schema);return Ki(n,r,e)?kL(n,s):!1},cz=()=>({state:t,dispatch:e})=>R2(t,e),dz=t=>({state:e,dispatch:n})=>{const s=Bt(t,e.schema);return LL(s)(e,n)},uz=()=>({state:t,dispatch:e})=>P2(t,e);function Hf(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function sN(t,e){const n=typeof e=="string"?[e]:e;return Object.keys(t).reduce((s,r)=>(n.includes(r)||(s[r]=t[r]),s),{})}var hz=(t,e)=>({tr:n,state:s,dispatch:r})=>{let a=null,l=null;const o=Hf(typeof t=="string"?t:t.name,s.schema);if(!o)return!1;o==="node"&&(a=Bt(t,s.schema)),o==="mark"&&(l=Hr(t,s.schema));let c=!1;return n.selection.ranges.forEach(d=>{s.doc.nodesBetween(d.$from.pos,d.$to.pos,(u,h)=>{a&&a===u.type&&(c=!0,r&&n.setNodeMarkup(h,void 0,sN(u.attrs,e))),l&&u.marks.length&&u.marks.forEach(m=>{l===m.type&&(c=!0,r&&n.addMark(h,h+u.nodeSize,l.create(sN(m.attrs,e))))})})}),c},fz=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),mz=()=>({tr:t,dispatch:e})=>{if(e){const n=new as(t.doc);t.setSelection(n)}return!0},pz=()=>({state:t,dispatch:e})=>A2(t,e),gz=()=>({state:t,dispatch:e})=>T2(t,e),xz=()=>({state:t,dispatch:e})=>AL(t,e),yz=()=>({state:t,dispatch:e})=>TL(t,e),vz=()=>({state:t,dispatch:e})=>ML(t,e);function ox(t,e,n={},s={}){return Jc(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:s.errorOnInvalidContent})}var bz=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:s={}}={})=>({editor:r,tr:a,dispatch:l,commands:o})=>{const{doc:c}=a;if(s.preserveWhitespace!=="full"){const d=ox(t,r.schema,s,{errorOnInvalidContent:e??r.options.enableContentCheck});return l&&a.replaceWith(0,c.content.size,d).setMeta("preventUpdate",!n),!0}return l&&a.setMeta("preventUpdate",!n),o.insertContentAt({from:0,to:c.content.size},t,{parseOptions:s,errorOnInvalidContent:e??r.options.enableContentCheck})};function SE(t,e){const n=Hr(e,t.schema),{from:s,to:r,empty:a}=t.selection,l=[];a?(t.storedMarks&&l.push(...t.storedMarks),l.push(...t.selection.$head.marks())):t.doc.nodesBetween(s,r,c=>{l.push(...c.marks)});const o=l.find(c=>c.type.name===n.name);return o?{...o.attrs}:{}}function CE(t,e){const n=new N2(t);return e.forEach(s=>{s.steps.forEach(r=>{n.step(r)})}),n}function jz(t){for(let e=0;e{n(r)&&s.push({node:r,pos:a})}),s}function wz(t,e){for(let n=t.depth;n>0;n-=1){const s=t.node(n);if(e(s))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:s}}}function Wf(t){return e=>wz(e.$from,t)}function we(t,e,n){return t.config[e]===void 0&&t.parent?we(t.parent,e,n):typeof t.config[e]=="function"?t.config[e].bind({...n,parent:t.parent?we(t.parent,e,n):null}):t.config[e]}function p0(t){return t.map(e=>{const n={name:e.name,options:e.options,storage:e.storage},s=we(e,"addExtensions",n);return s?[e,...p0(s())]:e}).flat(10)}function g0(t,e){const n=Ga.fromSchema(e).serializeFragment(t),r=document.implementation.createHTMLDocument().createElement("div");return r.appendChild(n),r.innerHTML}function EE(t){return typeof t=="function"}function Ze(t,e=void 0,...n){return EE(t)?e?t.bind(e)(...n):t(...n):t}function kz(t={}){return Object.keys(t).length===0&&t.constructor===Object}function lo(t){const e=t.filter(r=>r.type==="extension"),n=t.filter(r=>r.type==="node"),s=t.filter(r=>r.type==="mark");return{baseExtensions:e,nodeExtensions:n,markExtensions:s}}function AE(t){const e=[],{nodeExtensions:n,markExtensions:s}=lo(t),r=[...n,...s],a={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return t.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage,extensions:r},c=we(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([m,f])=>{e.push({type:h,name:m,attribute:{...a,...f}})})})})}),r.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=we(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,h])=>{const m={...a,...h};typeof(m==null?void 0:m.default)=="function"&&(m.default=m.default()),m!=null&&m.isRequired&&(m==null?void 0:m.default)===void 0&&delete m.default,e.push({type:l.name,name:u,attribute:m})})}),e}function _t(...t){return t.filter(e=>!!e).reduce((e,n)=>{const s={...e};return Object.entries(n).forEach(([r,a])=>{if(!s[r]){s[r]=a;return}if(r==="class"){const o=a?String(a).split(" "):[],c=s[r]?s[r].split(" "):[],d=o.filter(u=>!c.includes(u));s[r]=[...c,...d].join(" ")}else if(r==="style"){const o=a?a.split(";").map(u=>u.trim()).filter(Boolean):[],c=s[r]?s[r].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,m]=u.split(":").map(f=>f.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(f=>f.trim());d.set(h,m)}),s[r]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else s[r]=a}),s},{})}function Zc(t,e){return e.filter(n=>n.type===t.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(t.attrs)||{}:{[n.name]:t.attrs[n.name]}).reduce((n,s)=>_t(n,s),{})}function Sz(t){return typeof t!="string"?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):t==="true"?!0:t==="false"?!1:t}function rN(t,e){return"style"in t?t:{...t,getAttrs:n=>{const s=t.getAttrs?t.getAttrs(n):t.attrs;if(s===!1)return!1;const r=e.reduce((a,l)=>{const o=l.attribute.parseHTML?l.attribute.parseHTML(n):Sz(n.getAttribute(l.name));return o==null?a:{...a,[l.name]:o}},{});return{...s,...r}}}}function iN(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e==="attrs"&&kz(n)?!1:n!=null))}function aN(t){var e,n;const s={};return!((e=t==null?void 0:t.attribute)!=null&&e.isRequired)&&"default"in((t==null?void 0:t.attribute)||{})&&(s.default=t.attribute.default),((n=t==null?void 0:t.attribute)==null?void 0:n.validate)!==void 0&&(s.validate=t.attribute.validate),[t.name,s]}function Cz(t,e){var n;const s=AE(t),{nodeExtensions:r,markExtensions:a}=lo(t),l=(n=r.find(d=>we(d,"topNode")))==null?void 0:n.name,o=Object.fromEntries(r.map(d=>{const u=s.filter(y=>y.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:e},m=t.reduce((y,v)=>{const b=we(v,"extendNodeSchema",h);return{...y,...b?b(d):{}}},{}),f=iN({...m,content:Ze(we(d,"content",h)),marks:Ze(we(d,"marks",h)),group:Ze(we(d,"group",h)),inline:Ze(we(d,"inline",h)),atom:Ze(we(d,"atom",h)),selectable:Ze(we(d,"selectable",h)),draggable:Ze(we(d,"draggable",h)),code:Ze(we(d,"code",h)),whitespace:Ze(we(d,"whitespace",h)),linebreakReplacement:Ze(we(d,"linebreakReplacement",h)),defining:Ze(we(d,"defining",h)),isolating:Ze(we(d,"isolating",h)),attrs:Object.fromEntries(u.map(aN))}),p=Ze(we(d,"parseHTML",h));p&&(f.parseDOM=p.map(y=>rN(y,u)));const g=we(d,"renderHTML",h);g&&(f.toDOM=y=>g({node:y,HTMLAttributes:Zc(y,u)}));const x=we(d,"renderText",h);return x&&(f.toText=x),[d.name,f]})),c=Object.fromEntries(a.map(d=>{const u=s.filter(x=>x.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:e},m=t.reduce((x,y)=>{const v=we(y,"extendMarkSchema",h);return{...x,...v?v(d):{}}},{}),f=iN({...m,inclusive:Ze(we(d,"inclusive",h)),excludes:Ze(we(d,"excludes",h)),group:Ze(we(d,"group",h)),spanning:Ze(we(d,"spanning",h)),code:Ze(we(d,"code",h)),attrs:Object.fromEntries(u.map(aN))}),p=Ze(we(d,"parseHTML",h));p&&(f.parseDOM=p.map(x=>rN(x,u)));const g=we(d,"renderHTML",h);return g&&(f.toDOM=x=>g({mark:x,HTMLAttributes:Zc(x,u)})),[d.name,f]}));return new a2({topNode:l,nodes:o,marks:c})}function Ez(t){const e=t.filter((n,s)=>t.indexOf(n)!==s);return Array.from(new Set(e))}function Ah(t){return t.sort((n,s)=>{const r=we(n,"priority")||100,a=we(s,"priority")||100;return r>a?-1:rs.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(s=>`'${s}'`).join(", ")}]. This can lead to issues.`),e}function ME(t,e,n){const{from:s,to:r}=e,{blockSeparator:a=` + +`,textSerializers:l={}}=n||{};let o="";return t.nodesBetween(s,r,(c,d,u,h)=>{var m;c.isBlock&&d>s&&(o+=a);const f=l==null?void 0:l[c.type.name];if(f)return u&&(o+=f({node:c,pos:d,parent:u,index:h,range:e})),!1;c.isText&&(o+=(m=c==null?void 0:c.text)==null?void 0:m.slice(Math.max(s,d)-d,r-d))}),o}function Az(t,e){const n={from:0,to:t.content.size};return ME(t,n,e)}function TE(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,e])=>e.spec.toText).map(([e,n])=>[e,n.spec.toText]))}function Dz(t,e){const n=Bt(e,t.schema),{from:s,to:r}=t.selection,a=[];t.doc.nodesBetween(s,r,o=>{a.push(o)});const l=a.reverse().find(o=>o.type.name===n.name);return l?{...l.attrs}:{}}function PE(t,e){const n=Hf(typeof e=="string"?e:e.name,t.schema);return n==="node"?Dz(t,e):n==="mark"?SE(t,e):{}}function Mz(t,e=JSON.stringify){const n={};return t.filter(s=>{const r=e(s);return Object.prototype.hasOwnProperty.call(n,r)?!1:n[r]=!0})}function Tz(t){const e=Mz(t);return e.length===1?e:e.filter((n,s)=>!e.filter((a,l)=>l!==s).some(a=>n.oldRange.from>=a.oldRange.from&&n.oldRange.to<=a.oldRange.to&&n.newRange.from>=a.newRange.from&&n.newRange.to<=a.newRange.to))}function IE(t){const{mapping:e,steps:n}=t,s=[];return e.maps.forEach((r,a)=>{const l=[];if(r.ranges.length)r.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=n[a];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=e.slice(a).map(o,-1),u=e.slice(a).map(c),h=e.invert().map(d,-1),m=e.invert().map(u);s.push({oldRange:{from:h,to:m},newRange:{from:d,to:u}})})}),Tz(s)}function x0(t,e,n){const s=[];return t===e?n.resolve(t).marks().forEach(r=>{const a=n.resolve(t),l=m0(a,r.type);l&&s.push({mark:r,...l})}):n.nodesBetween(t,e,(r,a)=>{!r||(r==null?void 0:r.nodeSize)===void 0||s.push(...r.marks.map(l=>({from:a,to:a+r.nodeSize,mark:l})))}),s}var Pz=(t,e,n,s=20)=>{const r=t.doc.resolve(n);let a=s,l=null;for(;a>0&&l===null;){const o=r.node(a);(o==null?void 0:o.type.name)===e?l=o:a-=1}return[l,a]};function tu(t,e){return e.nodes[t]||e.marks[t]||null}function Mu(t,e,n){return Object.fromEntries(Object.entries(n).filter(([s])=>{const r=t.find(a=>a.type===e&&a.name===s);return r?r.attribute.keepOnSplit:!1}))}var Iz=(t,e=500)=>{let n="";const s=t.parentOffset;return t.parent.nodesBetween(Math.max(0,s-e),s,(r,a,l,o)=>{var c,d;const u=((d=(c=r.type.spec).toText)==null?void 0:d.call(c,{node:r,pos:a,parent:l,index:o}))||r.textContent||"%leaf%";n+=r.isAtom&&!r.isText?u:u.slice(0,Math.max(0,s-a))}),n};function cx(t,e,n={}){const{empty:s,ranges:r}=t.selection,a=e?Hr(e,t.schema):null;if(s)return!!(t.storedMarks||t.selection.$from.marks()).filter(h=>a?a.name===h.type.name:!0).find(h=>Ch(h.attrs,n,{strict:!1}));let l=0;const o=[];if(r.forEach(({$from:h,$to:m})=>{const f=h.pos,p=m.pos;t.doc.nodesBetween(f,p,(g,x)=>{if(!g.isText&&!g.marks.length)return;const y=Math.max(f,x),v=Math.min(p,x+g.nodeSize),b=v-y;l+=b,o.push(...g.marks.map(j=>({mark:j,from:y,to:v})))})}),l===0)return!1;const c=o.filter(h=>a?a.name===h.mark.type.name:!0).filter(h=>Ch(h.mark.attrs,n,{strict:!1})).reduce((h,m)=>h+m.to-m.from,0),d=o.filter(h=>a?h.mark.type!==a&&h.mark.type.excludes(a):!0).reduce((h,m)=>h+m.to-m.from,0);return(c>0?c+d:c)>=l}function Rz(t,e,n={}){if(!e)return Ki(t,null,n)||cx(t,null,n);const s=Hf(e,t.schema);return s==="node"?Ki(t,e,n):s==="mark"?cx(t,e,n):!1}var Oz=(t,e)=>{const{$from:n,$to:s,$anchor:r}=t.selection;if(e){const a=Wf(o=>o.type.name===e)(t.selection);if(!a)return!1;const l=t.doc.resolve(a.pos+1);return r.pos+1===l.end()}return!(s.parentOffset{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)};function lN(t,e){return Array.isArray(e)?e.some(n=>(typeof n=="string"?n:n.name)===t.name):e}function oN(t,e){const{nodeExtensions:n}=lo(e),s=n.find(l=>l.name===t);if(!s)return!1;const r={name:s.name,options:s.options,storage:s.storage},a=Ze(we(s,"group",r));return typeof a!="string"?!1:a.split(" ").includes("list")}function Qf(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var s;if(n){if(t.type.name==="hardBreak")return!0;if(t.isText)return/^\s*$/m.test((s=t.text)!=null?s:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(t.content.childCount===0)return!0;if(e){let r=!0;return t.content.forEach(a=>{r!==!1&&(Qf(a,{ignoreWhitespace:n,checkChildren:e})||(r=!1))}),r}return!1}function RE(t){return t instanceof ke}var OE=class LE{constructor(e){this.position=e}static fromJSON(e){return new LE(e.position)}toJSON(){return{position:this.position}}};function Fz(t,e){const n=e.mapping.mapResult(t.position);return{position:new OE(n.pos),mapResult:n}}function zz(t){return new OE(t)}function $z(t,e,n){var s;const{selection:r}=e;let a=null;if(jE(r)&&(a=r.$cursor),a){const o=(s=t.storedMarks)!=null?s:a.marks();return a.parent.type.allowsMarkType(n)&&(!!n.isInSet(o)||!o.some(d=>d.type.excludes(n)))}const{ranges:l}=r;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?t.doc.inlineContent&&t.doc.type.allowsMarkType(n):!1;return t.doc.nodesBetween(o.pos,c.pos,(u,h,m)=>{if(d)return!1;if(u.isInline){const f=!m||m.type.allowsMarkType(n),p=!!n.isInSet(u.marks)||!u.marks.some(g=>g.type.excludes(n));d=f&&p}return!d}),d})}var Bz=(t,e={})=>({tr:n,state:s,dispatch:r})=>{const{selection:a}=n,{empty:l,ranges:o}=a,c=Hr(t,s.schema);if(r)if(l){const d=SE(s,c);n.addStoredMark(c.create({...d,...e}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;s.doc.nodesBetween(u,h,(m,f)=>{const p=Math.max(f,u),g=Math.min(f+m.nodeSize,h);m.marks.find(y=>y.type===c)?m.marks.forEach(y=>{c===y.type&&n.addMark(p,g,c.create({...y.attrs,...e}))}):n.addMark(p,g,c.create(e))})});return $z(s,n,c)},_z=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),Vz=(t,e={})=>({state:n,dispatch:s,chain:r})=>{const a=Bt(t,n.schema);let l;return n.selection.$anchor.sameParent(n.selection.$head)&&(l=n.selection.$anchor.parent.attrs),a.isTextblock?r().command(({commands:o})=>jj(a,{...l,...e})(n)?!0:o.clearNodes()).command(({state:o})=>jj(a,{...l,...e})(o,s)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Kz=t=>({tr:e,dispatch:n})=>{if(n){const{doc:s}=e,r=ua(t,0,s.content.size),a=ke.create(s,r);e.setSelection(a)}return!0},Uz=(t,e)=>({tr:n,state:s,dispatch:r})=>{const{selection:a}=s;let l,o;return typeof e=="number"?(l=e,o=e):e&&"from"in e&&"to"in e?(l=e.from,o=e.to):(l=a.from,o=a.to),r&&n.doc.nodesBetween(l,o,(c,d)=>{c.isText||n.setNodeMarkup(d,void 0,{...c.attrs,dir:t})}),!0},qz=t=>({tr:e,dispatch:n})=>{if(n){const{doc:s}=e,{from:r,to:a}=typeof t=="number"?{from:t,to:t}:t,l=De.atStart(s).from,o=De.atEnd(s).to,c=ua(r,l,o),d=ua(a,l,o),u=De.create(s,c,d);e.setSelection(u)}return!0},Hz=t=>({state:e,dispatch:n})=>{const s=Bt(t,e.schema);return $L(s)(e,n)};function cN(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const s=n.filter(r=>e==null?void 0:e.includes(r.type.name));t.tr.ensureMarks(s)}}var Wz=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:s,editor:r})=>{const{selection:a,doc:l}=e,{$from:o,$to:c}=a,d=r.extensionManager.attributes,u=Mu(d,o.node().type.name,o.node().attrs);if(a instanceof ke&&a.node.isBlock)return!o.parentOffset||!Rr(l,o.pos)?!1:(s&&(t&&cN(n,r.extensionManager.splittableMarks),e.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,m=o.depth===0?void 0:jz(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&m?[{type:m,attrs:u}]:void 0,p=Rr(e.doc,e.mapping.map(o.pos),1,f);if(!f&&!p&&Rr(e.doc,e.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(p=!0,f=m?[{type:m,attrs:u}]:void 0),s){if(p&&(a instanceof De&&e.deleteSelection(),e.split(e.mapping.map(o.pos),1,f),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const g=e.mapping.map(o.before()),x=e.doc.resolve(g);o.node(-1).canReplaceWith(x.index(),x.index()+1,m)&&e.setNodeMarkup(e.mapping.map(o.before()),m)}t&&cN(n,r.extensionManager.splittableMarks),e.scrollIntoView()}return p},Qz=(t,e={})=>({tr:n,state:s,dispatch:r,editor:a})=>{var l;const o=Bt(t,s.schema),{$from:c,$to:d}=s.selection,u=s.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const m=a.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(r){let y=X.empty;const v=c.index(-1)?1:c.index(-2)?2:3;for(let w=c.depth-v;w>=c.depth-3;w-=1)y=X.from(c.node(w).copy(y));const b=c.indexAfter(-1){if(T>-1)return!1;w.isTextblock&&w.content.size===0&&(T=S+1)}),T>-1&&n.setSelection(De.near(n.doc.resolve(T))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,p={...Mu(m,h.type.name,h.attrs),...e},g={...Mu(m,c.node().type.name,c.node().attrs),...e};n.delete(c.pos,d.pos);const x=f?[{type:o,attrs:p},{type:f,attrs:g}]:[{type:o,attrs:p}];if(!Rr(n.doc,c.pos,2))return!1;if(r){const{selection:y,storedMarks:v}=s,{splittableMarks:b}=a.extensionManager,j=v||y.$to.parentOffset&&y.$from.marks();if(n.split(c.pos,2,x).scrollIntoView(),!j||!r)return!0;const k=j.filter(E=>b.includes(E.type.name));n.ensureMarks(k)}return!0},sp=(t,e)=>{const n=Wf(l=>l.type===e)(t.selection);if(!n)return!0;const s=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(s===void 0)return!0;const r=t.doc.nodeAt(s);return n.node.type===(r==null?void 0:r.type)&&Qi(t.doc,n.pos)&&t.join(n.pos),!0},rp=(t,e)=>{const n=Wf(l=>l.type===e)(t.selection);if(!n)return!0;const s=t.doc.resolve(n.start).after(n.depth);if(s===void 0)return!0;const r=t.doc.nodeAt(s);return n.node.type===(r==null?void 0:r.type)&&Qi(t.doc,s)&&t.join(s),!0},Gz=(t,e,n,s={})=>({editor:r,tr:a,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:m}=r.extensionManager,f=Bt(t,l.schema),p=Bt(e,l.schema),{selection:g,storedMarks:x}=l,{$from:y,$to:v}=g,b=y.blockRange(v),j=x||g.$to.parentOffset&&g.$from.marks();if(!b)return!1;const k=Wf(E=>oN(E.type.name,h))(g);if(b.depth>=1&&k&&b.depth-k.depth<=1){if(k.node.type===f)return d.liftListItem(p);if(oN(k.node.type.name,h)&&f.validContent(k.node.content)&&o)return c().command(()=>(a.setNodeMarkup(k.pos,f),!0)).command(()=>sp(a,f)).command(()=>rp(a,f)).run()}return!n||!j||!o?c().command(()=>u().wrapInList(f,s)?!0:d.clearNodes()).wrapInList(f,s).command(()=>sp(a,f)).command(()=>rp(a,f)).run():c().command(()=>{const E=u().wrapInList(f,s),T=j.filter(w=>m.includes(w.type.name));return a.ensureMarks(T),E?!0:d.clearNodes()}).wrapInList(f,s).command(()=>sp(a,f)).command(()=>rp(a,f)).run()},Jz=(t,e={},n={})=>({state:s,commands:r})=>{const{extendEmptyMarkRange:a=!1}=n,l=Hr(t,s.schema);return cx(s,l,e)?r.unsetMark(l,{extendEmptyMarkRange:a}):r.setMark(l,e)},Zz=(t,e,n={})=>({state:s,commands:r})=>{const a=Bt(t,s.schema),l=Bt(e,s.schema),o=Ki(s,a,n);let c;return s.selection.$anchor.sameParent(s.selection.$head)&&(c=s.selection.$anchor.parent.attrs),o?r.setNode(l,c):r.setNode(a,{...c,...n})},Yz=(t,e={})=>({state:n,commands:s})=>{const r=Bt(t,n.schema);return Ki(n,r,e)?s.lift(r):s.wrapIn(r,e)},Xz=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let s=0;s=0;c-=1)l.step(o.steps[c].invert(o.docs[c]));if(a.text){const c=l.doc.resolve(a.from).marks();l.replaceWith(a.from,a.to,t.schema.text(a.text,c))}else l.delete(a.from,a.to)}return!0}}return!1},e$=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,{empty:s,ranges:r}=n;return s||e&&r.forEach(a=>{t.removeMark(a.$from.pos,a.$to.pos)}),!0},t$=(t,e={})=>({tr:n,state:s,dispatch:r})=>{var a;const{extendEmptyMarkRange:l=!1}=e,{selection:o}=n,c=Hr(t,s.schema),{$from:d,empty:u,ranges:h}=o;if(!r)return!0;if(u&&l){let{from:m,to:f}=o;const p=(a=d.marks().find(x=>x.type===c))==null?void 0:a.attrs,g=m0(d,c,p);g&&(m=g.from,f=g.to),n.removeMark(m,f,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},n$=t=>({tr:e,state:n,dispatch:s})=>{const{selection:r}=n;let a,l;return typeof t=="number"?(a=t,l=t):t&&"from"in t&&"to"in t?(a=t.from,l=t.to):(a=r.from,l=r.to),s&&e.doc.nodesBetween(a,l,(o,c)=>{if(o.isText)return;const d={...o.attrs};delete d.dir,e.setNodeMarkup(c,void 0,d)}),!0},s$=(t,e={})=>({tr:n,state:s,dispatch:r})=>{let a=null,l=null;const o=Hf(typeof t=="string"?t:t.name,s.schema);if(!o)return!1;o==="node"&&(a=Bt(t,s.schema)),o==="mark"&&(l=Hr(t,s.schema));let c=!1;return n.selection.ranges.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;let m,f,p,g;n.selection.empty?s.doc.nodesBetween(u,h,(x,y)=>{a&&a===x.type&&(c=!0,p=Math.max(y,u),g=Math.min(y+x.nodeSize,h),m=y,f=x)}):s.doc.nodesBetween(u,h,(x,y)=>{y=u&&y<=h&&(a&&a===x.type&&(c=!0,r&&n.setNodeMarkup(y,void 0,{...x.attrs,...e})),l&&x.marks.length&&x.marks.forEach(v=>{if(l===v.type&&(c=!0,r)){const b=Math.max(y,u),j=Math.min(y+x.nodeSize,h);n.addMark(b,j,l.create({...v.attrs,...e}))}}))}),f&&(m!==void 0&&r&&n.setNodeMarkup(m,void 0,{...f.attrs,...e}),l&&f.marks.length&&f.marks.forEach(x=>{l===x.type&&r&&n.addMark(p,g,l.create({...x.attrs,...e}))}))}),c},r$=(t,e={})=>({state:n,dispatch:s})=>{const r=Bt(t,n.schema);return PL(r,e)(n,s)},i$=(t,e={})=>({state:n,dispatch:s})=>{const r=Bt(t,n.schema);return IL(r,e)(n,s)},a$=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(s=>s.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(s=>s!==e):delete this.callbacks[t]),this}once(t,e){const n=(...s)=>{this.off(t,n),e.apply(this,s)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}},Gf=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=(e=t.undoable)!=null?e:!0}},l$=(t,e)=>{if(f0(e))return e.exec(t);const n=e(t);if(!n)return null;const s=[n.text];return s.index=n.index,s.input=t,s.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),s.push(n.replaceWith)),s};function nu(t){var e;const{editor:n,from:s,to:r,text:a,rules:l,plugin:o}=t,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(s);if(d.parent.type.spec.code||(e=d.nodeBefore||d.nodeAfter)!=null&&e.marks.find(m=>m.type.spec.code))return!1;let u=!1;const h=Iz(d)+a;return l.forEach(m=>{if(u)return;const f=l$(h,m.find);if(!f)return;const p=c.state.tr,g=Uf({state:c.state,transaction:p}),x={from:s-(f[0].length-a.length),to:r},{commands:y,chain:v,can:b}=new qf({editor:n,state:g});m.handler({state:g,range:x,match:f,commands:y,chain:v,can:b})===null||!p.steps.length||(m.undoable&&p.setMeta(o,{transform:p,from:s,to:r,text:a}),c.dispatch(p),u=!0)}),u}function o$(t){const{editor:e,rules:n}=t,s=new Nt({state:{init(){return null},apply(r,a,l){const o=r.getMeta(s);if(o)return o;const c=r.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=g0(X.from(u),l.schema);const{from:h}=c,m=h+u.length;nu({editor:e,from:h,to:m,text:u,rules:n,plugin:s})}),r.selectionSet||r.docChanged?null:a}},props:{handleTextInput(r,a,l,o){return nu({editor:e,from:a,to:l,text:o,rules:n,plugin:s})},handleDOMEvents:{compositionend:r=>(setTimeout(()=>{const{$cursor:a}=r.state.selection;a&&nu({editor:e,from:a.pos,to:a.pos,text:"",rules:n,plugin:s})}),!1)},handleKeyDown(r,a){if(a.key!=="Enter")return!1;const{$cursor:l}=r.state.selection;return l?nu({editor:e,from:l.pos,to:l.pos,text:` +`,rules:n,plugin:s}):!1}},isInputRules:!0});return s}function c$(t){return Object.prototype.toString.call(t).slice(8,-1)}function su(t){return c$(t)!=="Object"?!1:t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype}function FE(t,e){const n={...t};return su(t)&&su(e)&&Object.keys(e).forEach(s=>{su(e[s])&&su(t[s])?n[s]=FE(t[s],e[s]):n[s]=e[s]}),n}var y0=class{constructor(t={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...t},this.name=this.config.name}get options(){return{...Ze(we(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...Ze(we(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>FE(this.options,t)});return e.name=this.name,e.parent=this.parent,e}extend(t={}){const e=new this.constructor({...this.config,...t});return e.parent=this,this.child=e,e.name="name"in t?t.name:e.parent.name,e}},Ja=class zE extends y0{constructor(){super(...arguments),this.type="mark"}static create(e={}){const n=typeof e=="function"?e():e;return new zE(n)}static handleExit({editor:e,mark:n}){const{tr:s}=e.state,r=e.state.selection.$from;if(r.pos===r.end()){const l=r.marks();if(!!!l.find(d=>(d==null?void 0:d.type.name)===n.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===n.name);return c&&s.removeStoredMark(c),s.insertText(" ",r.pos),e.view.dispatch(s),!0}return!1}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function d$(t){return typeof t=="number"}var u$=class{constructor(t){this.find=t.find,this.handler=t.handler}},h$=(t,e,n)=>{if(f0(e))return[...t.matchAll(e)];const s=e(t,n);return s?s.map(r=>{const a=[r.text];return a.index=r.index,a.input=t,a.data=r.data,r.replaceWith&&(r.text.includes(r.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),a.push(r.replaceWith)),a}):[]};function f$(t){const{editor:e,state:n,from:s,to:r,rule:a,pasteEvent:l,dropEvent:o}=t,{commands:c,chain:d,can:u}=new qf({editor:e,state:n}),h=[];return n.doc.nodesBetween(s,r,(f,p)=>{var g,x,y,v,b;if((x=(g=f.type)==null?void 0:g.spec)!=null&&x.code||!(f.isText||f.isTextblock||f.isInline))return;const j=(b=(v=(y=f.content)==null?void 0:y.size)!=null?v:f.nodeSize)!=null?b:0,k=Math.max(s,p),E=Math.min(r,p+j);if(k>=E)return;const T=f.isText?f.text||"":f.textBetween(k-p,E-p,void 0,"");h$(T,a.find,l).forEach(S=>{if(S.index===void 0)return;const M=k+S.index+1,F=M+S[0].length,R={from:n.tr.mapping.map(M),to:n.tr.mapping.map(F)},V=a.handler({state:n,range:R,match:S,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(V)})}),h.every(f=>f!==null)}var ru=null,m$=t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=n.clipboardData)==null||e.setData("text/html",t),n};function p$(t){const{editor:e,rules:n}=t;let s=null,r=!1,a=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:m,rule:f,pasteEvt:p})=>{const g=u.tr,x=Uf({state:u,transaction:g});if(!(!f$({editor:e,state:x,from:Math.max(h-1,0),to:m.b-1,rule:f,pasteEvent:p,dropEvent:o})||!g.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,g}};return n.map(u=>new Nt({view(h){const m=p=>{var g;s=(g=h.dom.parentElement)!=null&&g.contains(p.target)?h.dom.parentElement:null,s&&(ru=e)},f=()=>{ru&&(ru=null)};return window.addEventListener("dragstart",m),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",m),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(h,m)=>{if(a=s===h.dom.parentElement,o=m,!a){const f=ru;f!=null&&f.isEditable&&setTimeout(()=>{const p=f.state.selection;p&&f.commands.deleteRange({from:p.from,to:p.to})},10)}return!1},paste:(h,m)=>{var f;const p=(f=m.clipboardData)==null?void 0:f.getData("text/html");return l=m,r=!!(p!=null&&p.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,f)=>{const p=h[0],g=p.getMeta("uiEvent")==="paste"&&!r,x=p.getMeta("uiEvent")==="drop"&&!a,y=p.getMeta("applyPasteRules"),v=!!y;if(!g&&!x&&!v)return;if(v){let{text:k}=y;typeof k=="string"?k=k:k=g0(X.from(k),f.schema);const{from:E}=y,T=E+k.length,w=m$(k);return c({rule:u,state:f,from:E,to:{b:T},pasteEvt:w})}const b=m.doc.content.findDiffStart(f.doc.content),j=m.doc.content.findDiffEnd(f.doc.content);if(!(!d$(b)||!j||b===j.b))return c({rule:u,state:f,from:b,to:j,pasteEvt:l})}}))}var Jf=class{constructor(t,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=DE(t),this.schema=Cz(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((t,e)=>{const n={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:tu(e.name,this.schema)},s=we(e,"addCommands",n);return s?{...t,...s()}:t},{})}get plugins(){const{editor:t}=this;return Ah([...this.extensions].reverse()).flatMap(s=>{const r={name:s.name,options:s.options,storage:this.editor.extensionStorage[s.name],editor:t,type:tu(s.name,this.schema)},a=[],l=we(s,"addKeyboardShortcuts",r);let o={};if(s.type==="mark"&&we(s,"exitable",r)&&(o.ArrowRight=()=>Ja.handleExit({editor:t,mark:s})),l){const m=Object.fromEntries(Object.entries(l()).map(([f,p])=>[f,()=>p({editor:t})]));o={...o,...m}}const c=D6(o);a.push(c);const d=we(s,"addInputRules",r);if(lN(s,t.options.enableInputRules)&&d){const m=d();if(m&&m.length){const f=o$({editor:t,rules:m}),p=Array.isArray(f)?f:[f];a.push(...p)}}const u=we(s,"addPasteRules",r);if(lN(s,t.options.enablePasteRules)&&u){const m=u();if(m&&m.length){const f=p$({editor:t,rules:m});a.push(...f)}}const h=we(s,"addProseMirrorPlugins",r);if(h){const m=h();a.push(...m)}return a})}get attributes(){return AE(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=lo(this.extensions);return Object.fromEntries(e.filter(n=>!!we(n,"addNodeView")).map(n=>{const s=this.attributes.filter(c=>c.type===n.name),r={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:Bt(n.name,this.schema)},a=we(n,"addNodeView",r);if(!a)return[];const l=a();if(!l)return[];const o=(c,d,u,h,m)=>{const f=Zc(c,s);return l({node:c,view:d,getPos:u,decorations:h,innerDecorations:m,editor:t,extension:n,HTMLAttributes:f})};return[n.name,o]}))}dispatchTransaction(t){const{editor:e}=this;return Ah([...this.extensions].reverse()).reduceRight((s,r)=>{const a={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:tu(r.name,this.schema)},l=we(r,"dispatchTransaction",a);return l?o=>{l.call(a,{transaction:o,next:s})}:s},t)}get markViews(){const{editor:t}=this,{markExtensions:e}=lo(this.extensions);return Object.fromEntries(e.filter(n=>!!we(n,"addMarkView")).map(n=>{const s=this.attributes.filter(o=>o.type===n.name),r={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:t,type:Hr(n.name,this.schema)},a=we(n,"addMarkView",r);if(!a)return[];const l=(o,c,d)=>{const u=Zc(o,s);return a()({mark:o,view:c,inline:d,editor:t,extension:n,HTMLAttributes:u,updateAttributes:h=>{D$(o,t,h)}})};return[n.name,l]}))}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(e=>[e.name,e.storage])),t.forEach(e=>{var n;const s={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:tu(e.name,this.schema)};e.type==="mark"&&((n=Ze(we(e,"keepOnSplit",s)))==null||n)&&this.splittableMarks.push(e.name);const r=we(e,"onBeforeCreate",s),a=we(e,"onCreate",s),l=we(e,"onUpdate",s),o=we(e,"onSelectionUpdate",s),c=we(e,"onTransaction",s),d=we(e,"onFocus",s),u=we(e,"onBlur",s),h=we(e,"onDestroy",s);r&&this.editor.on("beforeCreate",r),a&&this.editor.on("create",a),l&&this.editor.on("update",l),o&&this.editor.on("selectionUpdate",o),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),u&&this.editor.on("blur",u),h&&this.editor.on("destroy",h)})}};Jf.resolve=DE;Jf.sort=Ah;Jf.flatten=p0;var g$={};h0(g$,{ClipboardTextSerializer:()=>BE,Commands:()=>_E,Delete:()=>VE,Drop:()=>KE,Editable:()=>UE,FocusEvents:()=>HE,Keymap:()=>WE,Paste:()=>QE,Tabindex:()=>GE,TextDirection:()=>JE,focusEventsPluginKey:()=>qE});var It=class $E extends y0{constructor(){super(...arguments),this.type="extension"}static create(e={}){const n=typeof e=="function"?e():e;return new $E(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}},BE=It.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Nt({key:new Ht("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:s,selection:r}=e,{ranges:a}=r,l=Math.min(...a.map(u=>u.$from.pos)),o=Math.max(...a.map(u=>u.$to.pos)),c=TE(n);return ME(s,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),_E=It.create({name:"commands",addCommands(){return{...vE}}}),VE=It.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,s,r;const a=()=>{var l,o,c,d;if((d=(c=(o=(l=this.editor.options.coreExtensionOptions)==null?void 0:l.delete)==null?void 0:o.filterTransaction)==null?void 0:c.call(o,t))!=null?d:t.getMeta("y-sync$"))return;const u=CE(t.before,[t,...e]);IE(u).forEach(f=>{u.mapping.mapResult(f.oldRange.from).deletedAfter&&u.mapping.mapResult(f.oldRange.to).deletedBefore&&u.before.nodesBetween(f.oldRange.from,f.oldRange.to,(p,g)=>{const x=g+p.nodeSize-2,y=f.oldRange.from<=g&&x<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:p,from:g,to:x,newFrom:u.mapping.map(g),newTo:u.mapping.map(x),deletedRange:f.oldRange,newRange:f.newRange,partial:!y,editor:this.editor,transaction:t,combinedTransform:u})})});const m=u.mapping;u.steps.forEach((f,p)=>{var g,x;if(f instanceof zs){const y=m.slice(p).map(f.from,-1),v=m.slice(p).map(f.to),b=m.invert().map(y,-1),j=m.invert().map(v),k=(g=u.doc.nodeAt(y-1))==null?void 0:g.marks.some(T=>T.eq(f.mark)),E=(x=u.doc.nodeAt(v))==null?void 0:x.marks.some(T=>T.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:b,to:j},newRange:{from:y,to:v},partial:!!(E||k),editor:this.editor,transaction:t,combinedTransform:u})}})};(r=(s=(n=this.editor.options.coreExtensionOptions)==null?void 0:n.delete)==null?void 0:s.async)==null||r?setTimeout(a,0):a()}}),KE=It.create({name:"drop",addProseMirrorPlugins(){return[new Nt({key:new Ht("tiptapDrop"),props:{handleDrop:(t,e,n,s)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:s})}}})]}}),UE=It.create({name:"editable",addProseMirrorPlugins(){return[new Nt({key:new Ht("editable"),props:{editable:()=>this.editor.options.editable}})]}}),qE=new Ht("focusEvents"),HE=It.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new Nt({key:qE,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const s=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(s),!1},blur:(e,n)=>{t.isFocused=!1;const s=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(s),!1}}}})]}}),WE=It.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:m,parent:f}=h,p=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,g=p.parent.type.spec.isolating,x=h.pos-h.parentOffset,y=g&&p.parent.childCount===1?x===h.pos:Ie.atStart(d).from===m;return!u||!f.type.isTextblock||f.textContent.length||!y||y&&h.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),s={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},r={...s},a={...s,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Eh()||kE()?a:r},addProseMirrorPlugins(){return[new Nt({key:new Ht("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(g=>g.getMeta("composition")))return;const s=t.some(g=>g.docChanged)&&!e.doc.eq(n.doc),r=t.some(g=>g.getMeta("preventClearDocument"));if(!s||r)return;const{empty:a,from:l,to:o}=e.selection,c=Ie.atStart(e.doc).from,d=Ie.atEnd(e.doc).to;if(a||!(l===c&&o===d)||!Qf(n.doc))return;const m=n.tr,f=Uf({state:n,transaction:m}),{commands:p}=new qf({editor:this.editor,state:f});if(p.clearNodes(),!!m.steps.length)return m}})]}}),QE=It.create({name:"paste",addProseMirrorPlugins(){return[new Nt({key:new Ht("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),GE=It.create({name:"tabindex",addProseMirrorPlugins(){return[new Nt({key:new Ht("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),JE=It.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=lo(this.extensions);return[{types:t.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const n=e.getAttribute("dir");return n&&(n==="ltr"||n==="rtl"||n==="auto")?n:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new Nt({key:new Ht("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),x$=class Ho{constructor(e,n,s=!1,r=null){this.currentNode=null,this.actualDepth=null,this.isBlock=s,this.resolvedPos=e,this.editor=n,this.currentNode=r}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let n=this.from,s=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,s=this.to-1}this.editor.commands.insertContentAt({from:n,to:s},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(e);return new Ho(n,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new Ho(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new Ho(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,s)=>{const r=n.isBlock&&!n.isTextblock,a=n.isAtom&&!n.isText,l=n.isInline,o=this.pos+s+(a?0:1);if(o<0||o>this.resolvedPos.doc.nodeSize-2)return;const c=this.resolvedPos.doc.resolve(o);if(!r&&!l&&c.depth<=this.depth)return;const d=new Ho(c,this.editor,r,r||l?n:null);r&&(d.actualDepth=this.depth+1),e.push(d)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,n={}){let s=null,r=this.parent;for(;r&&!s;){if(r.node.type.name===e)if(Object.keys(n).length>0){const a=r.node.attrs,l=Object.keys(n);for(let o=0;o{s&&r.length>0||(l.node.type.name===e&&a.every(c=>n[c]===l.node.attrs[c])&&r.push(l),!(s&&r.length>0)&&(r=r.concat(l.querySelectorAll(e,n,s))))}),r}setAttribute(e){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(n)}},y$=`.ProseMirror { + position: relative; +} + +.ProseMirror { + word-wrap: break-word; + white-space: pre-wrap; + white-space: break-spaces; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ +} + +.ProseMirror [contenteditable="false"] { + white-space: normal; +} + +.ProseMirror [contenteditable="false"] [contenteditable="true"] { + white-space: pre-wrap; +} + +.ProseMirror pre { + white-space: pre-wrap; +} + +img.ProseMirror-separator { + display: inline !important; + border: none !important; + margin: 0 !important; + width: 0 !important; + height: 0 !important; +} + +.ProseMirror-gapcursor { + display: none; + pointer-events: none; + position: absolute; + margin: 0; +} + +.ProseMirror-gapcursor:after { + content: ""; + display: block; + position: absolute; + top: -2px; + width: 20px; + border-top: 1px solid black; + animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; +} + +@keyframes ProseMirror-cursor-blink { + to { + visibility: hidden; + } +} + +.ProseMirror-hideselection *::selection { + background: transparent; +} + +.ProseMirror-hideselection *::-moz-selection { + background: transparent; +} + +.ProseMirror-hideselection * { + caret-color: transparent; +} + +.ProseMirror-focused .ProseMirror-gapcursor { + display: block; +}`;function v$(t,e,n){const s=document.querySelector("style[data-tiptap-style]");if(s!==null)return s;const r=document.createElement("style");return e&&r.setAttribute("nonce",e),r.setAttribute("data-tiptap-style",""),r.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(r),r}var b$=class extends a${constructor(t={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:s})=>{throw s},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:Fz,createMappablePosition:zz},this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:s,slice:r,moved:a})=>this.options.onDrop(s,r,a)),this.on("paste",({event:s,slice:r})=>this.options.onPaste(s,r)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=NE(e,this.options.autofocus);this.editorState=jl.create({doc:e,schema:this.schema,selection:n||void 0}),this.options.element&&this.mount(this.options.element)}mount(t){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(t),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const t=this.editorView.dom;t!=null&&t.editor&&delete t.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(t){console.warn("Failed to remove CSS element:",t)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=v$(y$,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,e=!0){this.setOptions({editable:t}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:t=>{this.editorState=t},dispatch:t=>{this.dispatchTransaction(t)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(t,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in t)return Reflect.get(t,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(t,e){const n=EE(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],s=this.state.reconfigure({plugins:n});return this.view.updateState(s),s}unregisterPlugin(t){if(this.isDestroyed)return;const e=this.state.plugins;let n=e;if([].concat(t).forEach(r=>{const a=typeof r=="string"?`${r}$`:r.key;n=n.filter(l=>!l.key.startsWith(a))}),e.length===n.length)return;const s=this.state.reconfigure({plugins:n});return this.view.updateState(s),s}createExtensionManager(){var t,e;const s=[...this.options.enableCoreExtensions?[UE,BE.configure({blockSeparator:(e=(t=this.options.coreExtensionOptions)==null?void 0:t.clipboardTextSerializer)==null?void 0:e.blockSeparator}),_E,HE,WE,GE,KE,QE,VE,JE.configure({direction:this.options.textDirection})].filter(r=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[r.name]!==!1:!0):[],...this.options.extensions].filter(r=>["extension","node","mark"].includes(r==null?void 0:r.type));this.extensionManager=new Jf(s,this)}createCommandManager(){this.commandManager=new qf({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=ox(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(n=>n.name!=="collaboration"),this.createExtensionManager()}}),t=ox(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){const{editorProps:e,enableExtensionDispatchTransaction:n}=this.options,s=e.dispatchTransaction||this.dispatchTransaction.bind(this),r=n?this.extensionManager.dispatchTransaction(s):s;this.editorView=new xE(t,{...e,attributes:{role:"textbox",...e==null?void 0:e.attributes},dispatchTransaction:r,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const a=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(a),this.prependClass(),this.injectCSS();const l=this.view.dom;l.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(d=>{var u;return(u=this.capturedTransaction)==null?void 0:u.step(d)});return}const{state:e,transactions:n}=this.state.applyTransaction(t),s=!this.state.selection.eq(e.selection),r=n.includes(t),a=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!r)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:t,appendedTransactions:n.slice(1)}),s&&this.emit("selectionUpdate",{editor:this,transaction:t});const l=n.findLast(d=>d.getMeta("focus")||d.getMeta("blur")),o=l==null?void 0:l.getMeta("focus"),c=l==null?void 0:l.getMeta("blur");o&&this.emit("focus",{editor:this,event:o.event,transaction:l}),c&&this.emit("blur",{editor:this,event:c.event,transaction:l}),!(t.getMeta("preventUpdate")||!n.some(d=>d.docChanged)||a.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return PE(this.state,t)}isActive(t,e){const n=typeof t=="string"?t:null,s=typeof t=="string"?e:t;return Rz(this.state,n,s)}getJSON(){return this.state.doc.toJSON()}getHTML(){return g0(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e=` + +`,textSerializers:n={}}=t||{};return Az(this.state.doc,{blockSeparator:e,textSerializers:{...TE(this.schema),...n}})}get isEmpty(){return Qf(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var t,e;return(e=(t=this.editorView)==null?void 0:t.isDestroyed)!=null?e:!0}$node(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelector(t,e))||null}$nodes(t,e){var n;return((n=this.$doc)==null?void 0:n.querySelectorAll(t,e))||null}$pos(t){const e=this.state.doc.resolve(t);return new x$(e,this)}get $doc(){return this.$pos(0)}};function oo(t){return new Gf({find:t.find,handler:({state:e,range:n,match:s})=>{const r=Ze(t.getAttributes,void 0,s);if(r===!1||r===null)return null;const{tr:a}=e,l=s[s.length-1],o=s[0];if(l){const c=o.search(/\S/),d=n.from+o.indexOf(l),u=d+l.length;if(x0(n.from,n.to,e.doc).filter(f=>f.mark.type.excluded.find(g=>g===t.type&&g!==f.mark.type)).filter(f=>f.to>d).length)return null;un.from&&a.delete(n.from+c,d);const m=n.from+c+l.length;a.addMark(n.from+c,m,t.type.create(r||{})),a.removeStoredMark(t.type)}},undoable:t.undoable})}function j$(t){return new Gf({find:t.find,handler:({state:e,range:n,match:s})=>{const r=Ze(t.getAttributes,void 0,s)||{},{tr:a}=e,l=n.from;let o=n.to;const c=t.type.create(r);if(s[1]){const d=s[0].lastIndexOf(s[1]);let u=l+d;u>o?u=o:o=u+s[1].length;const h=s[0][s[0].length-1];a.insertText(h,l+s[0].length-1),a.replaceWith(u,o,c)}else if(s[0]){const d=t.type.isInline?l:l-1;a.insert(d,t.type.create(r)).delete(a.mapping.map(l),a.mapping.map(o))}a.scrollIntoView()},undoable:t.undoable})}function dx(t){return new Gf({find:t.find,handler:({state:e,range:n,match:s})=>{const r=e.doc.resolve(n.from),a=Ze(t.getAttributes,void 0,s)||{};if(!r.node(-1).canReplaceWith(r.index(-1),r.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,a)},undoable:t.undoable})}function co(t){return new Gf({find:t.find,handler:({state:e,range:n,match:s,chain:r})=>{const a=Ze(t.getAttributes,void 0,s)||{},l=e.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&Jy(c,t.type,a);if(!d)return null;if(l.wrap(c,d),t.keepMarks&&t.editor){const{selection:h,storedMarks:m}=e,{splittableMarks:f}=t.editor.extensionManager,p=m||h.$to.parentOffset&&h.$from.marks();if(p){const g=p.filter(x=>f.includes(x.type.name));l.ensureMarks(g)}}if(t.keepAttributes){const h=t.type.name==="bulletList"||t.type.name==="orderedList"?"listItem":"taskList";r().updateAttributes(h,a).run()}const u=l.doc.resolve(n.from-1).nodeBefore;u&&u.type===t.type&&Qi(l.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(s,u))&&l.join(n.from-1)},undoable:t.undoable})}function N$(t,e){const{selection:n}=t,{$from:s}=n;if(n instanceof ke){const a=s.index();return s.parent.canReplaceWith(a,a+1,e)}let r=s.depth;for(;r>=0;){const a=s.index(r);if(s.node(r).contentMatchAt(a).matchType(e))return!0;r-=1}return!1}var w$={};h0(w$,{createAtomBlockMarkdownSpec:()=>k$,createBlockMarkdownSpec:()=>S$,createInlineMarkdownSpec:()=>A$,parseAttributes:()=>v0,parseIndentedBlocks:()=>ux,renderNestedMarkdownContent:()=>j0,serializeAttributes:()=>b0});function v0(t){if(!(t!=null&&t.trim()))return{};const e={},n=[],s=t.replace(/["']([^"']*)["']/g,d=>(n.push(d),`__QUOTED_${n.length-1}__`)),r=s.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(r){const d=r.map(u=>u.trim().slice(1));e.class=d.join(" ")}const a=s.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);a&&(e.id=a[1]);const l=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(s.matchAll(l)).forEach(([,d,u])=>{var h;const m=parseInt(((h=u.match(/__QUOTED_(\d+)__/))==null?void 0:h[1])||"0",10),f=n[m];f&&(e[d]=f.slice(1,-1))});const c=s.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return c&&c.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function b0(t){if(!t||Object.keys(t).length===0)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(s=>e.push(`.${s}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([n,s])=>{n==="class"||n==="id"||(s===!0?e.push(n):s!==!1&&s!=null&&e.push(`${n}="${String(s)}"`))}),e.join(" ")}function k$(t){const{nodeName:e,name:n,parseAttributes:s=v0,serializeAttributes:r=b0,defaultAttributes:a={},requiredAttributes:l=[],allowedAttributes:o}=t,c=n||e,d=u=>{if(!o)return u;const h={};return o.forEach(m=>{m in u&&(h[m]=u[m])}),h};return{parseMarkdown:(u,h)=>{const m={...a,...u.attributes};return h.createNode(e,m,[])},markdownTokenizer:{name:e,level:"block",start(u){var h;const m=new RegExp(`^:::${c}(?:\\s|$)`,"m"),f=(h=u.match(m))==null?void 0:h.index;return f!==void 0?f:-1},tokenize(u,h,m){const f=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),p=u.match(f);if(!p)return;const g=p[1]||"",x=s(g);if(!l.find(v=>!(v in x)))return{type:e,raw:p[0],attributes:x}}},renderMarkdown:u=>{const h=d(u.attrs||{}),m=r(h),f=m?` {${m}}`:"";return`:::${c}${f} :::`}}}function S$(t){const{nodeName:e,name:n,getContent:s,parseAttributes:r=v0,serializeAttributes:a=b0,defaultAttributes:l={},content:o="block",allowedAttributes:c}=t,d=n||e,u=h=>{if(!c)return h;const m={};return c.forEach(f=>{f in h&&(m[f]=h[f])}),m};return{parseMarkdown:(h,m)=>{let f;if(s){const g=s(h);f=typeof g=="string"?[{type:"text",text:g}]:g}else o==="block"?f=m.parseChildren(h.tokens||[]):f=m.parseInline(h.tokens||[]);const p={...l,...h.attributes};return m.createNode(e,p,f)},markdownTokenizer:{name:e,level:"block",start(h){var m;const f=new RegExp(`^:::${d}`,"m"),p=(m=h.match(f))==null?void 0:m.index;return p!==void 0?p:-1},tokenize(h,m,f){var p;const g=new RegExp(`^:::${d}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),x=h.match(g);if(!x)return;const[y,v=""]=x,b=r(v);let j=1;const k=y.length;let E="";const T=/^:::([\w-]*)(\s.*)?/gm,w=h.slice(k);for(T.lastIndex=0;;){const S=T.exec(w);if(S===null)break;const M=S.index,F=S[1];if(!((p=S[2])!=null&&p.endsWith(":::"))){if(F)j+=1;else if(j-=1,j===0){const R=w.slice(0,M);E=R.trim();const V=h.slice(0,k+M+S[0].length);let D=[];if(E)if(o==="block")for(D=f.blockTokens(R),D.forEach(z=>{z.text&&(!z.tokens||z.tokens.length===0)&&(z.tokens=f.inlineTokens(z.text))});D.length>0;){const z=D[D.length-1];if(z.type==="paragraph"&&(!z.text||z.text.trim()===""))D.pop();else break}else D=f.inlineTokens(E);return{type:e,raw:V,attributes:b,content:E,tokens:D}}}}}},renderMarkdown:(h,m)=>{const f=u(h.attrs||{}),p=a(f),g=p?` {${p}}`:"",x=m.renderChildren(h.content||[],` + +`);return`:::${d}${g} + +${x} + +:::`}}}function C$(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let s=n.exec(t);for(;s!==null;){const[,r,a,l]=s;e[r]=a||l,s=n.exec(t)}return e}function E$(t){return Object.entries(t).filter(([,e])=>e!=null).map(([e,n])=>`${e}="${n}"`).join(" ")}function A$(t){const{nodeName:e,name:n,getContent:s,parseAttributes:r=C$,serializeAttributes:a=E$,defaultAttributes:l={},selfClosing:o=!1,allowedAttributes:c}=t,d=n||e,u=m=>{if(!c)return m;const f={};return c.forEach(p=>{const g=typeof p=="string"?p:p.name,x=typeof p=="string"?void 0:p.skipIfDefault;if(g in m){const y=m[g];if(x!==void 0&&y===x)return;f[g]=y}}),f},h=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(m,f)=>{const p={...l,...m.attributes};if(o)return f.createNode(e,p);const g=s?s(m):m.content||"";return g?f.createNode(e,p,[f.createTextNode(g)]):f.createNode(e,p,[])},markdownTokenizer:{name:e,level:"inline",start(m){const f=o?new RegExp(`\\[${h}\\s*[^\\]]*\\]`):new RegExp(`\\[${h}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${h}\\]`),p=m.match(f),g=p==null?void 0:p.index;return g!==void 0?g:-1},tokenize(m,f,p){const g=o?new RegExp(`^\\[${h}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${h}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${h}\\]`),x=m.match(g);if(!x)return;let y="",v="";if(o){const[,j]=x;v=j}else{const[,j,k]=x;v=j,y=k||""}const b=r(v.trim());return{type:e,raw:x[0],content:y.trim(),attributes:b}}},renderMarkdown:m=>{let f="";s?f=s(m):m.content&&m.content.length>0&&(f=m.content.filter(y=>y.type==="text").map(y=>y.text).join(""));const p=u(m.attrs||{}),g=a(p),x=g?` ${g}`:"";return o?`[${d}${x}]`:`[${d}${x}]${f}[/${d}]`}}}function ux(t,e,n){var s,r,a,l;const o=t.split(` +`),c=[];let d="",u=0;const h=e.baseIndentSize||2;for(;u0)break;if(m.trim()===""){u+=1,d=`${d}${m} +`;continue}else return}const p=e.extractItemData(f),{indentLevel:g,mainContent:x}=p;d=`${d}${m} +`;const y=[x];for(u+=1;uM.trim()!=="");if(T===-1)break;if((((r=(s=o[u+1+T].match(/^(\s*)/))==null?void 0:s[1])==null?void 0:r.length)||0)>g){y.push(k),d=`${d}${k} +`,u+=1;continue}else break}if((((l=(a=k.match(/^(\s*)/))==null?void 0:a[1])==null?void 0:l.length)||0)>g)y.push(k),d=`${d}${k} +`,u+=1;else break}let v;const b=y.slice(1);if(b.length>0){const k=b.map(E=>E.slice(g+h)).join(` +`);k.trim()&&(e.customNestedParser?v=e.customNestedParser(k):v=n.blockTokens(k))}const j=e.createToken(p,v);c.push(j)}if(c.length!==0)return{items:c,raw:d}}function j0(t,e,n,s){if(!t||!Array.isArray(t.content))return"";const r=typeof n=="function"?n(s):n,[a,...l]=t.content,o=e.renderChildren([a]),c=[`${r}${o}`];return l&&l.length>0&&l.forEach(d=>{const u=e.renderChildren([d]);if(u){const h=u.split(` +`).map(m=>m?e.indent(m):"").join(` +`);c.push(h)}}),c.join(` +`)}function D$(t,e,n={}){const{state:s}=e,{doc:r,tr:a}=s,l=t;r.descendants((o,c)=>{const d=a.mapping.map(c),u=a.mapping.map(c)+o.nodeSize;let h=null;if(o.marks.forEach(f=>{if(f!==l)return!1;h=f}),!h)return;let m=!1;if(Object.keys(n).forEach(f=>{n[f]!==h.attrs[f]&&(m=!0)}),m){const f=t.type.create({...t.attrs,...n});a.removeMark(d,u,t.type),a.addMark(d,u,f)}}),a.docChanged&&e.view.dispatch(a)}var hs=class ZE extends y0{constructor(){super(...arguments),this.type="node"}static create(e={}){const n=typeof e=="function"?e():e;return new ZE(n)}configure(e){return super.configure(e)}extend(e){const n=typeof e=="function"?e():e;return super.extend(n)}};function qa(t){return new u$({find:t.find,handler:({state:e,range:n,match:s,pasteEvent:r})=>{const a=Ze(t.getAttributes,void 0,s,r);if(a===!1||a===null)return null;const{tr:l}=e,o=s[s.length-1],c=s[0];let d=n.to;if(o){const u=c.search(/\S/),h=n.from+c.indexOf(o),m=h+o.length;if(x0(n.from,n.to,e.doc).filter(p=>p.mark.type.excluded.find(x=>x===t.type&&x!==p.mark.type)).filter(p=>p.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,t.type.create(a||{})),l.removeStoredMark(t.type)}}})}const{getOwnPropertyNames:M$,getOwnPropertySymbols:T$}=Object,{hasOwnProperty:P$}=Object.prototype;function ip(t,e){return function(s,r,a){return t(s,r,a)&&e(s,r,a)}}function iu(t){return function(n,s,r){if(!n||!s||typeof n!="object"||typeof s!="object")return t(n,s,r);const{cache:a}=r,l=a.get(n),o=a.get(s);if(l&&o)return l===s&&o===n;a.set(n,s),a.set(s,n);const c=t(n,s,r);return a.delete(n),a.delete(s),c}}function I$(t){return t!=null?t[Symbol.toStringTag]:void 0}function dN(t){return M$(t).concat(T$(t))}const R$=Object.hasOwn||((t,e)=>P$.call(t,e));function Za(t,e){return t===e||!t&&!e&&t!==t&&e!==e}const O$="__v",L$="__o",F$="_owner",{getOwnPropertyDescriptor:uN,keys:hN}=Object;function z$(t,e){return t.byteLength===e.byteLength&&Dh(new Uint8Array(t),new Uint8Array(e))}function $$(t,e,n){let s=t.length;if(e.length!==s)return!1;for(;s-- >0;)if(!n.equals(t[s],e[s],s,s,t,e,n))return!1;return!0}function B$(t,e){return t.byteLength===e.byteLength&&Dh(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function _$(t,e){return Za(t.getTime(),e.getTime())}function V$(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function K$(t,e){return t===e}function fN(t,e,n){const s=t.size;if(s!==e.size)return!1;if(!s)return!0;const r=new Array(s),a=t.entries();let l,o,c=0;for(;(l=a.next())&&!l.done;){const d=e.entries();let u=!1,h=0;for(;(o=d.next())&&!o.done;){if(r[h]){h++;continue}const m=l.value,f=o.value;if(n.equals(m[0],f[0],c,h,t,e,n)&&n.equals(m[1],f[1],m[0],f[0],t,e,n)){u=r[h]=!0;break}h++}if(!u)return!1;c++}return!0}const U$=Za;function q$(t,e,n){const s=hN(t);let r=s.length;if(hN(e).length!==r)return!1;for(;r-- >0;)if(!YE(t,e,n,s[r]))return!1;return!0}function Oo(t,e,n){const s=dN(t);let r=s.length;if(dN(e).length!==r)return!1;let a,l,o;for(;r-- >0;)if(a=s[r],!YE(t,e,n,a)||(l=uN(t,a),o=uN(e,a),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function H$(t,e){return Za(t.valueOf(),e.valueOf())}function W$(t,e){return t.source===e.source&&t.flags===e.flags}function mN(t,e,n){const s=t.size;if(s!==e.size)return!1;if(!s)return!0;const r=new Array(s),a=t.values();let l,o;for(;(l=a.next())&&!l.done;){const c=e.values();let d=!1,u=0;for(;(o=c.next())&&!o.done;){if(!r[u]&&n.equals(l.value,o.value,l.value,o.value,t,e,n)){d=r[u]=!0;break}u++}if(!d)return!1}return!0}function Dh(t,e){let n=t.byteLength;if(e.byteLength!==n||t.byteOffset!==e.byteOffset)return!1;for(;n-- >0;)if(t[n]!==e[n])return!1;return!0}function Q$(t,e){return t.hostname===e.hostname&&t.pathname===e.pathname&&t.protocol===e.protocol&&t.port===e.port&&t.hash===e.hash&&t.username===e.username&&t.password===e.password}function YE(t,e,n,s){return(s===F$||s===L$||s===O$)&&(t.$$typeof||e.$$typeof)?!0:R$(e,s)&&n.equals(t[s],e[s],s,s,t,e,n)}const G$="[object ArrayBuffer]",J$="[object Arguments]",Z$="[object Boolean]",Y$="[object DataView]",X$="[object Date]",eB="[object Error]",tB="[object Map]",nB="[object Number]",sB="[object Object]",rB="[object RegExp]",iB="[object Set]",aB="[object String]",lB={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},oB="[object URL]",cB=Object.prototype.toString;function dB({areArrayBuffersEqual:t,areArraysEqual:e,areDataViewsEqual:n,areDatesEqual:s,areErrorsEqual:r,areFunctionsEqual:a,areMapsEqual:l,areNumbersEqual:o,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:u,areSetsEqual:h,areTypedArraysEqual:m,areUrlsEqual:f,unknownTagComparators:p}){return function(x,y,v){if(x===y)return!0;if(x==null||y==null)return!1;const b=typeof x;if(b!==typeof y)return!1;if(b!=="object")return b==="number"?o(x,y,v):b==="function"?a(x,y,v):!1;const j=x.constructor;if(j!==y.constructor)return!1;if(j===Object)return c(x,y,v);if(Array.isArray(x))return e(x,y,v);if(j===Date)return s(x,y,v);if(j===RegExp)return u(x,y,v);if(j===Map)return l(x,y,v);if(j===Set)return h(x,y,v);const k=cB.call(x);if(k===X$)return s(x,y,v);if(k===rB)return u(x,y,v);if(k===tB)return l(x,y,v);if(k===iB)return h(x,y,v);if(k===sB)return typeof x.then!="function"&&typeof y.then!="function"&&c(x,y,v);if(k===oB)return f(x,y,v);if(k===eB)return r(x,y,v);if(k===J$)return c(x,y,v);if(lB[k])return m(x,y,v);if(k===G$)return t(x,y,v);if(k===Y$)return n(x,y,v);if(k===Z$||k===nB||k===aB)return d(x,y,v);if(p){let E=p[k];if(!E){const T=I$(x);T&&(E=p[T])}if(E)return E(x,y,v)}return!1}}function uB({circular:t,createCustomConfig:e,strict:n}){let s={areArrayBuffersEqual:z$,areArraysEqual:n?Oo:$$,areDataViewsEqual:B$,areDatesEqual:_$,areErrorsEqual:V$,areFunctionsEqual:K$,areMapsEqual:n?ip(fN,Oo):fN,areNumbersEqual:U$,areObjectsEqual:n?Oo:q$,arePrimitiveWrappersEqual:H$,areRegExpsEqual:W$,areSetsEqual:n?ip(mN,Oo):mN,areTypedArraysEqual:n?ip(Dh,Oo):Dh,areUrlsEqual:Q$,unknownTagComparators:void 0};if(e&&(s=Object.assign({},s,e(s))),t){const r=iu(s.areArraysEqual),a=iu(s.areMapsEqual),l=iu(s.areObjectsEqual),o=iu(s.areSetsEqual);s=Object.assign({},s,{areArraysEqual:r,areMapsEqual:a,areObjectsEqual:l,areSetsEqual:o})}return s}function hB(t){return function(e,n,s,r,a,l,o){return t(e,n,o)}}function fB({circular:t,comparator:e,createState:n,equals:s,strict:r}){if(n)return function(o,c){const{cache:d=t?new WeakMap:void 0,meta:u}=n();return e(o,c,{cache:d,equals:s,meta:u,strict:r})};if(t)return function(o,c){return e(o,c,{cache:new WeakMap,equals:s,meta:void 0,strict:r})};const a={cache:void 0,equals:s,meta:void 0,strict:r};return function(o,c){return e(o,c,a)}}const mB=Ji();Ji({strict:!0});Ji({circular:!0});Ji({circular:!0,strict:!0});Ji({createInternalComparator:()=>Za});Ji({strict:!0,createInternalComparator:()=>Za});Ji({circular:!0,createInternalComparator:()=>Za});Ji({circular:!0,createInternalComparator:()=>Za,strict:!0});function Ji(t={}){const{circular:e=!1,createInternalComparator:n,createState:s,strict:r=!1}=t,a=uB(t),l=dB(a),o=n?n(l):hB(l);return fB({circular:e,comparator:l,createState:s,equals:o,strict:r})}var XE={exports:{}},e4={};/** + * @license React + * use-sync-external-store-shim/with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Zf=N,pB=Wy;function gB(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var xB=typeof Object.is=="function"?Object.is:gB,yB=pB.useSyncExternalStore,vB=Zf.useRef,bB=Zf.useEffect,jB=Zf.useMemo,NB=Zf.useDebugValue;e4.useSyncExternalStoreWithSelector=function(t,e,n,s,r){var a=vB(null);if(a.current===null){var l={hasValue:!1,value:null};a.current=l}else l=a.current;a=jB(function(){function c(f){if(!d){if(d=!0,u=f,f=s(f),r!==void 0&&l.hasValue){var p=l.value;if(r(p,f))return h=p}return h=f}if(p=h,xB(u,f))return p;var g=s(f);return r!==void 0&&r(p,g)?(u=f,p):(u=f,h=g)}var d=!1,u,h,m=n===void 0?null:n;return[function(){return c(e())},m===null?void 0:function(){return c(m())}]},[e,n,s,r]);var o=yB(t,a[0],a[1]);return bB(function(){l.hasValue=!0,l.value=o},[o]),NB(o),o};XE.exports=e4;var wB=XE.exports,kB=(...t)=>e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&(n.current=e)})},SB=({contentComponent:t})=>{const e=Wy.useSyncExternalStore(t.subscribe,t.getSnapshot,t.getServerSnapshot);return i.jsx(i.Fragment,{children:Object.values(e)})};function CB(){const t=new Set;let e={};return{subscribe(n){return t.add(n),()=>{t.delete(n)}},getSnapshot(){return e},getServerSnapshot(){return e},setRenderer(n,s){e={...e,[n]:rM.createPortal(s.reactElement,s.element,n)},t.forEach(r=>r())},removeRenderer(n){const s={...e};delete s[n],e=s,t.forEach(r=>r())}}}var EB=class extends ut.Component{constructor(t){var e;super(t),this.editorContentRef=ut.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!((e=t.editor)!=null&&e.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){var t;const e=this.props.editor;if(e&&!e.isDestroyed&&((t=e.view.dom)!=null&&t.parentNode)){if(e.contentComponent)return;const n=this.editorContentRef.current;n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n}),e.contentComponent=CB(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=e.contentComponent.subscribe(()=>{this.setState(s=>s.hasContentComponentInitialized?s:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),e.createNodeViews(),this.initialized=!0}}componentWillUnmount(){var t;const e=this.props.editor;if(e){this.initialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),e.contentComponent=null;try{if(!((t=e.view.dom)!=null&&t.parentNode))return;const n=document.createElement("div");n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;return i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:kB(e,this.editorContentRef),...n}),(t==null?void 0:t.contentComponent)&&i.jsx(SB,{contentComponent:t.contentComponent})]})}},AB=N.forwardRef((t,e)=>{const n=ut.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[t.editor]);return ut.createElement(EB,{key:n,innerRef:e,...t})}),t4=ut.memo(AB),DB=typeof window<"u"?N.useLayoutEffect:N.useEffect,MB=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const e=()=>{this.transactionNumber+=1,this.subscribers.forEach(s=>s())},n=this.editor;return n.on("transaction",e),()=>{n.off("transaction",e)}}}};function TB(t){var e;const[n]=N.useState(()=>new MB(t.editor)),s=wB.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,(e=t.equalityFn)!=null?e:mB);return DB(()=>n.watch(t.editor),[t.editor,n]),N.useDebugValue(s),s}var PB=!1,hx=typeof window>"u",IB=hx||!!(typeof window<"u"&&window.next),RB=class n4{constructor(e){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=e,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(e){this.editor=e,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?hx||IB?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const e={...this.options.current,onBeforeCreate:(...s)=>{var r,a;return(a=(r=this.options.current).onBeforeCreate)==null?void 0:a.call(r,...s)},onBlur:(...s)=>{var r,a;return(a=(r=this.options.current).onBlur)==null?void 0:a.call(r,...s)},onCreate:(...s)=>{var r,a;return(a=(r=this.options.current).onCreate)==null?void 0:a.call(r,...s)},onDestroy:(...s)=>{var r,a;return(a=(r=this.options.current).onDestroy)==null?void 0:a.call(r,...s)},onFocus:(...s)=>{var r,a;return(a=(r=this.options.current).onFocus)==null?void 0:a.call(r,...s)},onSelectionUpdate:(...s)=>{var r,a;return(a=(r=this.options.current).onSelectionUpdate)==null?void 0:a.call(r,...s)},onTransaction:(...s)=>{var r,a;return(a=(r=this.options.current).onTransaction)==null?void 0:a.call(r,...s)},onUpdate:(...s)=>{var r,a;return(a=(r=this.options.current).onUpdate)==null?void 0:a.call(r,...s)},onContentError:(...s)=>{var r,a;return(a=(r=this.options.current).onContentError)==null?void 0:a.call(r,...s)},onDrop:(...s)=>{var r,a;return(a=(r=this.options.current).onDrop)==null?void 0:a.call(r,...s)},onPaste:(...s)=>{var r,a;return(a=(r=this.options.current).onPaste)==null?void 0:a.call(r,...s)},onDelete:(...s)=>{var r,a;return(a=(r=this.options.current).onDelete)==null?void 0:a.call(r,...s)}};return new b$(e)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(e){return this.subscriptions.add(e),()=>{this.subscriptions.delete(e)}}static compareOptions(e,n){return Object.keys(e).every(s=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(s)?!0:s==="extensions"&&e.extensions&&n.extensions?e.extensions.length!==n.extensions.length?!1:e.extensions.every((r,a)=>{var l;return r===((l=n.extensions)==null?void 0:l[a])}):e[s]===n[s])}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&e.length===0?n4.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(e){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=e;return}if(this.previousDeps.length===e.length&&this.previousDeps.every((s,r)=>s===e[r]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=e}scheduleDestroy(){const e=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===e){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===e&&this.setEditor(null))},1)}};function OB(t={},e=[]){const n=N.useRef(t);n.current=t;const[s]=N.useState(()=>new RB(n)),r=Wy.useSyncExternalStore(s.subscribe,s.getEditor,s.getServerSnapshot);return N.useDebugValue(r),N.useEffect(s.onRender(e)),TB({editor:r,selector:({transactionNumber:a})=>t.shouldRerenderOnTransaction===!1||t.shouldRerenderOnTransaction===void 0?null:t.immediatelyRender&&a===0?0:a+1}),r}var s4=N.createContext({editor:null});s4.Consumer;var LB=N.createContext({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),FB=()=>N.useContext(LB);ut.forwardRef((t,e)=>{const{onDragStart:n}=FB(),s=t.as||"div";return i.jsx(s,{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})});ut.createContext({markViewContentRef:()=>{}});var N0=N.createContext({get editor(){throw new Error("useTiptap must be used within a provider")}});N0.displayName="TiptapContext";var zB=()=>N.useContext(N0);function r4({editor:t,instance:e,children:n}){const s=t??e;if(!s)throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");const r=N.useMemo(()=>({editor:s}),[s]),a=N.useMemo(()=>({editor:s}),[s]);return i.jsx(s4.Provider,{value:a,children:i.jsx(N0.Provider,{value:r,children:n})})}r4.displayName="Tiptap";function i4({...t}){const{editor:e}=zB();return i.jsx(t4,{editor:e,...t})}i4.displayName="Tiptap.Content";Object.assign(r4,{Content:i4});var Mh=(t,e)=>{if(t==="slot")return 0;if(t instanceof Function)return t(e);const{children:n,...s}=e??{};if(t==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,s,n]},$B=/^\s*>\s$/,BB=hs.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:t}){return Mh("blockquote",{..._t(this.options.HTMLAttributes,t),children:Mh("slot",{})})},parseMarkdown:(t,e)=>e.createNode("blockquote",void 0,e.parseChildren(t.tokens||[])),renderMarkdown:(t,e)=>{if(!t.content)return"";const n=">",s=[];return t.content.forEach(r=>{const o=e.renderChildren([r]).split(` +`).map(c=>c.trim()===""?n:`${n} ${c}`);s.push(o.join(` +`))}),s.join(` +${n} +`)},addCommands(){return{setBlockquote:()=>({commands:t})=>t.wrapIn(this.name),toggleBlockquote:()=>({commands:t})=>t.toggleWrap(this.name),unsetBlockquote:()=>({commands:t})=>t.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[co({find:$B,type:this.type})]}}),_B=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,VB=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,KB=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,UB=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,qB=Ja.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){return Mh("strong",{..._t(this.options.HTMLAttributes,t),children:Mh("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[oo({find:_B,type:this.type}),oo({find:KB,type:this.type})]},addPasteRules(){return[qa({find:VB,type:this.type}),qa({find:UB,type:this.type})]}}),HB=/(^|[^`])`([^`]+)`(?!`)$/,WB=/(^|[^`])`([^`]+)`(?!`)/g,QB=Ja.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:t}){return["code",_t(this.options.HTMLAttributes,t),0]},markdownTokenName:"codespan",parseMarkdown:(t,e)=>e.applyMark("code",[{type:"text",text:t.text||""}]),renderMarkdown:(t,e)=>t.content?`\`${e.renderChildren(t.content)}\``:"",addCommands(){return{setCode:()=>({commands:t})=>t.setMark(this.name),toggleCode:()=>({commands:t})=>t.toggleMark(this.name),unsetCode:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[oo({find:HB,type:this.type})]},addPasteRules(){return[qa({find:WB,type:this.type})]}}),ap=4,GB=/^```([a-z]+)?[\s\n]$/,JB=/^~~~([a-z]+)?[\s\n]$/,ZB=hs.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:ap,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var e;const{languageClassPrefix:n}=this.options;if(!n)return null;const a=[...((e=t.firstElementChild)==null?void 0:e.classList)||[]].filter(l=>l.startsWith(n)).map(l=>l.replace(n,""))[0];return a||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:t,HTMLAttributes:e}){return["pre",_t(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(t,e)=>{var n;return((n=t.raw)==null?void 0:n.startsWith("```"))===!1&&t.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:t.lang||null},t.text?[e.createTextNode(t.text)]:[])},renderMarkdown:(t,e)=>{var n;let s="";const r=((n=t.attrs)==null?void 0:n.language)||"";return t.content?s=[`\`\`\`${r}`,e.renderChildren(t.content),"```"].join(` +`):s=`\`\`\`${r} + +\`\`\``,s},addCommands(){return{setCodeBlock:t=>({commands:e})=>e.setNode(this.name,t),toggleCodeBlock:t=>({commands:e})=>e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:t,$anchor:e}=this.editor.state.selection,n=e.pos===1;return!t||e.parent.type.name!==this.name?!1:n||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:ap,{state:s}=t,{selection:r}=s,{$from:a,empty:l}=r;if(a.parent.type!==this.type)return!1;const o=" ".repeat(n);return l?t.commands.insertContent(o):t.commands.command(({tr:c})=>{const{from:d,to:u}=r,f=s.doc.textBetween(d,u,` +`,` +`).split(` +`).map(p=>o+p).join(` +`);return c.replaceWith(d,u,s.schema.text(f)),!0})},"Shift-Tab":({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=(e=this.options.tabSize)!=null?e:ap,{state:s}=t,{selection:r}=s,{$from:a,empty:l}=r;return a.parent.type!==this.type?!1:l?t.commands.command(({tr:o})=>{var c;const{pos:d}=a,u=a.start(),h=a.end(),f=s.doc.textBetween(u,h,` +`,` +`).split(` +`);let p=0,g=0;const x=d-u;for(let E=0;E=x){p=E;break}g+=f[E].length+1}const v=((c=f[p].match(/^ */))==null?void 0:c[0])||"",b=Math.min(v.length,n);if(b===0)return!0;let j=u;for(let E=0;E{const{from:c,to:d}=r,m=s.doc.textBetween(c,d,` +`,` +`).split(` +`).map(f=>{var p;const g=((p=f.match(/^ */))==null?void 0:p[0])||"",x=Math.min(g.length,n);return f.slice(x)}).join(` +`);return o.replaceWith(c,d,s.schema.text(m)),!0})},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:s,empty:r}=n;if(!r||s.parent.type!==this.type)return!1;const a=s.parentOffset===s.parent.nodeSize-2,l=s.parent.textContent.endsWith(` + +`);return!a||!l?!1:t.chain().command(({tr:o})=>(o.delete(s.pos-2,s.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:s}=e,{$from:r,empty:a}=n;if(!a||r.parent.type!==this.type||!(r.parentOffset===r.parent.nodeSize-2))return!1;const o=r.after();return o===void 0?!1:s.nodeAt(o)?t.commands.command(({tr:d})=>(d.setSelection(Ie.near(s.resolve(o))),!0)):t.commands.exitCode()}}},addInputRules(){return[dx({find:GB,type:this.type,getAttributes:t=>({language:t[1]})}),dx({find:JB,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new Nt({key:new Ht("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),s=e.clipboardData.getData("vscode-editor-data"),r=s?JSON.parse(s):void 0,a=r==null?void 0:r.mode;if(!n||!a)return!1;const{tr:l,schema:o}=t.state,c=o.text(n.replace(/\r\n?/g,` +`));return l.replaceSelectionWith(this.type.create({language:a},c)),l.selection.$from.parent.type!==this.type&&l.setSelection(De.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),t.dispatch(l),!0}}})]}}),YB=hs.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` + +`):""}),XB=hs.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:t}){return["br",_t(this.options.HTMLAttributes,t)]},renderText(){return` +`},renderMarkdown:()=>` +`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:s})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:r,storedMarks:a}=n;if(r.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=s.extensionManager,c=a||r.$to.parentOffset&&r.$from.marks();return e().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const h=c.filter(m=>o.includes(m.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),e_=hs.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,_t(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const s=(n=t.attrs)!=null&&n.level?parseInt(t.attrs.level,10):1,r="#".repeat(s);return t.content?`${r} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.setNode(this.name,t):!1,toggleHeading:t=>({commands:e})=>this.options.levels.includes(t.level)?e.toggleNode(this.name,"paragraph",t):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>dx({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),t_=hs.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:t}){return["hr",_t(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!N$(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:s}=n,r=t();return RE(n)?r.insertContentAt(s.pos,{type:this.name}):r.insertContent({type:this.name}),r.command(({state:a,tr:l,dispatch:o})=>{if(o){const{$to:c}=l.selection,d=c.end();if(c.nodeAfter)c.nodeAfter.isTextblock?l.setSelection(De.create(l.doc,c.pos+1)):c.nodeAfter.isBlock?l.setSelection(ke.create(l.doc,c.pos)):l.setSelection(De.create(l.doc,c.pos));else{const u=a.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,h=u==null?void 0:u.create();h&&(l.insert(d,h),l.setSelection(De.create(l.doc,d+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[j$({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),n_=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,s_=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,r_=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,i_=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,a_=Ja.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>t.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",_t(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[oo({find:n_,type:this.type}),oo({find:r_,type:this.type})]},addPasteRules(){return[qa({find:s_,type:this.type}),qa({find:i_,type:this.type})]}});const l_="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",o_="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",fx="numeric",mx="ascii",px="alpha",dc="asciinumeric",Wo="alphanumeric",gx="domain",a4="emoji",c_="scheme",d_="slashscheme",lp="whitespace";function u_(t,e){return t in e||(e[t]=[]),e[t]}function ha(t,e,n){e[fx]&&(e[dc]=!0,e[Wo]=!0),e[mx]&&(e[dc]=!0,e[px]=!0),e[dc]&&(e[Wo]=!0),e[px]&&(e[Wo]=!0),e[Wo]&&(e[gx]=!0),e[a4]&&(e[gx]=!0);for(const s in e){const r=u_(s,n);r.indexOf(t)<0&&r.push(t)}}function h_(t,e){const n={};for(const s in e)e[s].indexOf(t)>=0&&(n[s]=!0);return n}function Vn(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}Vn.groups={};Vn.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let s=0;st.ta(e,n,s,r),kt=(t,e,n,s,r)=>t.tr(e,n,s,r),pN=(t,e,n,s,r)=>t.ts(e,n,s,r),te=(t,e,n,s,r)=>t.tt(e,n,s,r),vr="WORD",xx="UWORD",l4="ASCIINUMERICAL",o4="ALPHANUMERICAL",Yc="LOCALHOST",yx="TLD",vx="UTLD",Tu="SCHEME",ll="SLASH_SCHEME",w0="NUM",bx="WS",k0="NL",uc="OPENBRACE",hc="CLOSEBRACE",Th="OPENBRACKET",Ph="CLOSEBRACKET",Ih="OPENPAREN",Rh="CLOSEPAREN",Oh="OPENANGLEBRACKET",Lh="CLOSEANGLEBRACKET",Fh="FULLWIDTHLEFTPAREN",zh="FULLWIDTHRIGHTPAREN",$h="LEFTCORNERBRACKET",Bh="RIGHTCORNERBRACKET",_h="LEFTWHITECORNERBRACKET",Vh="RIGHTWHITECORNERBRACKET",Kh="FULLWIDTHLESSTHAN",Uh="FULLWIDTHGREATERTHAN",qh="AMPERSAND",Hh="APOSTROPHE",Wh="ASTERISK",ti="AT",Qh="BACKSLASH",Gh="BACKTICK",Jh="CARET",ci="COLON",S0="COMMA",Zh="DOLLAR",Gs="DOT",Yh="EQUALS",C0="EXCLAMATION",ms="HYPHEN",fc="PERCENT",Xh="PIPE",ef="PLUS",tf="POUND",mc="QUERY",E0="QUOTE",c4="FULLWIDTHMIDDLEDOT",A0="SEMI",Js="SLASH",pc="TILDE",nf="UNDERSCORE",d4="EMOJI",sf="SYM";var u4=Object.freeze({__proto__:null,ALPHANUMERICAL:o4,AMPERSAND:qh,APOSTROPHE:Hh,ASCIINUMERICAL:l4,ASTERISK:Wh,AT:ti,BACKSLASH:Qh,BACKTICK:Gh,CARET:Jh,CLOSEANGLEBRACKET:Lh,CLOSEBRACE:hc,CLOSEBRACKET:Ph,CLOSEPAREN:Rh,COLON:ci,COMMA:S0,DOLLAR:Zh,DOT:Gs,EMOJI:d4,EQUALS:Yh,EXCLAMATION:C0,FULLWIDTHGREATERTHAN:Uh,FULLWIDTHLEFTPAREN:Fh,FULLWIDTHLESSTHAN:Kh,FULLWIDTHMIDDLEDOT:c4,FULLWIDTHRIGHTPAREN:zh,HYPHEN:ms,LEFTCORNERBRACKET:$h,LEFTWHITECORNERBRACKET:_h,LOCALHOST:Yc,NL:k0,NUM:w0,OPENANGLEBRACKET:Oh,OPENBRACE:uc,OPENBRACKET:Th,OPENPAREN:Ih,PERCENT:fc,PIPE:Xh,PLUS:ef,POUND:tf,QUERY:mc,QUOTE:E0,RIGHTCORNERBRACKET:Bh,RIGHTWHITECORNERBRACKET:Vh,SCHEME:Tu,SEMI:A0,SLASH:Js,SLASH_SCHEME:ll,SYM:sf,TILDE:pc,TLD:yx,UNDERSCORE:nf,UTLD:vx,UWORD:xx,WORD:vr,WS:bx});const gr=/[a-z]/,Lo=new RegExp("\\p{L}","u"),op=new RegExp("\\p{Emoji}","u"),xr=/\d/,cp=/\s/,gN="\r",dp=` +`,f_="️",m_="‍",up="";let au=null,lu=null;function p_(t=[]){const e={};Vn.groups=e;const n=new Vn;au==null&&(au=xN(l_)),lu==null&&(lu=xN(o_)),te(n,"'",Hh),te(n,"{",uc),te(n,"}",hc),te(n,"[",Th),te(n,"]",Ph),te(n,"(",Ih),te(n,")",Rh),te(n,"<",Oh),te(n,">",Lh),te(n,"(",Fh),te(n,")",zh),te(n,"「",$h),te(n,"」",Bh),te(n,"『",_h),te(n,"』",Vh),te(n,"<",Kh),te(n,">",Uh),te(n,"&",qh),te(n,"*",Wh),te(n,"@",ti),te(n,"`",Gh),te(n,"^",Jh),te(n,":",ci),te(n,",",S0),te(n,"$",Zh),te(n,".",Gs),te(n,"=",Yh),te(n,"!",C0),te(n,"-",ms),te(n,"%",fc),te(n,"|",Xh),te(n,"+",ef),te(n,"#",tf),te(n,"?",mc),te(n,'"',E0),te(n,"/",Js),te(n,";",A0),te(n,"~",pc),te(n,"_",nf),te(n,"\\",Qh),te(n,"・",c4);const s=kt(n,xr,w0,{[fx]:!0});kt(s,xr,s);const r=kt(s,gr,l4,{[dc]:!0}),a=kt(s,Lo,o4,{[Wo]:!0}),l=kt(n,gr,vr,{[mx]:!0});kt(l,xr,r),kt(l,gr,l),kt(r,xr,r),kt(r,gr,r);const o=kt(n,Lo,xx,{[px]:!0});kt(o,gr),kt(o,xr,a),kt(o,Lo,o),kt(a,xr,a),kt(a,gr),kt(a,Lo,a);const c=te(n,dp,k0,{[lp]:!0}),d=te(n,gN,bx,{[lp]:!0}),u=kt(n,cp,bx,{[lp]:!0});te(n,up,u),te(d,dp,c),te(d,up,u),kt(d,cp,u),te(u,gN),te(u,dp),kt(u,cp,u),te(u,up,u);const h=kt(n,op,d4,{[a4]:!0});te(h,"#"),kt(h,op,h),te(h,f_,h);const m=te(h,m_);te(m,"#"),kt(m,op,h);const f=[[gr,l],[xr,r]],p=[[gr,null],[Lo,o],[xr,a]];for(let g=0;gg[0]>x[0]?1:-1);for(let g=0;g=0?v[gx]=!0:gr.test(x)?xr.test(x)?v[dc]=!0:v[mx]=!0:v[fx]=!0,pN(n,x,x,v)}return pN(n,"localhost",Yc,{ascii:!0}),n.jd=new Vn(sf),{start:n,tokens:Object.assign({groups:e},u4)}}function h4(t,e){const n=g_(e.replace(/[A-Z]/g,o=>o.toLowerCase())),s=n.length,r=[];let a=0,l=0;for(;l=0&&(h+=n[l].length,m++),d+=n[l].length,a+=n[l].length,l++;a-=h,l-=m,d-=h,r.push({t:u.t,v:e.slice(a-d,a),s:a-d,e:a})}return r}function g_(t){const e=[],n=t.length;let s=0;for(;s56319||s+1===n||(a=t.charCodeAt(s+1))<56320||a>57343?t[s]:t.slice(s,s+2);e.push(l),s+=l.length}return e}function Gr(t,e,n,s,r){let a;const l=e.length;for(let o=0;o=0;)a++;if(a>0){e.push(n.join(""));for(let l=parseInt(t.substring(s,s+a),10);l>0;l--)n.pop();s+=a}else n.push(t[s]),s++}return e}const Xc={defaultProtocol:"http",events:null,format:yN,formatHref:yN,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function D0(t,e=null){let n=Object.assign({},Xc);t&&(n=Object.assign(n,t instanceof D0?t.o:t));const s=n.ignoreTags,r=[];for(let a=0;an?s.substring(0,n)+"…":s},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=Xc.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),s=t.get("formatHref",n,this),r=t.get("tagName",n,e),a=this.toFormattedString(t),l={},o=t.get("className",n,e),c=t.get("target",n,e),d=t.get("rel",n,e),u=t.getObj("attributes",n,e),h=t.getObj("events",n,e);return l.href=s,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),u&&Object.assign(l,u),{tagName:r,attributes:l,content:a,eventListeners:h}}};function Yf(t,e){class n extends f4{constructor(r,a){super(r,a),this.t=t}}for(const s in e)n.prototype[s]=e[s];return n.t=t,n}const vN=Yf("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),bN=Yf("text"),x_=Yf("nl"),ou=Yf("url",{isLink:!0,toHref(t=Xc.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==Yc&&t[1].t===ci}}),fs=t=>new Vn(t);function y_({groups:t}){const e=t.domain.concat([qh,Wh,ti,Qh,Gh,Jh,Zh,Yh,ms,w0,fc,Xh,ef,tf,Js,sf,pc,nf]),n=[Hh,ci,S0,Gs,C0,fc,mc,E0,A0,Oh,Lh,uc,hc,Ph,Th,Ih,Rh,Fh,zh,$h,Bh,_h,Vh,Kh,Uh],s=[qh,Hh,Wh,Qh,Gh,Jh,Zh,Yh,ms,uc,hc,fc,Xh,ef,tf,mc,Js,sf,pc,nf],r=fs(),a=te(r,pc);Pe(a,s,a),Pe(a,t.domain,a);const l=fs(),o=fs(),c=fs();Pe(r,t.domain,l),Pe(r,t.scheme,o),Pe(r,t.slashscheme,c),Pe(l,s,a),Pe(l,t.domain,l);const d=te(l,ti);te(a,ti,d),te(o,ti,d),te(c,ti,d);const u=te(a,Gs);Pe(u,s,a),Pe(u,t.domain,a);const h=fs();Pe(d,t.domain,h),Pe(h,t.domain,h);const m=te(h,Gs);Pe(m,t.domain,h);const f=fs(vN);Pe(m,t.tld,f),Pe(m,t.utld,f),te(d,Yc,f);const p=te(h,ms);te(p,ms,p),Pe(p,t.domain,h),Pe(f,t.domain,h),te(f,Gs,m),te(f,ms,p);const g=te(f,ci);Pe(g,t.numeric,vN);const x=te(l,ms),y=te(l,Gs);te(x,ms,x),Pe(x,t.domain,l),Pe(y,s,a),Pe(y,t.domain,l);const v=fs(ou);Pe(y,t.tld,v),Pe(y,t.utld,v),Pe(v,t.domain,l),Pe(v,s,a),te(v,Gs,y),te(v,ms,x),te(v,ti,d);const b=te(v,ci),j=fs(ou);Pe(b,t.numeric,j);const k=fs(ou),E=fs();Pe(k,e,k),Pe(k,n,E),Pe(E,e,k),Pe(E,n,E),te(v,Js,k),te(j,Js,k);const T=te(o,ci),w=te(c,ci),S=te(w,Js),M=te(S,Js);Pe(o,t.domain,l),te(o,Gs,y),te(o,ms,x),Pe(c,t.domain,l),te(c,Gs,y),te(c,ms,x),Pe(T,t.domain,k),te(T,Js,k),te(T,mc,k),Pe(M,t.domain,k),Pe(M,e,k),te(M,Js,k);const F=[[uc,hc],[Th,Ph],[Ih,Rh],[Oh,Lh],[Fh,zh],[$h,Bh],[_h,Vh],[Kh,Uh]];for(let R=0;R=0&&m++,r++,u++;if(m<0)r-=u,r0&&(a.push(hp(bN,e,l)),l=[]),r-=m,u-=m;const f=h.t,p=n.slice(r-u,r);a.push(hp(f,e,p))}}return l.length>0&&a.push(hp(bN,e,l)),a}function hp(t,e,n){const s=n[0].s,r=n[n.length-1].e,a=e.slice(s,r);return new t(a,n)}const b_=typeof console<"u"&&console&&console.warn||(()=>{}),j_="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",lt={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function N_(){return Vn.groups={},lt.scanner=null,lt.parser=null,lt.tokenQueue=[],lt.pluginQueue=[],lt.customSchemes=[],lt.initialized=!1,lt}function jN(t,e=!1){if(lt.initialized&&b_(`linkifyjs: already initialized - will not register custom scheme "${t}" ${j_}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error(`linkifyjs: incorrect scheme format. +1. Must only contain digits, lowercase ASCII letters or "-" +2. Cannot start or end with "-" +3. "-" cannot repeat`);lt.customSchemes.push([t,e])}function w_(){lt.scanner=p_(lt.customSchemes);for(let t=0;t{const r=e.some(d=>d.docChanged)&&!n.doc.eq(s.doc),a=e.some(d=>d.getMeta("preventAutolink"));if(!r||a)return;const{tr:l}=s,o=CE(n.doc,[...e]);if(IE(o).forEach(({newRange:d})=>{const u=Nz(s.doc,d,f=>f.isTextblock);let h,m;if(u.length>1)h=u[0],m=s.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const f=s.doc.textBetween(d.from,d.to," "," ");if(!S_.test(f))return;h=u[0],m=s.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const f=m.split(k_).filter(Boolean);if(f.length<=0)return!1;const p=f[f.length-1],g=h.pos+m.lastIndexOf(p);if(!p)return!1;const x=M0(p).map(y=>y.toObject(t.defaultProtocol));if(!E_(x))return!1;x.filter(y=>y.isLink).map(y=>({...y,from:g+y.start+1,to:g+y.end+1})).filter(y=>s.schema.marks.code?!s.doc.rangeHasMark(y.from,y.to,s.schema.marks.code):!0).filter(y=>t.validate(y.value)).filter(y=>t.shouldAutoLink(y.value)).forEach(y=>{x0(y.from,y.to,s.doc).some(v=>v.mark.type===t.type)||l.addMark(y.from,y.to,t.type.create({href:y.href}))})}}),!!l.steps.length)return l}})}function D_(t){return new Nt({key:new Ht("handleClickLink"),props:{handleClick:(e,n,s)=>{var r,a;if(s.button!==0||!e.editable)return!1;let l=null;if(s.target instanceof HTMLAnchorElement)l=s.target;else{const c=s.target;if(!c)return!1;const d=t.editor.view.dom;l=c.closest("a"),l&&!d.contains(l)&&(l=null)}if(!l)return!1;let o=!1;if(t.enableClickSelection&&(o=t.editor.commands.extendMarkRange(t.type.name)),t.openOnClick){const c=PE(e.state,t.type.name),d=(r=l.href)!=null?r:c.href,u=(a=l.target)!=null?a:c.target;d&&(window.open(d,u),o=!0)}return o}}})}function M_(t){return new Nt({key:new Ht("handlePasteLink"),props:{handlePaste:(e,n,s)=>{const{shouldAutoLink:r}=t,{state:a}=e,{selection:l}=a,{empty:o}=l;if(o)return!1;let c="";s.content.forEach(u=>{c+=u.textContent});const d=m4(c,{defaultProtocol:t.defaultProtocol}).find(u=>u.isLink&&u.value===c);return!c||!d||r!==void 0&&!r(d.value)?!1:t.editor.commands.setMark(t.type,{href:d.href})}}})}function Yi(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(s=>{const r=typeof s=="string"?s:s.scheme;r&&n.push(r)}),!t||t.replace(C_,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var p4=Ja.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{if(typeof t=="string"){jN(t);return}jN(t.scheme,t.optionalSlashes)})},onDestroy(){N_()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!Yi(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(t),n=/^[a-z][a-z0-9+.-]*:/i.test(t);if(e||n&&!t.includes("@"))return!0;const r=(t.includes("@")?t.split("@").pop():t).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(r)||!/\./.test(r))}}},addAttributes(){return{href:{default:null,parseHTML(t){return t.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:n=>!!Yi(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:e=>!!Yi(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",_t(this.options.HTMLAttributes,t),0]:["a",_t(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n,s,r,a;const l=(s=(n=t.attrs)==null?void 0:n.href)!=null?s:"",o=(a=(r=t.attrs)==null?void 0:r.title)!=null?a:"",c=e.renderChildren(t);return o?`[${c}](${l} "${o}")`:`[${c}](${l})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return this.options.isAllowedUri(n,{defaultValidate:s=>!!Yi(s,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,t).setMeta("preventAutolink",!0).run():!1},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return n&&!this.options.isAllowedUri(n,{defaultValidate:s=>!!Yi(s,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[qa({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:s}=this.options,r=m4(t).filter(a=>a.isLink&&this.options.isAllowedUri(a.value,{defaultValidate:l=>!!Yi(l,n),protocols:n,defaultProtocol:s}));r.length&&r.forEach(a=>{this.options.shouldAutoLink(a.value)&&e.push({text:a.value,data:{href:a.href},index:a.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:(e=t.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;return this.options.autolink&&t.push(A_({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:s=>this.options.isAllowedUri(s,{defaultValidate:r=>!!Yi(r,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),t.push(D_({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(M_({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),T_=p4,P_=Object.defineProperty,I_=(t,e)=>{for(var n in e)P_(t,n,{get:e[n],enumerable:!0})},R_="listItem",NN="textStyle",wN=/^\s*([-+*])\s$/,g4=hs.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:t}){return["ul",_t(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>t.type!=="list"||t.ordered?[]:{type:"bulletList",content:t.items?e.parseChildren(t.items):[]},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` +`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(R_,this.editor.getAttributes(NN)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=co({find:wN,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=co({find:wN,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(NN),editor:this.editor})),[t]}}),x4=hs.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:t}){return["li",_t(this.options.HTMLAttributes,t),0]},markdownTokenName:"list_item",parseMarkdown:(t,e)=>{if(t.type!=="list_item")return[];let n=[];if(t.tokens&&t.tokens.length>0)if(t.tokens.some(r=>r.type==="paragraph"))n=e.parseChildren(t.tokens);else{const r=t.tokens[0];if(r&&r.type==="text"&&r.tokens&&r.tokens.length>0){if(n=[{type:"paragraph",content:e.parseInline(r.tokens)}],t.tokens.length>1){const l=t.tokens.slice(1),o=e.parseChildren(l);n.push(...o)}}else n=e.parseChildren(t.tokens)}return n.length===0&&(n=[{type:"paragraph",content:[]}]),{type:"listItem",content:n}},renderMarkdown:(t,e,n)=>j0(t,e,s=>{var r,a;return s.parentType==="bulletList"?"- ":s.parentType==="orderedList"?`${(((a=(r=s.meta)==null?void 0:r.parentAttrs)==null?void 0:a.start)||1)+s.index}. `:"- "},n),addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),O_={};I_(O_,{findListItemPos:()=>Ed,getNextListDepth:()=>P0,handleBackspace:()=>jx,handleDelete:()=>Nx,hasListBefore:()=>y4,hasListItemAfter:()=>L_,hasListItemBefore:()=>v4,listItemHasSubList:()=>b4,nextListIsDeeper:()=>j4,nextListIsHigher:()=>N4});var Ed=(t,e)=>{const{$from:n}=e.selection,s=Bt(t,e.schema);let r=null,a=n.depth,l=n.pos,o=null;for(;a>0&&o===null;)r=n.node(a),r.type===s?o=a:(a-=1,l-=1);return o===null?null:{$pos:e.doc.resolve(l),depth:o}},P0=(t,e)=>{const n=Ed(t,e);if(!n)return!1;const[,s]=Pz(e,t,n.$pos.pos+4);return s},y4=(t,e,n)=>{const{$anchor:s}=t.selection,r=Math.max(0,s.pos-2),a=t.doc.resolve(r).node();return!(!a||!n.includes(a.type.name))},v4=(t,e)=>{var n;const{$anchor:s}=e.selection,r=e.doc.resolve(s.pos-2);return!(r.index()===0||((n=r.nodeBefore)==null?void 0:n.type.name)!==t)},b4=(t,e,n)=>{if(!n)return!1;const s=Bt(t,e.schema);let r=!1;return n.descendants(a=>{a.type===s&&(r=!0)}),r},jx=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!Ki(t.state,e)&&y4(t.state,e,n)){const{$anchor:o}=t.state.selection,c=t.state.doc.resolve(o.before()-1),d=[];c.node().descendants((m,f)=>{m.type.name===e&&d.push({node:m,pos:f})});const u=d.at(-1);if(!u)return!1;const h=t.state.doc.resolve(c.start()+u.pos+1);return t.chain().cut({from:o.start()-1,to:o.end()+1},h.end()).joinForward().run()}if(!Ki(t.state,e)||!Lz(t.state))return!1;const s=Ed(e,t.state);if(!s)return!1;const a=t.state.doc.resolve(s.$pos.pos-2).node(s.depth),l=b4(e,t.state,a);return v4(e,t.state)&&!l?t.commands.joinItemBackward():t.chain().liftListItem(e).run()},j4=(t,e)=>{const n=P0(t,e),s=Ed(t,e);return!s||!n?!1:n>s.depth},N4=(t,e)=>{const n=P0(t,e),s=Ed(t,e);return!s||!n?!1:n{if(!Ki(t.state,e)||!Oz(t.state,e))return!1;const{selection:n}=t.state,{$from:s,$to:r}=n;return!n.empty&&s.sameParent(r)?!1:j4(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():N4(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward()},L_=(t,e)=>{var n;const{$anchor:s}=e.selection,r=e.doc.resolve(s.pos-s.parentOffset-2);return!(r.index()===r.parent.childCount-1||((n=r.nodeAfter)==null?void 0:n.type.name)!==t)},w4=It.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&Nx(t,n)&&(e=!0)}),e},"Mod-Delete":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{t.state.schema.nodes[n]!==void 0&&Nx(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:s})=>{t.state.schema.nodes[n]!==void 0&&jx(t,n,s)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:s})=>{t.state.schema.nodes[n]!==void 0&&jx(t,n,s)&&(e=!0)}),e}}}}),kN=/^(\s*)(\d+)\.\s+(.*)$/,F_=/^\s/;function z_(t){const e=[];let n=0,s=0;for(;ne;)m.push(t[h]),h+=1;if(m.length>0){const f=Math.min(...m.map(g=>g.indent)),p=k4(m,f,n);d.push({type:"list",ordered:!0,start:m[0].number,items:p,raw:m.map(g=>g.raw).join(` +`)})}r.push({type:"list_item",raw:l.raw,tokens:d}),a=h}else a+=1}return r}function $_(t,e){return t.map(n=>{if(n.type!=="list_item")return e.parseChildren([n])[0];const s=[];return n.tokens&&n.tokens.length>0&&n.tokens.forEach(r=>{if(r.type==="paragraph"||r.type==="list"||r.type==="blockquote"||r.type==="code")s.push(...e.parseChildren([r]));else if(r.type==="text"&&r.tokens){const a=e.parseChildren([r]);s.push({type:"paragraph",content:a})}else{const a=e.parseChildren([r]);a.length>0&&s.push(...a)}}),{type:"listItem",content:s}})}var B_="listItem",SN="textStyle",CN=/^(\d+)\.\s$/,S4=hs.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:t=>t.hasAttribute("start")?parseInt(t.getAttribute("start")||"",10):1},type:{default:null,parseHTML:t=>t.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:t}){const{start:e,...n}=t;return e===1?["ol",_t(this.options.HTMLAttributes,n),0]:["ol",_t(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if(t.type!=="list"||!t.ordered)return[];const n=t.start||1,s=t.items?$_(t.items,e):[];return n!==1?{type:"orderedList",attrs:{start:n},content:s}:{type:"orderedList",content:s}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` +`):"",markdownTokenizer:{name:"orderedList",level:"block",start:t=>{const e=t.match(/^(\s*)(\d+)\.\s+/),n=e==null?void 0:e.index;return n!==void 0?n:-1},tokenize:(t,e,n)=>{var s;const r=t.split(` +`),[a,l]=z_(r);if(a.length===0)return;const o=k4(a,0,n);return o.length===0?void 0:{type:"list",ordered:!0,start:((s=a[0])==null?void 0:s.number)||1,items:o,raw:r.slice(0,l).join(` +`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(B_,this.editor.getAttributes(SN)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let t=co({find:CN,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(t=co({find:CN,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(SN)}),joinPredicate:(e,n)=>n.childCount+n.attrs.start===+e[1],editor:this.editor})),[t]}}),__=/^\s*(\[([( |x])?\])\s$/,V_=hs.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:t=>{const e=t.getAttribute("data-checked");return e===""||e==="true"},renderHTML:t=>({"data-checked":t.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:t,HTMLAttributes:e}){return["li",_t(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:t.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(t,e)=>{const n=[];if(t.tokens&&t.tokens.length>0?n.push(e.createNode("paragraph",{},e.parseInline(t.tokens))):t.text?n.push(e.createNode("paragraph",{},[e.createNode("text",{text:t.text})])):n.push(e.createNode("paragraph",{},[])),t.nestedTokens&&t.nestedTokens.length>0){const s=e.parseChildren(t.nestedTokens);n.push(...s)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;const r=`- [${(n=t.attrs)!=null&&n.checked?"x":" "}] `;return j0(t,e,r)},addKeyboardShortcuts(){const t={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...t,Tab:()=>this.editor.commands.sinkListItem(this.name)}:t},addNodeView(){return({node:t,HTMLAttributes:e,getPos:n,editor:s})=>{const r=document.createElement("li"),a=document.createElement("label"),l=document.createElement("span"),o=document.createElement("input"),c=document.createElement("div"),d=h=>{var m,f;o.ariaLabel=((f=(m=this.options.a11y)==null?void 0:m.checkboxLabel)==null?void 0:f.call(m,h,o.checked))||`Task item checkbox for ${h.textContent||"empty task item"}`};d(t),a.contentEditable="false",o.type="checkbox",o.addEventListener("mousedown",h=>h.preventDefault()),o.addEventListener("change",h=>{if(!s.isEditable&&!this.options.onReadOnlyChecked){o.checked=!o.checked;return}const{checked:m}=h.target;s.isEditable&&typeof n=="function"&&s.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{const p=n();if(typeof p!="number")return!1;const g=f.doc.nodeAt(p);return f.setNodeMarkup(p,void 0,{...g==null?void 0:g.attrs,checked:m}),!0}).run(),!s.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,m)||(o.checked=!o.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([h,m])=>{r.setAttribute(h,m)}),r.dataset.checked=t.attrs.checked,o.checked=t.attrs.checked,a.append(o,l),r.append(a,c),Object.entries(e).forEach(([h,m])=>{r.setAttribute(h,m)});let u=new Set(Object.keys(e));return{dom:r,contentDOM:c,update:h=>{if(h.type!==this.type)return!1;r.dataset.checked=h.attrs.checked,o.checked=h.attrs.checked,d(h);const m=s.extensionManager.attributes,f=Zc(h,m),p=new Set(Object.keys(f)),g=this.options.HTMLAttributes;return u.forEach(x=>{p.has(x)||(x in g?r.setAttribute(x,g[x]):r.removeAttribute(x))}),Object.entries(f).forEach(([x,y])=>{y==null?x in g?r.setAttribute(x,g[x]):r.removeAttribute(x):r.setAttribute(x,y)}),u=p,!0}}}},addInputRules(){return[co({find:__,type:this.type,getAttributes:t=>({checked:t[t.length-1]==="x"})})]}}),K_=hs.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:t}){return["ul",_t(this.options.HTMLAttributes,t,{"data-type":this.name}),0]},parseMarkdown:(t,e)=>e.createNode("taskList",{},e.parseChildren(t.items||[])),renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,` +`):"",markdownTokenizer:{name:"taskList",level:"block",start(t){var e;const n=(e=t.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return n!==void 0?n:-1},tokenize(t,e,n){const s=a=>{const l=ux(a,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:o=>({indentLevel:o[1].length,mainContent:o[4],checked:o[3].toLowerCase()==="x"}),createToken:(o,c)=>({type:"taskItem",raw:"",mainContent:o.mainContent,indentLevel:o.indentLevel,checked:o.checked,text:o.mainContent,tokens:n.inlineTokens(o.mainContent),nestedTokens:c}),customNestedParser:s},n);return l?[{type:"taskList",raw:l.raw,items:l.items}]:n.blockTokens(a)},r=ux(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:a=>({indentLevel:a[1].length,mainContent:a[4],checked:a[3].toLowerCase()==="x"}),createToken:(a,l)=>({type:"taskItem",raw:"",mainContent:a.mainContent,indentLevel:a.indentLevel,checked:a.checked,text:a.mainContent,tokens:n.inlineTokens(a.mainContent),nestedTokens:l}),customNestedParser:s},n);if(r)return{type:"taskList",raw:r.raw,items:r.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:t})=>t.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});It.create({name:"listKit",addExtensions(){const t=[];return this.options.bulletList!==!1&&t.push(g4.configure(this.options.bulletList)),this.options.listItem!==!1&&t.push(x4.configure(this.options.listItem)),this.options.listKeymap!==!1&&t.push(w4.configure(this.options.listKeymap)),this.options.orderedList!==!1&&t.push(S4.configure(this.options.orderedList)),this.options.taskItem!==!1&&t.push(V_.configure(this.options.taskItem)),this.options.taskList!==!1&&t.push(K_.configure(this.options.taskList)),t}});var EN=" ",U_=" ",q_=hs.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:t}){return["p",_t(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];if(n.length===1&&n[0].type==="image")return e.parseChildren([n[0]]);const s=e.parseInline(n);return s.length===1&&s[0].type==="text"&&(s[0].text===EN||s[0].text===U_)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,s)},renderMarkdown:(t,e)=>{if(!t)return"";const n=Array.isArray(t.content)?t.content:[];return n.length===0?EN:e.renderChildren(n)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),H_=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,W_=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Q_=Ja.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["s",_t(this.options.HTMLAttributes,t),0]},markdownTokenName:"del",parseMarkdown:(t,e)=>e.applyMark("strike",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`~~${e.renderChildren(t)}~~`,addCommands(){return{setStrike:()=>({commands:t})=>t.setMark(this.name),toggleStrike:()=>({commands:t})=>t.toggleMark(this.name),unsetStrike:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[oo({find:H_,type:this.type})]},addPasteRules(){return[qa({find:W_,type:this.type})]}}),G_=hs.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),J_=Ja.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>t.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:t}){return["u",_t(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown(t,e){return`++${e.renderChildren(t)}++`},markdownTokenizer:{name:"underline",level:"inline",start(t){return t.indexOf("++")},tokenize(t,e,n){const r=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!r)return;const a=r[2].trim();return{type:"underline",raw:r[0],text:a,tokens:n.inlineTokens(a)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function Z_(t={}){return new Nt({view(e){return new Y_(e,t)}})}class Y_{constructor(e,n){var s;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(s=n.width)!==null&&s!==void 0?s:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(r=>{let a=l=>{this[r](l)};return e.dom.addEventListener(r,a),{name:r,handler:a}})}destroy(){this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){this.cursorPos!=null&&n.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,s,r=this.editorView.dom,a=r.getBoundingClientRect(),l=a.width/r.offsetWidth,o=a.height/r.offsetHeight;if(n){let h=e.nodeBefore,m=e.nodeAfter;if(h||m){let f=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(f){let p=f.getBoundingClientRect(),g=h?p.bottom:p.top;h&&m&&(g=(g+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let x=this.width/2*o;s={left:p.left,right:p.right,top:g-x,bottom:g+x}}}}if(!s){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;s={left:h.left-m,right:h.left+m,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,f=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*f}this.element.style.left=(s.left-d)/l+"px",this.element.style.top=(s.top-u)/o+"px",this.element.style.width=(s.right-s.left)/l+"px",this.element.style.height=(s.bottom-s.top)/o+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),s=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),r=s&&s.type.spec.disableDropCursor,a=typeof r=="function"?r(this.editorView,n,e):r;if(n&&!a){let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=x2(this.editorView.state.doc,l,this.editorView.dragging.slice);o!=null&&(l=o)}this.setCursor(l),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class Dt extends Ie{constructor(e){super(e,e)}map(e,n){let s=e.resolve(n.map(this.head));return Dt.valid(s)?new Dt(s):Ie.near(s)}content(){return me.empty}eq(e){return e instanceof Dt&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new Dt(e.resolve(n.pos))}getBookmark(){return new I0(this.anchor)}static valid(e){let n=e.parent;if(n.isTextblock||!X_(e)||!eV(e))return!1;let s=n.type.spec.allowGapCursor;if(s!=null)return s;let r=n.contentMatchAt(e.index()).defaultType;return r&&r.isTextblock}static findGapCursorFrom(e,n,s=!1){e:for(;;){if(!s&&Dt.valid(e))return e;let r=e.pos,a=null;for(let l=e.depth;;l--){let o=e.node(l);if(n>0?e.indexAfter(l)0){a=o.child(n>0?e.indexAfter(l):e.index(l)-1);break}else if(l==0)return null;r+=n;let c=e.doc.resolve(r);if(Dt.valid(c))return c}for(;;){let l=n>0?a.firstChild:a.lastChild;if(!l){if(a.isAtom&&!a.isText&&!ke.isSelectable(a)){e=e.doc.resolve(r+a.nodeSize*n),s=!1;continue e}break}a=l,r+=n;let o=e.doc.resolve(r);if(Dt.valid(o))return o}return null}}}Dt.prototype.visible=!1;Dt.findFrom=Dt.findGapCursorFrom;Ie.jsonID("gapcursor",Dt);class I0{constructor(e){this.pos=e}map(e){return new I0(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return Dt.valid(n)?new Dt(n):Ie.near(n)}}function C4(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function X_(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),s=t.node(e);if(n==0){if(s.type.spec.isolating)return!0;continue}for(let r=s.child(n-1);;r=r.lastChild){if(r.childCount==0&&!r.inlineContent||C4(r.type))return!0;if(r.inlineContent)return!1}}return!0}function eV(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),s=t.node(e);if(n==s.childCount){if(s.type.spec.isolating)return!0;continue}for(let r=s.child(n);;r=r.firstChild){if(r.childCount==0&&!r.inlineContent||C4(r.type))return!0;if(r.inlineContent)return!1}}return!0}function tV(){return new Nt({props:{decorations:iV,createSelectionBetween(t,e,n){return e.pos==n.pos&&Dt.valid(n)?new Dt(n):null},handleClick:sV,handleKeyDown:nV,handleDOMEvents:{beforeinput:rV}}})}const nV=yE({ArrowLeft:cu("horiz",-1),ArrowRight:cu("horiz",1),ArrowUp:cu("vert",-1),ArrowDown:cu("vert",1)});function cu(t,e){const n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(s,r,a){let l=s.selection,o=e>0?l.$to:l.$from,c=l.empty;if(l instanceof De){if(!a.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=s.doc.resolve(e>0?o.after():o.before())}let d=Dt.findGapCursorFrom(o,e,c);return d?(r&&r(s.tr.setSelection(new Dt(d))),!0):!1}}function sV(t,e,n){if(!t||!t.editable)return!1;let s=t.state.doc.resolve(e);if(!Dt.valid(s))return!1;let r=t.posAtCoords({left:n.clientX,top:n.clientY});return r&&r.inside>-1&&ke.isSelectable(t.state.doc.nodeAt(r.inside))?!1:(t.dispatch(t.state.tr.setSelection(new Dt(s))),!0)}function rV(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof Dt))return!1;let{$from:n}=t.state.selection,s=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!s)return!1;let r=X.empty;for(let l=s.length-1;l>=0;l--)r=X.from(s[l].createAndFill(null,r));let a=t.state.tr.replace(n.pos,n.pos,new me(r,0,0));return a.setSelection(De.near(a.doc.resolve(n.pos+1))),t.dispatch(a),!1}function iV(t){if(!(t.selection instanceof Dt))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",yt.create(t.doc,[An.widget(t.selection.head,e,{key:"gapcursor"})])}var rf=200,tn=function(){};tn.prototype.append=function(e){return e.length?(e=tn.from(e),!this.length&&e||e.length=n?tn.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,n))};tn.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};tn.prototype.forEach=function(e,n,s){n===void 0&&(n=0),s===void 0&&(s=this.length),n<=s?this.forEachInner(e,n,s,0):this.forEachInvertedInner(e,n,s,0)};tn.prototype.map=function(e,n,s){n===void 0&&(n=0),s===void 0&&(s=this.length);var r=[];return this.forEach(function(a,l){return r.push(e(a,l))},n,s),r};tn.from=function(e){return e instanceof tn?e:e&&e.length?new E4(e):tn.empty};var E4=function(t){function e(s){t.call(this),this.values=s}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(r,a){return r==0&&a==this.length?this:new e(this.values.slice(r,a))},e.prototype.getInner=function(r){return this.values[r]},e.prototype.forEachInner=function(r,a,l,o){for(var c=a;c=l;c--)if(r(this.values[c],o+c)===!1)return!1},e.prototype.leafAppend=function(r){if(this.length+r.length<=rf)return new e(this.values.concat(r.flatten()))},e.prototype.leafPrepend=function(r){if(this.length+r.length<=rf)return new e(r.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e}(tn);tn.empty=new E4([]);var aV=function(t){function e(n,s){t.call(this),this.left=n,this.right=s,this.length=n.length+s.length,this.depth=Math.max(n.depth,s.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(s){return so&&this.right.forEachInner(s,Math.max(r-o,0),Math.min(this.length,a)-o,l+o)===!1)return!1},e.prototype.forEachInvertedInner=function(s,r,a,l){var o=this.left.length;if(r>o&&this.right.forEachInvertedInner(s,r-o,Math.max(a,o)-o,l+o)===!1||a=a?this.right.slice(s-a,r-a):this.left.slice(s,a).append(this.right.slice(0,r-a))},e.prototype.leafAppend=function(s){var r=this.right.leafAppend(s);if(r)return new e(this.left,r)},e.prototype.leafPrepend=function(s){var r=this.left.leafPrepend(s);if(r)return new e(r,this.right)},e.prototype.appendInner=function(s){return this.left.depth>=Math.max(this.right.depth,s.depth)+1?new e(this.left,new e(this.right,s)):new e(this,s)},e}(tn);const lV=500;class Ls{constructor(e,n){this.items=e,this.eventCount=n}popEvent(e,n){if(this.eventCount==0)return null;let s=this.items.length;for(;;s--)if(this.items.get(s-1).selection){--s;break}let r,a;n&&(r=this.remapping(s,this.items.length),a=r.maps.length);let l=e.tr,o,c,d=[],u=[];return this.items.forEach((h,m)=>{if(!h.step){r||(r=this.remapping(s,m+1),a=r.maps.length),a--,u.push(h);return}if(r){u.push(new Zs(h.map));let f=h.step.map(r.slice(a)),p;f&&l.maybeStep(f).doc&&(p=l.mapping.maps[l.mapping.maps.length-1],d.push(new Zs(p,void 0,void 0,d.length+u.length))),a--,p&&r.appendMap(p,a)}else l.maybeStep(h.step);if(h.selection)return o=r?h.selection.map(r.slice(a)):h.selection,c=new Ls(this.items.slice(0,s).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(e,n,s,r){let a=[],l=this.eventCount,o=this.items,c=!r&&o.length?o.get(o.length-1):null;for(let u=0;ucV&&(o=oV(o,d),l-=d),new Ls(o.append(a),l)}remapping(e,n){let s=new qc;return this.items.forEach((r,a)=>{let l=r.mirrorOffset!=null&&a-r.mirrorOffset>=e?s.maps.length-r.mirrorOffset:void 0;s.appendMap(r.map,l)},e,n),s}addMaps(e){return this.eventCount==0?this:new Ls(this.items.append(e.map(n=>new Zs(n))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let s=[],r=Math.max(0,this.items.length-n),a=e.mapping,l=e.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},r);let c=n;this.items.forEach(m=>{let f=a.getMirror(--c);if(f==null)return;l=Math.min(l,f);let p=a.maps[f];if(m.step){let g=e.steps[f].invert(e.docs[f]),x=m.selection&&m.selection.map(a.slice(c+1,f));x&&o++,s.push(new Zs(p,g,x))}else s.push(new Zs(p))},r);let d=[];for(let m=n;mlV&&(h=h.compress(this.items.length-s.length)),h}emptyItemCount(){let e=0;return this.items.forEach(n=>{n.step||e++}),e}compress(e=this.items.length){let n=this.remapping(0,e),s=n.maps.length,r=[],a=0;return this.items.forEach((l,o)=>{if(o>=e)r.push(l),l.selection&&a++;else if(l.step){let c=l.step.map(n.slice(s)),d=c&&c.getMap();if(s--,d&&n.appendMap(d,s),c){let u=l.selection&&l.selection.map(n.slice(s));u&&a++;let h=new Zs(d.invert(),c,u),m,f=r.length-1;(m=r.length&&r[f].merge(h))?r[f]=m:r.push(h)}}else l.map&&s--},this.items.length,0),new Ls(tn.from(r.reverse()),a)}}Ls.empty=new Ls(tn.empty,0);function oV(t,e){let n;return t.forEach((s,r)=>{if(s.selection&&e--==0)return n=r,!1}),t.slice(n)}class Zs{constructor(e,n,s,r){this.map=e,this.step=n,this.selection=s,this.mirrorOffset=r}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new Zs(n.getMap().invert(),n,this.selection)}}}class ni{constructor(e,n,s,r,a){this.done=e,this.undone=n,this.prevRanges=s,this.prevTime=r,this.prevComposition=a}}const cV=20;function dV(t,e,n,s){let r=n.getMeta(Ta),a;if(r)return r.historyState;n.getMeta(fV)&&(t=new ni(t.done,t.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return t;if(l&&l.getMeta(Ta))return l.getMeta(Ta).redo?new ni(t.done.addTransform(n,void 0,s,Pu(e)),t.undone,AN(n.mapping.maps),t.prevTime,t.prevComposition):new ni(t.done,t.undone.addTransform(n,void 0,s,Pu(e)),null,t.prevTime,t.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(l&&l.getMeta("addToHistory")===!1)){let o=n.getMeta("composition"),c=t.prevTime==0||!l&&t.prevComposition!=o&&(t.prevTime<(n.time||0)-s.newGroupDelay||!uV(n,t.prevRanges)),d=l?fp(t.prevRanges,n.mapping):AN(n.mapping.maps);return new ni(t.done.addTransform(n,c?e.selection.getBookmark():void 0,s,Pu(e)),Ls.empty,d,n.time,o??t.prevComposition)}else return(a=n.getMeta("rebased"))?new ni(t.done.rebased(n,a),t.undone.rebased(n,a),fp(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new ni(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),fp(t.prevRanges,n.mapping),t.prevTime,t.prevComposition)}function uV(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((s,r)=>{for(let a=0;a=e[a]&&(n=!0)}),n}function AN(t){let e=[];for(let n=t.length-1;n>=0&&e.length==0;n--)t[n].forEach((s,r,a,l)=>e.push(a,l));return e}function fp(t,e){if(!t)return null;let n=[];for(let s=0;s{let r=Ta.getState(n);if(!r||(t?r.undone:r.done).eventCount==0)return!1;if(s){let a=hV(r,n,t);a&&s(e?a.scrollIntoView():a)}return!0}}const D4=A4(!1,!0),M4=A4(!0,!0);It.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{const e=(t==null?void 0:t.node)||this.editor.state.doc;if(((t==null?void 0:t.mode)||this.options.mode)==="textSize"){const s=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(s)}return e.nodeSize},this.storage.words=t=>{const e=(t==null?void 0:t.node)||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new Nt({key:new Ht("characterCount"),appendTransaction:(e,n,s)=>{if(t)return;const r=this.options.limit;if(r==null||r===0){t=!0;return}const a=this.storage.characters({node:s.doc});if(a>r){const l=a-r,o=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${r} characters. Content was automatically trimmed.`);const d=s.tr.deleteRange(o,c);return t=!0,d}t=!0},filterTransaction:(e,n)=>{const s=this.options.limit;if(!e.docChanged||s===0||s===null||s===void 0)return!0;const r=this.storage.characters({node:n.doc}),a=this.storage.characters({node:e.doc});if(a<=s||r>s&&a>s&&a<=r)return!0;if(r>s&&a>s&&a>r||!e.getMeta("paste"))return!1;const o=e.selection.$head.pos,c=a-s,d=o-c,u=o;return e.deleteRange(d,u),!(this.storage.characters({node:e.doc})>s)}})]}});var pV=It.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Z_(this.options)]}});It.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new Nt({key:new Ht("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:s}=this.editor,{anchor:r}=e,a=[];if(!n||!s)return yt.create(t,[]);let l=0;this.options.mode==="deepest"&&t.descendants((c,d)=>{if(c.isText)return;if(!(r>=d&&r<=d+c.nodeSize-1))return!1;l+=1});let o=0;return t.descendants((c,d)=>{if(c.isText||!(r>=d&&r<=d+c.nodeSize-1))return!1;if(o+=1,this.options.mode==="deepest"&&l-o>0||this.options.mode==="shallowest"&&o>1)return this.options.mode==="deepest";a.push(An.node(d,d+c.nodeSize,{class:this.options.className}))}),yt.create(t,a)}}})]}});var gV=It.create({name:"gapCursor",addProseMirrorPlugins(){return[tV()]},extendNodeSchema(t){var e;const n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=Ze(we(t,"allowGapCursor",n)))!=null?e:null}}}),MN="placeholder";function xV(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}It.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:MN,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const t=this.options.dataAttribute?`data-${xV(this.options.dataAttribute)}`:`data-${MN}`;return[new Nt({key:new Ht("placeholder"),props:{decorations:({doc:e,selection:n})=>{const s=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:r}=n,a=[];if(!s)return null;const l=this.editor.isEmpty;return e.descendants((o,c)=>{const d=r>=c&&r<=c+o.nodeSize,u=!o.isLeaf&&Qf(o);if((d||!this.options.showOnlyCurrent)&&u){const h=[this.options.emptyNodeClass];l&&h.push(this.options.emptyEditorClass);const m=An.node(c,c+o.nodeSize,{class:h.join(" "),[t]:typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:o,pos:c,hasAnchor:d}):this.options.placeholder});a.push(m)}return this.options.includeChildren}),yt.create(e,a)}}})]}});It.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:t,options:e}=this;return[new Nt({key:new Ht("selection"),props:{decorations(n){return n.selection.empty||t.isFocused||!t.isEditable||RE(n.selection)||t.view.dragging?null:yt.create(n.doc,[An.inline(n.selection.from,n.selection.to,{class:e.className})])}}})]}});function TN({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(e==null?void 0:e.type)===t}var yV=It.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;const e=new Ht(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:t.name)||"paragraph",s=Object.entries(this.editor.schema.nodes).map(([,r])=>r).filter(r=>(this.options.notAfter||[]).concat(n).includes(r.name));return[new Nt({key:e,appendTransaction:(r,a,l)=>{const{doc:o,tr:c,schema:d}=l,u=e.getState(l),h=o.content.size,m=d.nodes[n];if(u)return c.insert(h,m.create())},state:{init:(r,a)=>{const l=a.tr.doc.lastChild;return!TN({node:l,types:s})},apply:(r,a)=>{if(!r.docChanged||r.getMeta("__uniqueIDTransaction"))return a;const l=r.doc.lastChild;return!TN({node:l,types:s})}}})]}}),vV=It.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>D4(t,e),redo:()=>({state:t,dispatch:e})=>M4(t,e)}},addProseMirrorPlugins(){return[mV(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),bV=It.create({name:"starterKit",addExtensions(){var t,e,n,s;const r=[];return this.options.bold!==!1&&r.push(qB.configure(this.options.bold)),this.options.blockquote!==!1&&r.push(BB.configure(this.options.blockquote)),this.options.bulletList!==!1&&r.push(g4.configure(this.options.bulletList)),this.options.code!==!1&&r.push(QB.configure(this.options.code)),this.options.codeBlock!==!1&&r.push(ZB.configure(this.options.codeBlock)),this.options.document!==!1&&r.push(YB.configure(this.options.document)),this.options.dropcursor!==!1&&r.push(pV.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&r.push(gV.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&r.push(XB.configure(this.options.hardBreak)),this.options.heading!==!1&&r.push(e_.configure(this.options.heading)),this.options.undoRedo!==!1&&r.push(vV.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&r.push(t_.configure(this.options.horizontalRule)),this.options.italic!==!1&&r.push(a_.configure(this.options.italic)),this.options.listItem!==!1&&r.push(x4.configure(this.options.listItem)),this.options.listKeymap!==!1&&r.push(w4.configure((t=this.options)==null?void 0:t.listKeymap)),this.options.link!==!1&&r.push(p4.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&r.push(S4.configure(this.options.orderedList)),this.options.paragraph!==!1&&r.push(q_.configure(this.options.paragraph)),this.options.strike!==!1&&r.push(Q_.configure(this.options.strike)),this.options.text!==!1&&r.push(G_.configure(this.options.text)),this.options.underline!==!1&&r.push(J_.configure((n=this.options)==null?void 0:n.underline)),this.options.trailingNode!==!1&&r.push(yV.configure((s=this.options)==null?void 0:s.trailingNode)),r}}),jV=bV;const NV=[{key:"{{vorname}}",label:"Vorname"},{key:"{{nachname}}",label:"Nachname"},{key:"{{kundennummer}}",label:"Kundennummer"},{key:"{{anrede}}",label:"Anrede"},{key:"{{email}}",label:"E-Mail"},{key:"{{datum}}",label:"Aktuelles Datum"}];function wV({editor:t}){if(!t)return null;const e=N.useCallback(()=>{const s=t.getAttributes("link").href,r=window.prompt("URL eingeben:",s);if(r!==null){if(r===""){t.chain().focus().extendMarkRange("link").unsetLink().run();return}t.chain().focus().extendMarkRange("link").setLink({href:r}).run()}},[t]),n=s=>`p-1.5 rounded hover:bg-gray-200 transition-colors ${s?"bg-gray-200 text-blue-600":"text-gray-600"}`;return i.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-gray-50",children:[i.jsx("button",{type:"button",onClick:()=>t.chain().focus().toggleBold().run(),className:n(t.isActive("bold")),title:"Fett",children:i.jsx(h5,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().toggleItalic().run(),className:n(t.isActive("italic")),title:"Kursiv",children:i.jsx(C5,{className:"w-4 h-4"})}),i.jsx("div",{className:"w-px h-5 bg-gray-300 mx-1"}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().toggleHeading({level:1}).run(),className:n(t.isActive("heading",{level:1})),title:"Überschrift 1",children:i.jsx(N5,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().toggleHeading({level:2}).run(),className:n(t.isActive("heading",{level:2})),title:"Überschrift 2",children:i.jsx(w5,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().toggleHeading({level:3}).run(),className:n(t.isActive("heading",{level:3})),title:"Überschrift 3",children:i.jsx(k5,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().setParagraph().run(),className:n(t.isActive("paragraph")),title:"Absatz",children:i.jsx(_5,{className:"w-4 h-4"})}),i.jsx("div",{className:"w-px h-5 bg-gray-300 mx-1"}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().toggleBulletList().run(),className:n(t.isActive("bulletList")),title:"Aufzählung",children:i.jsx(T5,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().toggleOrderedList().run(),className:n(t.isActive("orderedList")),title:"Nummerierung",children:i.jsx(M5,{className:"w-4 h-4"})}),i.jsx("div",{className:"w-px h-5 bg-gray-300 mx-1"}),i.jsx("button",{type:"button",onClick:e,className:n(t.isActive("link")),title:"Link",children:i.jsx(D5,{className:"w-4 h-4"})}),i.jsx("div",{className:"w-px h-5 bg-gray-300 mx-1"}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().undo().run(),disabled:!t.can().undo(),className:"p-1.5 rounded hover:bg-gray-200 text-gray-600 disabled:opacity-30",title:"Rückgängig",children:i.jsx(V5,{className:"w-4 h-4"})}),i.jsx("button",{type:"button",onClick:()=>t.chain().focus().redo().run(),disabled:!t.can().redo(),className:"p-1.5 rounded hover:bg-gray-200 text-gray-600 disabled:opacity-30",title:"Wiederherstellen",children:i.jsx(F5,{className:"w-4 h-4"})})]})}function kV(){var h,m;const t=ye(),[e,n]=N.useState(!1),[s,r]=N.useState(!1),{data:a,isLoading:l}=fe({queryKey:["privacy-policy"],queryFn:()=>Mr.getPrivacyPolicy()}),o=G({mutationFn:f=>Mr.updatePrivacyPolicy(f),onSuccess:()=>{t.invalidateQueries({queryKey:["privacy-policy"]}),r(!0),setTimeout(()=>r(!1),2e3)}}),c=OB({extensions:[jV,T_.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}})],content:((h=a==null?void 0:a.data)==null?void 0:h.html)||"",editorProps:{attributes:{class:"prose prose-sm max-w-none p-4 min-h-[400px] focus:outline-none"}}},[(m=a==null?void 0:a.data)==null?void 0:m.html]),d=f=>{c&&c.chain().focus().insertContent(f).run()},u=()=>{c&&o.mutate(c.getHTML())};return l?i.jsx("div",{className:"text-center py-8 text-gray-500",children:"Laden..."}):i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[i.jsx(Me,{to:"/settings",children:i.jsx(I,{variant:"ghost",size:"sm",children:i.jsx(Yn,{className:"w-4 h-4"})})}),i.jsx("h1",{className:"text-2xl font-bold flex-1",children:"Datenschutzerklärung bearbeiten"}),i.jsxs(I,{variant:"secondary",onClick:()=>n(!e),children:[i.jsx(Oe,{className:"w-4 h-4 mr-2"}),e?"Editor":"Vorschau"]}),i.jsxs(I,{onClick:u,disabled:o.isPending,children:[i.jsx(zy,{className:"w-4 h-4 mr-2"}),s?"Gespeichert!":o.isPending?"Speichern...":"Speichern"]})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-6",children:[i.jsx("div",{className:"lg:col-span-3",children:e?i.jsx(Z,{children:i.jsx("div",{className:"prose prose-sm max-w-none p-4",dangerouslySetInnerHTML:{__html:(c==null?void 0:c.getHTML())||""}})}):i.jsxs("div",{className:"border rounded-lg bg-white overflow-hidden",children:[i.jsx(wV,{editor:c}),i.jsx(t4,{editor:c})]})}),i.jsxs("div",{className:"lg:col-span-1",children:[i.jsxs(Z,{title:"Platzhalter",children:[i.jsx("p",{className:"text-xs text-gray-500 mb-3",children:"Klicken Sie auf einen Platzhalter, um ihn an der Cursorposition einzufügen."}),i.jsx("div",{className:"space-y-2",children:NV.map(f=>i.jsxs("button",{onClick:()=>d(f.key),className:"w-full text-left px-3 py-2 text-sm bg-gray-50 border rounded hover:bg-blue-50 hover:border-blue-300 transition-colors",children:[i.jsx("span",{className:"font-mono text-blue-600 text-xs",children:f.key}),i.jsx("br",{}),i.jsx("span",{className:"text-gray-600",children:f.label})]},f.key))})]}),o.isError&&i.jsx("div",{className:"mt-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:"Fehler beim Speichern. Bitte versuchen Sie es erneut."})]})]})]})}function SV({children:t}){const{isAuthenticated:e,isLoading:n}=nt();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:i.jsx("div",{className:"text-gray-500",children:"Laden..."})}):e?i.jsx(i.Fragment,{children:t}):i.jsx(bl,{to:"/login",replace:!0})}function CV({children:t}){const{hasPermission:e,developerMode:n}=nt();return!e("developer:access")||!n?i.jsx(bl,{to:"/",replace:!0}):i.jsx(i.Fragment,{children:t})}function EV(){const{isAuthenticated:t,isLoading:e}=nt();return e?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:i.jsx("div",{className:"text-gray-500",children:"Laden..."})}):i.jsxs(i.Fragment,{children:[i.jsx(l5,{}),i.jsxs(ZM,{children:[i.jsx($e,{path:"/datenschutz/:hash",element:i.jsx(pO,{})}),i.jsx($e,{path:"/login",element:t?i.jsx(bl,{to:"/",replace:!0}):i.jsx(J5,{})}),i.jsxs($e,{path:"/",element:i.jsx(SV,{children:i.jsx(G5,{})}),children:[i.jsx($e,{index:!0,element:i.jsx(Z5,{})}),i.jsx($e,{path:"customers",element:i.jsx(X5,{})}),i.jsx($e,{path:"customers/new",element:i.jsx(W1,{})}),i.jsx($e,{path:"customers/:id",element:i.jsx(lR,{})}),i.jsx($e,{path:"customers/:id/edit",element:i.jsx(W1,{})}),i.jsx($e,{path:"contracts",element:i.jsx(WR,{})}),i.jsx($e,{path:"contracts/cockpit",element:i.jsx(A3,{})}),i.jsx($e,{path:"contracts/new",element:i.jsx(X1,{})}),i.jsx($e,{path:"contracts/:id",element:i.jsx(y3,{})}),i.jsx($e,{path:"contracts/:id/edit",element:i.jsx(X1,{})}),i.jsx($e,{path:"tasks",element:i.jsx(M3,{})}),i.jsx($e,{path:"settings",element:i.jsx(hO,{})}),i.jsx($e,{path:"settings/users",element:i.jsx(dO,{})}),i.jsx($e,{path:"settings/platforms",element:i.jsx(R3,{})}),i.jsx($e,{path:"settings/cancellation-periods",element:i.jsx(L3,{})}),i.jsx($e,{path:"settings/contract-durations",element:i.jsx(z3,{})}),i.jsx($e,{path:"settings/providers",element:i.jsx(B3,{})}),i.jsx($e,{path:"settings/contract-categories",element:i.jsx(H3,{})}),i.jsx($e,{path:"settings/view",element:i.jsx(G3,{})}),i.jsx($e,{path:"settings/portal",element:i.jsx(J3,{})}),i.jsx($e,{path:"settings/deadlines",element:i.jsx(Z3,{})}),i.jsx($e,{path:"settings/email-providers",element:i.jsx(X3,{})}),i.jsx($e,{path:"settings/database-backup",element:i.jsx(eO,{})}),i.jsx($e,{path:"settings/audit-logs",element:i.jsx(iO,{})}),i.jsx($e,{path:"settings/gdpr",element:i.jsx(cO,{})}),i.jsx($e,{path:"settings/privacy-policy",element:i.jsx(kV,{})}),i.jsx($e,{path:"users",element:i.jsx(bl,{to:"/settings/users",replace:!0})}),i.jsx($e,{path:"platforms",element:i.jsx(bl,{to:"/settings/platforms",replace:!0})}),i.jsx($e,{path:"developer/database",element:i.jsx(CV,{children:i.jsx(mO,{})})})]}),i.jsx($e,{path:"*",element:i.jsx(bl,{to:"/",replace:!0})})]})]})}const AV=new LT({defaultOptions:{queries:{retry:1,staleTime:0,gcTime:0,refetchOnMount:"always"}}});pp.createRoot(document.getElementById("root")).render(i.jsx(ut.StrictMode,{children:i.jsx(FT,{client:AV,children:i.jsx(aT,{children:i.jsx(a5,{children:i.jsxs(i5,{children:[i.jsx(EV,{}),i.jsx(DP,{position:"top-right",toastOptions:{duration:4e3,style:{background:"#363636",color:"#fff"},success:{iconTheme:{primary:"#10b981",secondary:"#fff"}},error:{iconTheme:{primary:"#ef4444",secondary:"#fff"}}}})]})})})})})); diff --git a/frontend/dist/assets/index-b8RXSgxB.css b/frontend/dist/assets/index-b8RXSgxB.css deleted file mode 100644 index 021dfd72..00000000 --- a/frontend/dist/assets/index-b8RXSgxB.css +++ /dev/null @@ -1 +0,0 @@ -*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-y-0{top:0;bottom:0}.bottom-4{bottom:1rem}.bottom-6{bottom:1.5rem}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-3{right:.75rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1\/2{top:50%}.top-4{top:1rem}.top-full{top:100%}.z-10{z-index:10}.z-50{z-index:50}.col-span-2{grid-column:span 2 / span 2}.-mx-2{margin-left:-.5rem;margin-right:-.5rem}.-mx-6{margin-left:-1.5rem;margin-right:-1.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.-mb-6{margin-bottom:-1.5rem}.-mb-px{margin-bottom:-1px}.-ml-1{margin-left:-.25rem}.-mt-2{margin-top:-.5rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-10{margin-left:2.5rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-4{margin-left:1rem}.ml-6{margin-left:1.5rem}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mr-4{margin-right:1rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-0\.5{height:.125rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.h-\[85vh\]{height:85vh}.h-full{height:100%}.max-h-40{max-height:10rem}.max-h-48{max-height:12rem}.max-h-80{max-height:20rem}.max-h-96{max-height:24rem}.max-h-\[600px\]{max-height:600px}.max-h-\[60vh\]{max-height:60vh}.max-h-\[90vh\]{max-height:90vh}.min-h-full{min-height:100%}.min-h-screen{min-height:100vh}.w-1\/3{width:33.333333%}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-16{width:4rem}.w-24{width:6rem}.w-28{width:7rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-40{width:10rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-8{width:2rem}.w-\[90vw\]{width:90vw}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-\[200px\]{min-width:200px}.min-w-\[90px\]{min-width:90px}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-\[180px\]{max-width:180px}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-grab{cursor:grab}.cursor-help{cursor:help}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 231 235 / var(--tw-divide-opacity, 1))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-line{white-space:pre-line}.whitespace-pre-wrap{white-space:pre-wrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-l-lg{border-top-left-radius:.5rem;border-bottom-left-radius:.5rem}.rounded-r-lg{border-top-right-radius:.5rem;border-bottom-right-radius:.5rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l-0{border-left-width:0px}.border-l-2{border-left-width:2px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-400{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-300{--tw-border-opacity: 1;border-color:rgb(134 239 172 / var(--tw-border-opacity, 1))}.border-purple-300{--tw-border-opacity: 1;border-color:rgb(216 180 254 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-300{--tw-border-opacity: 1;border-color:rgb(252 165 165 / var(--tw-border-opacity, 1))}.border-red-400{--tw-border-opacity: 1;border-color:rgb(248 113 113 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-600{--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.border-yellow-300{--tw-border-opacity: 1;border-color:rgb(253 224 71 / var(--tw-border-opacity, 1))}.border-l-blue-500{--tw-border-opacity: 1;border-left-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-l-gray-300{--tw-border-opacity: 1;border-left-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-l-gray-400{--tw-border-opacity: 1;border-left-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/20{background-color:#0003}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-50\/50{background-color:#f9fafb80}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-opacity-50{--tw-bg-opacity: .5}.fill-current{fill:currentColor}.\!p-4{padding:1rem!important}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pl-10{padding-left:2.5rem}.pl-3{padding-left:.75rem}.pr-10{padding-right:2.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-2xl{font-size:1.5rem;line-height:2rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.italic{font-style:italic}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-800{--tw-text-opacity: 1;color:rgb(154 52 18 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.line-through{text-decoration-line:line-through}.opacity-0{opacity:0}.opacity-30{opacity:.3}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-blue-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-gray-400{--tw-ring-opacity: 1;--tw-ring-color: rgb(156 163 175 / var(--tw-ring-opacity, 1))}.ring-offset-2{--tw-ring-offset-width: 2px}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}body{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:left-\[2px\]:after{content:var(--tw-content);left:2px}.after\:top-\[2px\]:after{content:var(--tw-content);top:2px}.after\:h-5:after{content:var(--tw-content);height:1.25rem}.after\:w-5:after{content:var(--tw-content);width:1.25rem}.after\:rounded-full:after{content:var(--tw-content);border-radius:9999px}.after\:border:after{content:var(--tw-content);border-width:1px}.after\:border-gray-300:after{content:var(--tw-content);--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.after\:bg-white:after{content:var(--tw-content);--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.after\:transition-all:after{content:var(--tw-content);transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.after\:content-\[\'\'\]:after{--tw-content: "";content:var(--tw-content)}.last\:border-0:last-child{border-width:0px}.last\:border-b-0:last-child{border-bottom-width:0px}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:bg-amber-200:hover{--tw-bg-opacity: 1;background-color:rgb(253 230 138 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-100:hover{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-50:hover{--tw-bg-opacity: .5}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-800:hover{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-red-600:hover{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.hover\:text-red-700:hover{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.hover\:text-yellow-600:hover{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-red-500:focus{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-gray-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(107 114 128 / var(--tw-ring-opacity, 1))}.focus\:ring-purple-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(168 85 247 / var(--tw-ring-opacity, 1))}.focus\:ring-red-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.group\/subtask:hover .group-hover\/subtask\:opacity-100,.group:hover .group-hover\:opacity-100{opacity:1}.peer:checked~.peer-checked\:bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.peer:checked~.peer-checked\:after\:translate-x-full:after{content:var(--tw-content);--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.peer:checked~.peer-checked\:after\:border-white:after{content:var(--tw-content);--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.peer:focus~.peer-focus\:outline-none{outline:2px solid transparent;outline-offset:2px}.peer:focus~.peer-focus\:ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.peer:focus~.peer-focus\:ring-blue-300{--tw-ring-opacity: 1;--tw-ring-color: rgb(147 197 253 / var(--tw-ring-opacity, 1))}@media (min-width: 640px){.sm\:w-auto{width:auto}}@media (min-width: 768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:col-span-1{grid-column:span 1 / span 1}.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:col-span-3{grid-column:span 3 / span 3}.lg\:block{display:block}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}} diff --git a/frontend/dist/assets/index-dzAFnrZs.css b/frontend/dist/assets/index-dzAFnrZs.css new file mode 100644 index 00000000..a0b6dd35 --- /dev/null +++ b/frontend/dist/assets/index-dzAFnrZs.css @@ -0,0 +1 @@ +*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-y-0{top:0;bottom:0}.bottom-4{bottom:1rem}.bottom-6{bottom:1.5rem}.left-3{left:.75rem}.left-4{left:1rem}.right-0{right:0}.right-3{right:.75rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1\/2{top:50%}.top-4{top:1rem}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.col-span-2{grid-column:span 2 / span 2}.-mx-2{margin-left:-.5rem;margin-right:-.5rem}.-mx-6{margin-left:-1.5rem;margin-right:-1.5rem}.mx-1{margin-left:.25rem;margin-right:.25rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.-mb-6{margin-bottom:-1.5rem}.-mb-px{margin-bottom:-1px}.-ml-1{margin-left:-.25rem}.-mt-2{margin-top:-.5rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-10{margin-left:2.5rem}.ml-2{margin-left:.5rem}.ml-3{margin-left:.75rem}.ml-4{margin-left:1rem}.ml-6{margin-left:1.5rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mr-4{margin-right:1rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-0\.5{height:.125rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-64{height:16rem}.h-8{height:2rem}.h-\[85vh\]{height:85vh}.h-full{height:100%}.max-h-40{max-height:10rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-80{max-height:20rem}.max-h-96{max-height:24rem}.max-h-\[600px\]{max-height:600px}.max-h-\[60vh\]{max-height:60vh}.max-h-\[90vh\]{max-height:90vh}.min-h-\[400px\]{min-height:400px}.min-h-full{min-height:100%}.min-h-screen{min-height:100vh}.w-1\/3{width:33.333333%}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-16{width:4rem}.w-24{width:6rem}.w-28{width:7rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-4{width:1rem}.w-40{width:10rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-56{width:14rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-8{width:2rem}.w-\[90vw\]{width:90vw}.w-full{width:100%}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-\[200px\]{min-width:200px}.min-w-\[90px\]{min-width:90px}.max-w-2xl{max-width:42rem}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-\[180px\]{max-width:180px}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-grab{cursor:grab}.cursor-help{cursor:help}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-200>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(229 231 235 / var(--tw-divide-opacity, 1))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-line{white-space:pre-line}.whitespace-pre-wrap{white-space:pre-wrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.rounded-l-lg{border-top-left-radius:.5rem;border-bottom-left-radius:.5rem}.rounded-r-lg{border-top-right-radius:.5rem;border-bottom-right-radius:.5rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-b-2{border-bottom-width:2px}.border-l-0{border-left-width:0px}.border-l-2{border-left-width:2px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-300{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-300{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-400{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-green-300{--tw-border-opacity: 1;border-color:rgb(134 239 172 / var(--tw-border-opacity, 1))}.border-purple-300{--tw-border-opacity: 1;border-color:rgb(216 180 254 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-red-300{--tw-border-opacity: 1;border-color:rgb(252 165 165 / var(--tw-border-opacity, 1))}.border-red-400{--tw-border-opacity: 1;border-color:rgb(248 113 113 / var(--tw-border-opacity, 1))}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-600{--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-yellow-200{--tw-border-opacity: 1;border-color:rgb(254 240 138 / var(--tw-border-opacity, 1))}.border-yellow-300{--tw-border-opacity: 1;border-color:rgb(253 224 71 / var(--tw-border-opacity, 1))}.border-l-blue-500{--tw-border-opacity: 1;border-left-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-l-gray-300{--tw-border-opacity: 1;border-left-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-l-gray-400{--tw-border-opacity: 1;border-left-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/20{background-color:#0003}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-50\/50{background-color:#f9fafb80}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-200{--tw-bg-opacity: 1;background-color:rgb(254 202 202 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-teal-100{--tw-bg-opacity: 1;background-color:rgb(204 251 241 / var(--tw-bg-opacity, 1))}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-100{--tw-bg-opacity: 1;background-color:rgb(254 249 195 / var(--tw-bg-opacity, 1))}.bg-yellow-50{--tw-bg-opacity: 1;background-color:rgb(254 252 232 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-opacity-50{--tw-bg-opacity: .5}.fill-current{fill:currentColor}.\!p-4{padding:1rem!important}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pl-10{padding-left:2.5rem}.pl-3{padding-left:.75rem}.pr-10{padding-right:2.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-2xl{font-size:1.5rem;line-height:2rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.italic{font-style:italic}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-500{--tw-text-opacity: 1;color:rgb(249 115 22 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-orange-800{--tw-text-opacity: 1;color:rgb(154 52 18 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-800{--tw-text-opacity: 1;color:rgb(107 33 168 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity, 1))}.text-teal-800{--tw-text-opacity: 1;color:rgb(17 94 89 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-yellow-600{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.text-yellow-700{--tw-text-opacity: 1;color:rgb(161 98 7 / var(--tw-text-opacity, 1))}.text-yellow-800{--tw-text-opacity: 1;color:rgb(133 77 14 / var(--tw-text-opacity, 1))}.line-through{text-decoration-line:line-through}.opacity-0{opacity:0}.opacity-30{opacity:.3}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-blue-500{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.ring-gray-400{--tw-ring-opacity: 1;--tw-ring-color: rgb(156 163 175 / var(--tw-ring-opacity, 1))}.ring-offset-2{--tw-ring-offset-width: 2px}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}body{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1));--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:left-\[2px\]:after{content:var(--tw-content);left:2px}.after\:top-\[2px\]:after{content:var(--tw-content);top:2px}.after\:h-5:after{content:var(--tw-content);height:1.25rem}.after\:w-5:after{content:var(--tw-content);width:1.25rem}.after\:rounded-full:after{content:var(--tw-content);border-radius:9999px}.after\:border:after{content:var(--tw-content);border-width:1px}.after\:border-gray-300:after{content:var(--tw-content);--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.after\:bg-white:after{content:var(--tw-content);--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.after\:transition-all:after{content:var(--tw-content);transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.after\:content-\[\'\'\]:after{--tw-content: "";content:var(--tw-content)}.last\:border-0:last-child{border-width:0px}.last\:border-b-0:last-child{border-bottom-width:0px}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:bg-amber-200:hover{--tw-bg-opacity: 1;background-color:rgb(253 230 138 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-300:hover{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-100:hover{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-opacity-50:hover{--tw-bg-opacity: .5}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-blue-800:hover{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-red-600:hover{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.hover\:text-red-700:hover{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.hover\:text-yellow-600:hover{--tw-text-opacity: 1;color:rgb(202 138 4 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:border-red-500:focus{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.focus\:border-transparent:focus{border-color:transparent}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-gray-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(107 114 128 / var(--tw-ring-opacity, 1))}.focus\:ring-green-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(34 197 94 / var(--tw-ring-opacity, 1))}.focus\:ring-purple-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(168 85 247 / var(--tw-ring-opacity, 1))}.focus\:ring-red-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(239 68 68 / var(--tw-ring-opacity, 1))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.group\/subtask:hover .group-hover\/subtask\:opacity-100,.group:hover .group-hover\:opacity-100{opacity:1}.peer:checked~.peer-checked\:bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.peer:checked~.peer-checked\:bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.peer:checked~.peer-checked\:after\:translate-x-full:after{content:var(--tw-content);--tw-translate-x: 100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.peer:checked~.peer-checked\:after\:border-white:after{content:var(--tw-content);--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.peer:focus~.peer-focus\:outline-none{outline:2px solid transparent;outline-offset:2px}.peer:focus~.peer-focus\:ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.peer:focus~.peer-focus\:ring-blue-300{--tw-ring-opacity: 1;--tw-ring-color: rgb(147 197 253 / var(--tw-ring-opacity, 1))}@media (min-width: 640px){.sm\:w-auto{width:auto}}@media (min-width: 768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}@media (min-width: 1024px){.lg\:col-span-1{grid-column:span 1 / span 1}.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:col-span-3{grid-column:span 3 / span 3}.lg\:block{display:block}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}} diff --git a/frontend/dist/index.html b/frontend/dist/index.html index 4e578634..8df3cb32 100644 --- a/frontend/dist/index.html +++ b/frontend/dist/index.html @@ -5,8 +5,8 @@ OpenCRM - - + +
diff --git a/frontend/node_modules/.bin/markdown-it b/frontend/node_modules/.bin/markdown-it new file mode 120000 index 00000000..8a641084 --- /dev/null +++ b/frontend/node_modules/.bin/markdown-it @@ -0,0 +1 @@ +../markdown-it/bin/markdown-it.mjs \ No newline at end of file diff --git a/frontend/node_modules/.package-lock.json b/frontend/node_modules/.package-lock.json index 58af1c44..aefb3470 100644 --- a/frontend/node_modules/.package-lock.json +++ b/frontend/node_modules/.package-lock.json @@ -295,6 +295,31 @@ "node": ">=12" } }, + "node_modules/@floating-ui/core": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.4.tgz", + "integrity": "sha512-C3HlIdsBxszvm5McXlB8PeOEWfBhcGBTZGkGlWc2U0KFY5IwG5OQEuQ8rq52DZmcHDlPLd+YFBK+cZcytwIFWg==", + "optional": true, + "dependencies": { + "@floating-ui/utils": "^0.2.10" + } + }, + "node_modules/@floating-ui/dom": { + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.5.tgz", + "integrity": "sha512-N0bD2kIPInNHUHehXhMke1rBGs1dwqvC9O9KYMyyjK7iXt7GAhnro7UlcuYcGdS/yYOlq0MAVgrow8IbWJwyqg==", + "optional": true, + "dependencies": { + "@floating-ui/core": "^1.7.4", + "@floating-ui/utils": "^0.2.10" + } + }, + "node_modules/@floating-ui/utils": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.10.tgz", + "integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==", + "optional": true + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -375,6 +400,11 @@ "node": ">= 8" } }, + "node_modules/@remirror/core-constants": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@remirror/core-constants/-/core-constants-3.0.0.tgz", + "integrity": "sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg==" + }, "node_modules/@remix-run/router": { "version": "1.23.2", "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz", @@ -439,6 +469,412 @@ "react": "^18 || ^19" } }, + "node_modules/@tiptap/core": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.19.0.tgz", + "integrity": "sha512-bpqELwPW+DG8gWiD8iiFtSl4vIBooG5uVJod92Qxn3rA9nFatyXRr4kNbMJmOZ66ezUvmCjXVe/5/G4i5cyzKA==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-blockquote": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-blockquote/-/extension-blockquote-3.19.0.tgz", + "integrity": "sha512-y3UfqY9KD5XwWz3ndiiJ089Ij2QKeiXy/g1/tlAN/F1AaWsnkHEHMLxCP1BIqmMpwsX7rZjMLN7G5Lp7c9682A==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-bold": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-bold/-/extension-bold-3.19.0.tgz", + "integrity": "sha512-UZgb1d0XK4J/JRIZ7jW+s4S6KjuEDT2z1PPM6ugcgofgJkWQvRZelCPbmtSFd3kwsD+zr9UPVgTh9YIuGQ8t+Q==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-bubble-menu": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.19.0.tgz", + "integrity": "sha512-klNVIYGCdznhFkrRokzGd6cwzoi8J7E5KbuOfZBwFwhMKZhlz/gJfKmYg9TJopeUhrr2Z9yHgWTk8dh/YIJCdQ==", + "optional": true, + "dependencies": { + "@floating-ui/dom": "^1.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-bullet-list": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-bullet-list/-/extension-bullet-list-3.19.0.tgz", + "integrity": "sha512-F9uNnqd0xkJbMmRxVI5RuVxwB9JaCH/xtRqOUNQZnRBt7IdAElCY+Dvb4hMCtiNv+enGM/RFGJuFHR9TxmI7rw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-code": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-code/-/extension-code-3.19.0.tgz", + "integrity": "sha512-2kqqQIXBXj2Or+4qeY3WoE7msK+XaHKL6EKOcKlOP2BW8eYqNTPzNSL+PfBDQ3snA7ljZQkTs/j4GYDj90vR1A==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-code-block": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-code-block/-/extension-code-block-3.19.0.tgz", + "integrity": "sha512-b/2qR+tMn8MQb+eaFYgVk4qXnLNkkRYmwELQ8LEtEDQPxa5Vl7J3eu8+4OyoIFhZrNDZvvoEp80kHMCP8sI6rg==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-document": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.19.0.tgz", + "integrity": "sha512-AOf0kHKSFO0ymjVgYSYDncRXTITdTcrj1tqxVazrmO60KNl1Rc2dAggDvIVTEBy5NvceF0scc7q3sE/5ZtVV7A==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-dropcursor": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-3.19.0.tgz", + "integrity": "sha512-sf3dEZXiLvsGqVK2maUIzXY6qtYYCvBumag7+VPTMGQ0D4hiZ1X/4ukt4+6VXDg5R2WP1CoIt/QvUetUjWNhbQ==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extensions": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-floating-menu": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.19.0.tgz", + "integrity": "sha512-JaoEkVRkt+Slq3tySlIsxnMnCjS0L5n1CA1hctjLy0iah8edetj3XD5mVv5iKqDzE+LIjF4nwLRRVKJPc8hFBg==", + "optional": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@floating-ui/dom": "^1.0.0", + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-gapcursor": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.19.0.tgz", + "integrity": "sha512-w7DACS4oSZaDWjz7gropZHPc9oXqC9yERZTcjWxyORuuIh1JFf0TRYspleK+OK28plK/IftojD/yUDn1MTRhvA==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extensions": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-hard-break": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-hard-break/-/extension-hard-break-3.19.0.tgz", + "integrity": "sha512-lAmQraYhPS5hafvCl74xDB5+bLuNwBKIEsVoim35I0sDJj5nTrfhaZgMJ91VamMvT+6FF5f1dvBlxBxAWa8jew==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-heading": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-heading/-/extension-heading-3.19.0.tgz", + "integrity": "sha512-uLpLlfyp086WYNOc0ekm1gIZNlEDfmzOhKzB0Hbyi6jDagTS+p9mxUNYeYOn9jPUxpFov43+Wm/4E24oY6B+TQ==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-horizontal-rule": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.19.0.tgz", + "integrity": "sha512-iqUHmgMGhMgYGwG6L/4JdelVQ5Mstb4qHcgTGd/4dkcUOepILvhdxajPle7OEdf9sRgjQO6uoAU5BVZVC26+ng==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-italic": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-3.19.0.tgz", + "integrity": "sha512-6GffxOnS/tWyCbDkirWNZITiXRta9wrCmrfa4rh+v32wfaOL1RRQNyqo9qN6Wjyl1R42Js+yXTzTTzZsOaLMYA==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-link": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.19.0.tgz", + "integrity": "sha512-HEGDJnnCPfr7KWu7Dsq+eRRe/mBCsv6DuI+7fhOCLDJjjKzNgrX2abbo/zG3D/4lCVFaVb+qawgJubgqXR/Smw==", + "dependencies": { + "linkifyjs": "^4.3.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-list": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-list/-/extension-list-3.19.0.tgz", + "integrity": "sha512-N6nKbFB2VwMsPlCw67RlAtYSK48TAsAUgjnD+vd3ieSlIufdQnLXDFUP6hFKx9mwoUVUgZGz02RA6bkxOdYyTw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-list-item": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-3.19.0.tgz", + "integrity": "sha512-VsSKuJz4/Tb6ZmFkXqWpDYkRzmaLTyE6dNSEpNmUpmZ32sMqo58mt11/huADNwfBFB0Ve7siH/VnFNIJYY3xvg==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-list-keymap": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-list-keymap/-/extension-list-keymap-3.19.0.tgz", + "integrity": "sha512-bxgmAgA3RzBGA0GyTwS2CC1c+QjkJJq9hC+S6PSOWELGRiTbwDN3MANksFXLjntkTa0N5fOnL27vBHtMStURqw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-ordered-list": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-ordered-list/-/extension-ordered-list-3.19.0.tgz", + "integrity": "sha512-cxGsINquwHYE1kmhAcLNLHAofmoDEG6jbesR5ybl7tU5JwtKVO7S/xZatll2DU1dsDAXWPWEeeMl4e/9svYjCg==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-paragraph": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-paragraph/-/extension-paragraph-3.19.0.tgz", + "integrity": "sha512-xWa6gj82l5+AzdYyrSk9P4ynySaDzg/SlR1FarXE5yPXibYzpS95IWaVR0m2Qaz7Rrk+IiYOTGxGRxcHLOelNg==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-strike": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-3.19.0.tgz", + "integrity": "sha512-xYpabHsv7PccLUBQaP8AYiFCnYbx6P93RHPd0lgNwhdOjYFd931Zy38RyoxPHAgbYVmhf1iyx7lpuLtBnhS5dA==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-text": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.19.0.tgz", + "integrity": "sha512-K95+SnbZy0h6hNFtfy23n8t/nOcTFEf69In9TSFVVmwn/Nwlke+IfiESAkqbt1/7sKJeegRXYO7WzFEmFl9Q/g==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extension-underline": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extension-underline/-/extension-underline-3.19.0.tgz", + "integrity": "sha512-800MGEWfG49j10wQzAFiW/ele1HT04MamcL8iyuPNu7ZbjbGN2yknvdrJlRy7hZlzIrVkZMr/1tz62KN33VHIw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0" + } + }, + "node_modules/@tiptap/extensions": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.19.0.tgz", + "integrity": "sha512-ZmGUhLbMWaGqnJh2Bry+6V4M6gMpUDYo4D1xNux5Gng/E/eYtc+PMxMZ/6F7tNTAuujLBOQKj6D+4SsSm457jw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0" + } + }, + "node_modules/@tiptap/pm": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.19.0.tgz", + "integrity": "sha512-789zcnM4a8OWzvbD2DL31d0wbSm9BVeO/R7PLQwLIGysDI3qzrcclyZ8yhqOEVuvPitRRwYLq+mY14jz7kY4cw==", + "dependencies": { + "prosemirror-changeset": "^2.3.0", + "prosemirror-collab": "^1.3.1", + "prosemirror-commands": "^1.6.2", + "prosemirror-dropcursor": "^1.8.1", + "prosemirror-gapcursor": "^1.3.2", + "prosemirror-history": "^1.4.1", + "prosemirror-inputrules": "^1.4.0", + "prosemirror-keymap": "^1.2.2", + "prosemirror-markdown": "^1.13.1", + "prosemirror-menu": "^1.2.4", + "prosemirror-model": "^1.24.1", + "prosemirror-schema-basic": "^1.2.3", + "prosemirror-schema-list": "^1.5.0", + "prosemirror-state": "^1.4.3", + "prosemirror-tables": "^1.6.4", + "prosemirror-trailing-node": "^3.0.0", + "prosemirror-transform": "^1.10.2", + "prosemirror-view": "^1.38.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + } + }, + "node_modules/@tiptap/react": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/react/-/react-3.19.0.tgz", + "integrity": "sha512-GQQMUUXMpNd8tRjc1jDK3tDRXFugJO7C928EqmeBcBzTKDrFIJ3QUoZKEPxUNb6HWhZ2WL7q00fiMzsv4DNSmg==", + "dependencies": { + "@types/use-sync-external-store": "^0.0.6", + "fast-equals": "^5.3.3", + "use-sync-external-store": "^1.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "optionalDependencies": { + "@tiptap/extension-bubble-menu": "^3.19.0", + "@tiptap/extension-floating-menu": "^3.19.0" + }, + "peerDependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/pm": "^3.19.0", + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "@types/react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/@tiptap/starter-kit": { + "version": "3.19.0", + "resolved": "https://registry.npmjs.org/@tiptap/starter-kit/-/starter-kit-3.19.0.tgz", + "integrity": "sha512-dTCkHEz+Y8ADxX7h+xvl6caAj+3nII/wMB1rTQchSuNKqJTOrzyUsCWm094+IoZmLT738wANE0fRIgziNHs/ug==", + "dependencies": { + "@tiptap/core": "^3.19.0", + "@tiptap/extension-blockquote": "^3.19.0", + "@tiptap/extension-bold": "^3.19.0", + "@tiptap/extension-bullet-list": "^3.19.0", + "@tiptap/extension-code": "^3.19.0", + "@tiptap/extension-code-block": "^3.19.0", + "@tiptap/extension-document": "^3.19.0", + "@tiptap/extension-dropcursor": "^3.19.0", + "@tiptap/extension-gapcursor": "^3.19.0", + "@tiptap/extension-hard-break": "^3.19.0", + "@tiptap/extension-heading": "^3.19.0", + "@tiptap/extension-horizontal-rule": "^3.19.0", + "@tiptap/extension-italic": "^3.19.0", + "@tiptap/extension-link": "^3.19.0", + "@tiptap/extension-list": "^3.19.0", + "@tiptap/extension-list-item": "^3.19.0", + "@tiptap/extension-list-keymap": "^3.19.0", + "@tiptap/extension-ordered-list": "^3.19.0", + "@tiptap/extension-paragraph": "^3.19.0", + "@tiptap/extension-strike": "^3.19.0", + "@tiptap/extension-text": "^3.19.0", + "@tiptap/extension-underline": "^3.19.0", + "@tiptap/extensions": "^3.19.0", + "@tiptap/pm": "^3.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + } + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -486,17 +922,34 @@ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", "dev": true }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==" + }, + "node_modules/@types/markdown-it": { + "version": "14.1.2", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", + "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==" + }, "node_modules/@types/prop-types": { "version": "15.7.15", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", - "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", - "dev": true + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==" }, "node_modules/@types/react": { "version": "18.3.27", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz", "integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==", - "dev": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.2.2" @@ -506,11 +959,15 @@ "version": "18.3.7", "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz", "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", - "dev": true, "peerDependencies": { "@types/react": "^18.0.0" } }, + "node_modules/@types/use-sync-external-store": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", + "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==" + }, "node_modules/@vitejs/plugin-react": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", @@ -556,6 +1013,11 @@ "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", "dev": true }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -776,6 +1238,11 @@ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "dev": true }, + "node_modules/crelt": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", + "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==" + }, "node_modules/cssesc": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", @@ -849,6 +1316,17 @@ "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", "dev": true }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -937,6 +1415,25 @@ "node": ">=6" } }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fast-equals": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.0.tgz", + "integrity": "sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/fast-glob": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", @@ -1265,6 +1762,19 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, + "node_modules/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, + "node_modules/linkifyjs": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.2.tgz", + "integrity": "sha512-NT1CJtq3hHIreOianA8aSXn6Cw0JzYOuDQbOrSPe7gqFnCpKP++MQe3ODgO3oh2GJFORkAAdqredOa60z63GbA==" + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -1293,6 +1803,22 @@ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc" } }, + "node_modules/markdown-it": { + "version": "14.1.1", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.1.tgz", + "integrity": "sha512-BuU2qnTti9YKgK5N+IeMubp14ZUKUUw7yeJbkjtosvHiP0AZ5c8IAgEMk79D0eC8F23r4Ac/q8cAIFdm2FtyoA==", + "dependencies": { + "argparse": "^2.0.1", + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -1301,6 +1827,11 @@ "node": ">= 0.4" } }, + "node_modules/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==" + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -1410,6 +1941,11 @@ "node": ">= 6" } }, + "node_modules/orderedmap": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz", + "integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==" + }, "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", @@ -1608,11 +2144,196 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "dev": true }, + "node_modules/prosemirror-changeset": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.4.0.tgz", + "integrity": "sha512-LvqH2v7Q2SF6yxatuPP2e8vSUKS/L+xAU7dPDC4RMyHMhZoGDfBC74mYuyYF4gLqOEG758wajtyhNnsTkuhvng==", + "dependencies": { + "prosemirror-transform": "^1.0.0" + } + }, + "node_modules/prosemirror-collab": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/prosemirror-collab/-/prosemirror-collab-1.3.1.tgz", + "integrity": "sha512-4SnynYR9TTYaQVXd/ieUvsVV4PDMBzrq2xPUWutHivDuOshZXqQ5rGbZM84HEaXKbLdItse7weMGOUdDVcLKEQ==", + "dependencies": { + "prosemirror-state": "^1.0.0" + } + }, + "node_modules/prosemirror-commands": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz", + "integrity": "sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==", + "dependencies": { + "prosemirror-model": "^1.0.0", + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.10.2" + } + }, + "node_modules/prosemirror-dropcursor": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.2.tgz", + "integrity": "sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==", + "dependencies": { + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.1.0", + "prosemirror-view": "^1.1.0" + } + }, + "node_modules/prosemirror-gapcursor": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.0.tgz", + "integrity": "sha512-z00qvurSdCEWUIulij/isHaqu4uLS8r/Fi61IbjdIPJEonQgggbJsLnstW7Lgdk4zQ68/yr6B6bf7sJXowIgdQ==", + "dependencies": { + "prosemirror-keymap": "^1.0.0", + "prosemirror-model": "^1.0.0", + "prosemirror-state": "^1.0.0", + "prosemirror-view": "^1.0.0" + } + }, + "node_modules/prosemirror-history": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.0.tgz", + "integrity": "sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==", + "dependencies": { + "prosemirror-state": "^1.2.2", + "prosemirror-transform": "^1.0.0", + "prosemirror-view": "^1.31.0", + "rope-sequence": "^1.3.0" + } + }, + "node_modules/prosemirror-inputrules": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz", + "integrity": "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==", + "dependencies": { + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.0.0" + } + }, + "node_modules/prosemirror-keymap": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz", + "integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==", + "dependencies": { + "prosemirror-state": "^1.0.0", + "w3c-keyname": "^2.2.0" + } + }, + "node_modules/prosemirror-markdown": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/prosemirror-markdown/-/prosemirror-markdown-1.13.4.tgz", + "integrity": "sha512-D98dm4cQ3Hs6EmjK500TdAOew4Z03EV71ajEFiWra3Upr7diytJsjF4mPV2dW+eK5uNectiRj0xFxYI9NLXDbw==", + "dependencies": { + "@types/markdown-it": "^14.0.0", + "markdown-it": "^14.0.0", + "prosemirror-model": "^1.25.0" + } + }, + "node_modules/prosemirror-menu": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/prosemirror-menu/-/prosemirror-menu-1.2.5.tgz", + "integrity": "sha512-qwXzynnpBIeg1D7BAtjOusR+81xCp53j7iWu/IargiRZqRjGIlQuu1f3jFi+ehrHhWMLoyOQTSRx/IWZJqOYtQ==", + "dependencies": { + "crelt": "^1.0.0", + "prosemirror-commands": "^1.0.0", + "prosemirror-history": "^1.0.0", + "prosemirror-state": "^1.0.0" + } + }, + "node_modules/prosemirror-model": { + "version": "1.25.4", + "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.4.tgz", + "integrity": "sha512-PIM7E43PBxKce8OQeezAs9j4TP+5yDpZVbuurd1h5phUxEKIu+G2a+EUZzIC5nS1mJktDJWzbqS23n1tsAf5QA==", + "dependencies": { + "orderedmap": "^2.0.0" + } + }, + "node_modules/prosemirror-schema-basic": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/prosemirror-schema-basic/-/prosemirror-schema-basic-1.2.4.tgz", + "integrity": "sha512-ELxP4TlX3yr2v5rM7Sb70SqStq5NvI15c0j9j/gjsrO5vaw+fnnpovCLEGIcpeGfifkuqJwl4fon6b+KdrODYQ==", + "dependencies": { + "prosemirror-model": "^1.25.0" + } + }, + "node_modules/prosemirror-schema-list": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz", + "integrity": "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==", + "dependencies": { + "prosemirror-model": "^1.0.0", + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.7.3" + } + }, + "node_modules/prosemirror-state": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz", + "integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==", + "dependencies": { + "prosemirror-model": "^1.0.0", + "prosemirror-transform": "^1.0.0", + "prosemirror-view": "^1.27.0" + } + }, + "node_modules/prosemirror-tables": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz", + "integrity": "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==", + "dependencies": { + "prosemirror-keymap": "^1.2.3", + "prosemirror-model": "^1.25.4", + "prosemirror-state": "^1.4.4", + "prosemirror-transform": "^1.10.5", + "prosemirror-view": "^1.41.4" + } + }, + "node_modules/prosemirror-trailing-node": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/prosemirror-trailing-node/-/prosemirror-trailing-node-3.0.0.tgz", + "integrity": "sha512-xiun5/3q0w5eRnGYfNlW1uU9W6x5MoFKWwq/0TIRgt09lv7Hcser2QYV8t4muXbEr+Fwo0geYn79Xs4GKywrRQ==", + "dependencies": { + "@remirror/core-constants": "3.0.0", + "escape-string-regexp": "^4.0.0" + }, + "peerDependencies": { + "prosemirror-model": "^1.22.1", + "prosemirror-state": "^1.4.2", + "prosemirror-view": "^1.33.8" + } + }, + "node_modules/prosemirror-transform": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.11.0.tgz", + "integrity": "sha512-4I7Ce4KpygXb9bkiPS3hTEk4dSHorfRw8uI0pE8IhxlK2GXsqv5tIA7JUSxtSu7u8APVOTtbUBxTmnHIxVkIJw==", + "dependencies": { + "prosemirror-model": "^1.21.0" + } + }, + "node_modules/prosemirror-view": { + "version": "1.41.6", + "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.41.6.tgz", + "integrity": "sha512-mxpcDG4hNQa/CPtzxjdlir5bJFDlm0/x5nGBbStB2BWX+XOQ9M8ekEG+ojqB5BcVu2Rc80/jssCMZzSstJuSYg==", + "dependencies": { + "prosemirror-model": "^1.20.0", + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.1.0" + } + }, "node_modules/proxy-from-env": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "engines": { + "node": ">=6" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -1821,6 +2542,11 @@ "fsevents": "~2.3.2" } }, + "node_modules/rope-sequence": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz", + "integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==" + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -2038,6 +2764,11 @@ "node": ">=14.17" } }, + "node_modules/uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==" + }, "node_modules/update-browserslist-db": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", @@ -2068,6 +2799,14 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/use-sync-external-store": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", + "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -2133,6 +2872,11 @@ } } }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/frontend/node_modules/.vite/deps/@tiptap_extension-link.js b/frontend/node_modules/.vite/deps/@tiptap_extension-link.js new file mode 100644 index 00000000..257ac8ce --- /dev/null +++ b/frontend/node_modules/.vite/deps/@tiptap_extension-link.js @@ -0,0 +1,15 @@ +import { + Link, + index_default, + isAllowedUri, + pasteRegex +} from "./chunk-MX7X7RGK.js"; +import "./chunk-YRIELJS7.js"; +import "./chunk-4MBMRILA.js"; +export { + Link, + index_default as default, + isAllowedUri, + pasteRegex +}; +//# sourceMappingURL=@tiptap_extension-link.js.map diff --git a/frontend/node_modules/.vite/deps/@tiptap_extension-link.js.map b/frontend/node_modules/.vite/deps/@tiptap_extension-link.js.map new file mode 100644 index 00000000..98652118 --- /dev/null +++ b/frontend/node_modules/.vite/deps/@tiptap_extension-link.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": [], + "sourcesContent": [], + "mappings": "", + "names": [] +} diff --git a/frontend/node_modules/.vite/deps/@tiptap_react.js b/frontend/node_modules/.vite/deps/@tiptap_react.js new file mode 100644 index 00000000..0419c47c --- /dev/null +++ b/frontend/node_modules/.vite/deps/@tiptap_react.js @@ -0,0 +1,1948 @@ +import { + CommandManager, + Editor, + Extendable, + Extension, + Fragment6, + InputRule, + MappablePosition, + Mark, + MarkView, + Node3, + NodePos, + NodeView, + PasteRule, + ResizableNodeView, + ResizableNodeview, + Tracker, + callOrReturn, + canInsertNode, + combineTransactionSteps, + commands_exports, + createAtomBlockMarkdownSpec, + createBlockMarkdownSpec, + createChainableState, + createDocument, + createInlineMarkdownSpec, + createMappablePosition, + createNodeFromContent, + createStyleTag, + defaultBlockAt, + deleteProps, + elementFromString, + escapeForRegEx, + extensions_exports, + findChildren, + findChildrenInRange, + findDuplicates, + findParentNode, + findParentNodeClosestToPos, + flattenExtensions, + fromString, + generateHTML, + generateJSON, + generateText, + getAttributes, + getAttributesFromExtensions, + getChangedRanges, + getDebugJSON, + getExtensionField, + getHTMLFromFragment, + getMarkAttributes, + getMarkRange, + getMarkType, + getMarksBetween, + getNodeAtPosition, + getNodeAttributes, + getNodeType, + getRenderedAttributes, + getSchema, + getSchemaByResolvedExtensions, + getSchemaTypeByName, + getSchemaTypeNameByName, + getSplittedAttributes, + getText, + getTextBetween, + getTextContentFromNodes, + getTextSerializersFromSchema, + getUpdatedPosition, + h, + injectExtensionAttributesToParseRule, + inputRulesPlugin, + isActive, + isAndroid, + isAtEndOfNode, + isAtStartOfNode, + isEmptyObject, + isExtensionRulesEnabled, + isFirefox, + isFunction, + isList, + isMacOS, + isMarkActive, + isNodeActive, + isNodeEmpty, + isNodeSelection, + isNumber, + isPlainObject, + isRegExp, + isSafari, + isString, + isTextSelection, + isiOS, + markInputRule, + markPasteRule, + markdown_exports, + mergeAttributes, + mergeDeep, + minMax, + nodeInputRule, + nodePasteRule, + objectIncludes, + parseAttributes, + parseIndentedBlocks, + pasteRulesPlugin, + posToDOMRect, + removeDuplicates, + renderNestedMarkdownContent, + resolveExtensions, + resolveFocusPosition, + rewriteUnknownContent, + selectionToInsertionEnd, + serializeAttributes, + sortExtensions, + splitExtensions, + textInputRule, + textPasteRule, + textblockTypeInputRule, + updateMarkViewAttributes, + wrappingInputRule +} from "./chunk-YRIELJS7.js"; +import { + require_react_dom +} from "./chunk-WERSD76P.js"; +import { + require_jsx_runtime +} from "./chunk-S77I6LSE.js"; +import { + require_react +} from "./chunk-3TFVT2CW.js"; +import { + __commonJS, + __toESM +} from "./chunk-4MBMRILA.js"; + +// node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js +var require_use_sync_external_store_shim_development = __commonJS({ + "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js"(exports) { + "use strict"; + (function() { + function is(x, y) { + return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; + } + function useSyncExternalStore$2(subscribe, getSnapshot) { + didWarnOld18Alpha || void 0 === React2.startTransition || (didWarnOld18Alpha = true, console.error( + "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." + )); + var value = getSnapshot(); + if (!didWarnUncachedGetSnapshot) { + var cachedValue = getSnapshot(); + objectIs(value, cachedValue) || (console.error( + "The result of getSnapshot should be cached to avoid an infinite loop" + ), didWarnUncachedGetSnapshot = true); + } + cachedValue = useState3({ + inst: { value, getSnapshot } + }); + var inst = cachedValue[0].inst, forceUpdate = cachedValue[1]; + useLayoutEffect2( + function() { + inst.value = value; + inst.getSnapshot = getSnapshot; + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + }, + [subscribe, value, getSnapshot] + ); + useEffect3( + function() { + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + return subscribe(function() { + checkIfSnapshotChanged(inst) && forceUpdate({ inst }); + }); + }, + [subscribe] + ); + useDebugValue3(value); + return value; + } + function checkIfSnapshotChanged(inst) { + var latestGetSnapshot = inst.getSnapshot; + inst = inst.value; + try { + var nextValue = latestGetSnapshot(); + return !objectIs(inst, nextValue); + } catch (error) { + return true; + } + } + function useSyncExternalStore$1(subscribe, getSnapshot) { + return getSnapshot(); + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var React2 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is, useState3 = React2.useState, useEffect3 = React2.useEffect, useLayoutEffect2 = React2.useLayoutEffect, useDebugValue3 = React2.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2; + exports.useSyncExternalStore = void 0 !== React2.useSyncExternalStore ? React2.useSyncExternalStore : shim; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + } +}); + +// node_modules/use-sync-external-store/shim/index.js +var require_shim = __commonJS({ + "node_modules/use-sync-external-store/shim/index.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_use_sync_external_store_shim_development(); + } + } +}); + +// node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js +var require_with_selector_development = __commonJS({ + "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js"(exports) { + "use strict"; + (function() { + function is(x, y) { + return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var React2 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore3 = shim.useSyncExternalStore, useRef2 = React2.useRef, useEffect3 = React2.useEffect, useMemo3 = React2.useMemo, useDebugValue3 = React2.useDebugValue; + exports.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { + var instRef = useRef2(null); + if (null === instRef.current) { + var inst = { hasValue: false, value: null }; + instRef.current = inst; + } else inst = instRef.current; + instRef = useMemo3( + function() { + function memoizedSelector(nextSnapshot) { + if (!hasMemo) { + hasMemo = true; + memoizedSnapshot = nextSnapshot; + nextSnapshot = selector(nextSnapshot); + if (void 0 !== isEqual && inst.hasValue) { + var currentSelection = inst.value; + if (isEqual(currentSelection, nextSnapshot)) + return memoizedSelection = currentSelection; + } + return memoizedSelection = nextSnapshot; + } + currentSelection = memoizedSelection; + if (objectIs(memoizedSnapshot, nextSnapshot)) + return currentSelection; + var nextSelection = selector(nextSnapshot); + if (void 0 !== isEqual && isEqual(currentSelection, nextSelection)) + return memoizedSnapshot = nextSnapshot, currentSelection; + memoizedSnapshot = nextSnapshot; + return memoizedSelection = nextSelection; + } + var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot; + return [ + function() { + return memoizedSelector(getSnapshot()); + }, + null === maybeGetServerSnapshot ? void 0 : function() { + return memoizedSelector(maybeGetServerSnapshot()); + } + ]; + }, + [getSnapshot, getServerSnapshot, selector, isEqual] + ); + var value = useSyncExternalStore3(subscribe, instRef[0], instRef[1]); + useEffect3( + function() { + inst.hasValue = true; + inst.value = value; + }, + [value] + ); + useDebugValue3(value); + return value; + }; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + } +}); + +// node_modules/use-sync-external-store/shim/with-selector.js +var require_with_selector = __commonJS({ + "node_modules/use-sync-external-store/shim/with-selector.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_with_selector_development(); + } + } +}); + +// node_modules/@tiptap/react/dist/index.js +var import_react = __toESM(require_react()); +var import_react2 = __toESM(require_react()); +var import_react_dom = __toESM(require_react_dom()); +var import_shim = __toESM(require_shim()); +var import_jsx_runtime = __toESM(require_jsx_runtime()); +var import_react3 = __toESM(require_react()); +var import_shim2 = __toESM(require_shim()); + +// node_modules/fast-equals/dist/es/index.mjs +var { getOwnPropertyNames, getOwnPropertySymbols } = Object; +var { hasOwnProperty } = Object.prototype; +function combineComparators(comparatorA, comparatorB) { + return function isEqual(a, b, state) { + return comparatorA(a, b, state) && comparatorB(a, b, state); + }; +} +function createIsCircular(areItemsEqual) { + return function isCircular(a, b, state) { + if (!a || !b || typeof a !== "object" || typeof b !== "object") { + return areItemsEqual(a, b, state); + } + const { cache } = state; + const cachedA = cache.get(a); + const cachedB = cache.get(b); + if (cachedA && cachedB) { + return cachedA === b && cachedB === a; + } + cache.set(a, b); + cache.set(b, a); + const result = areItemsEqual(a, b, state); + cache.delete(a); + cache.delete(b); + return result; + }; +} +function getShortTag(value) { + return value != null ? value[Symbol.toStringTag] : void 0; +} +function getStrictProperties(object) { + return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object)); +} +var hasOwn = ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + Object.hasOwn || ((object, property) => hasOwnProperty.call(object, property)) +); +function sameValueZeroEqual(a, b) { + return a === b || !a && !b && a !== a && b !== b; +} +var PREACT_VNODE = "__v"; +var PREACT_OWNER = "__o"; +var REACT_OWNER = "_owner"; +var { getOwnPropertyDescriptor, keys } = Object; +function areArrayBuffersEqual(a, b) { + return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b)); +} +function areArraysEqual(a, b, state) { + let index = a.length; + if (b.length !== index) { + return false; + } + while (index-- > 0) { + if (!state.equals(a[index], b[index], index, index, a, b, state)) { + return false; + } + } + return true; +} +function areDataViewsEqual(a, b) { + return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)); +} +function areDatesEqual(a, b) { + return sameValueZeroEqual(a.getTime(), b.getTime()); +} +function areErrorsEqual(a, b) { + return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack; +} +function areFunctionsEqual(a, b) { + return a === b; +} +function areMapsEqual(a, b, state) { + const size = a.size; + if (size !== b.size) { + return false; + } + if (!size) { + return true; + } + const matchedIndices = new Array(size); + const aIterable = a.entries(); + let aResult; + let bResult; + let index = 0; + while (aResult = aIterable.next()) { + if (aResult.done) { + break; + } + const bIterable = b.entries(); + let hasMatch = false; + let matchIndex = 0; + while (bResult = bIterable.next()) { + if (bResult.done) { + break; + } + if (matchedIndices[matchIndex]) { + matchIndex++; + continue; + } + const aEntry = aResult.value; + const bEntry = bResult.value; + if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state) && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) { + hasMatch = matchedIndices[matchIndex] = true; + break; + } + matchIndex++; + } + if (!hasMatch) { + return false; + } + index++; + } + return true; +} +var areNumbersEqual = sameValueZeroEqual; +function areObjectsEqual(a, b, state) { + const properties = keys(a); + let index = properties.length; + if (keys(b).length !== index) { + return false; + } + while (index-- > 0) { + if (!isPropertyEqual(a, b, state, properties[index])) { + return false; + } + } + return true; +} +function areObjectsEqualStrict(a, b, state) { + const properties = getStrictProperties(a); + let index = properties.length; + if (getStrictProperties(b).length !== index) { + return false; + } + let property; + let descriptorA; + let descriptorB; + while (index-- > 0) { + property = properties[index]; + if (!isPropertyEqual(a, b, state, property)) { + return false; + } + descriptorA = getOwnPropertyDescriptor(a, property); + descriptorB = getOwnPropertyDescriptor(b, property); + if ((descriptorA || descriptorB) && (!descriptorA || !descriptorB || descriptorA.configurable !== descriptorB.configurable || descriptorA.enumerable !== descriptorB.enumerable || descriptorA.writable !== descriptorB.writable)) { + return false; + } + } + return true; +} +function arePrimitiveWrappersEqual(a, b) { + return sameValueZeroEqual(a.valueOf(), b.valueOf()); +} +function areRegExpsEqual(a, b) { + return a.source === b.source && a.flags === b.flags; +} +function areSetsEqual(a, b, state) { + const size = a.size; + if (size !== b.size) { + return false; + } + if (!size) { + return true; + } + const matchedIndices = new Array(size); + const aIterable = a.values(); + let aResult; + let bResult; + while (aResult = aIterable.next()) { + if (aResult.done) { + break; + } + const bIterable = b.values(); + let hasMatch = false; + let matchIndex = 0; + while (bResult = bIterable.next()) { + if (bResult.done) { + break; + } + if (!matchedIndices[matchIndex] && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) { + hasMatch = matchedIndices[matchIndex] = true; + break; + } + matchIndex++; + } + if (!hasMatch) { + return false; + } + } + return true; +} +function areTypedArraysEqual(a, b) { + let index = a.byteLength; + if (b.byteLength !== index || a.byteOffset !== b.byteOffset) { + return false; + } + while (index-- > 0) { + if (a[index] !== b[index]) { + return false; + } + } + return true; +} +function areUrlsEqual(a, b) { + return a.hostname === b.hostname && a.pathname === b.pathname && a.protocol === b.protocol && a.port === b.port && a.hash === b.hash && a.username === b.username && a.password === b.password; +} +function isPropertyEqual(a, b, state, property) { + if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE) && (a.$$typeof || b.$$typeof)) { + return true; + } + return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state); +} +var ARRAY_BUFFER_TAG = "[object ArrayBuffer]"; +var ARGUMENTS_TAG = "[object Arguments]"; +var BOOLEAN_TAG = "[object Boolean]"; +var DATA_VIEW_TAG = "[object DataView]"; +var DATE_TAG = "[object Date]"; +var ERROR_TAG = "[object Error]"; +var MAP_TAG = "[object Map]"; +var NUMBER_TAG = "[object Number]"; +var OBJECT_TAG = "[object Object]"; +var REG_EXP_TAG = "[object RegExp]"; +var SET_TAG = "[object Set]"; +var STRING_TAG = "[object String]"; +var TYPED_ARRAY_TAGS = { + "[object Int8Array]": true, + "[object Uint8Array]": true, + "[object Uint8ClampedArray]": true, + "[object Int16Array]": true, + "[object Uint16Array]": true, + "[object Int32Array]": true, + "[object Uint32Array]": true, + "[object Float16Array]": true, + "[object Float32Array]": true, + "[object Float64Array]": true, + "[object BigInt64Array]": true, + "[object BigUint64Array]": true +}; +var URL_TAG = "[object URL]"; +var toString = Object.prototype.toString; +function createEqualityComparator({ areArrayBuffersEqual: areArrayBuffersEqual2, areArraysEqual: areArraysEqual2, areDataViewsEqual: areDataViewsEqual2, areDatesEqual: areDatesEqual2, areErrorsEqual: areErrorsEqual2, areFunctionsEqual: areFunctionsEqual2, areMapsEqual: areMapsEqual2, areNumbersEqual: areNumbersEqual2, areObjectsEqual: areObjectsEqual2, arePrimitiveWrappersEqual: arePrimitiveWrappersEqual2, areRegExpsEqual: areRegExpsEqual2, areSetsEqual: areSetsEqual2, areTypedArraysEqual: areTypedArraysEqual2, areUrlsEqual: areUrlsEqual2, unknownTagComparators }) { + return function comparator(a, b, state) { + if (a === b) { + return true; + } + if (a == null || b == null) { + return false; + } + const type = typeof a; + if (type !== typeof b) { + return false; + } + if (type !== "object") { + if (type === "number") { + return areNumbersEqual2(a, b, state); + } + if (type === "function") { + return areFunctionsEqual2(a, b, state); + } + return false; + } + const constructor = a.constructor; + if (constructor !== b.constructor) { + return false; + } + if (constructor === Object) { + return areObjectsEqual2(a, b, state); + } + if (Array.isArray(a)) { + return areArraysEqual2(a, b, state); + } + if (constructor === Date) { + return areDatesEqual2(a, b, state); + } + if (constructor === RegExp) { + return areRegExpsEqual2(a, b, state); + } + if (constructor === Map) { + return areMapsEqual2(a, b, state); + } + if (constructor === Set) { + return areSetsEqual2(a, b, state); + } + const tag = toString.call(a); + if (tag === DATE_TAG) { + return areDatesEqual2(a, b, state); + } + if (tag === REG_EXP_TAG) { + return areRegExpsEqual2(a, b, state); + } + if (tag === MAP_TAG) { + return areMapsEqual2(a, b, state); + } + if (tag === SET_TAG) { + return areSetsEqual2(a, b, state); + } + if (tag === OBJECT_TAG) { + return typeof a.then !== "function" && typeof b.then !== "function" && areObjectsEqual2(a, b, state); + } + if (tag === URL_TAG) { + return areUrlsEqual2(a, b, state); + } + if (tag === ERROR_TAG) { + return areErrorsEqual2(a, b, state); + } + if (tag === ARGUMENTS_TAG) { + return areObjectsEqual2(a, b, state); + } + if (TYPED_ARRAY_TAGS[tag]) { + return areTypedArraysEqual2(a, b, state); + } + if (tag === ARRAY_BUFFER_TAG) { + return areArrayBuffersEqual2(a, b, state); + } + if (tag === DATA_VIEW_TAG) { + return areDataViewsEqual2(a, b, state); + } + if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) { + return arePrimitiveWrappersEqual2(a, b, state); + } + if (unknownTagComparators) { + let unknownTagComparator = unknownTagComparators[tag]; + if (!unknownTagComparator) { + const shortTag = getShortTag(a); + if (shortTag) { + unknownTagComparator = unknownTagComparators[shortTag]; + } + } + if (unknownTagComparator) { + return unknownTagComparator(a, b, state); + } + } + return false; + }; +} +function createEqualityComparatorConfig({ circular, createCustomConfig, strict }) { + let config = { + areArrayBuffersEqual, + areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual, + areDataViewsEqual, + areDatesEqual, + areErrorsEqual, + areFunctionsEqual, + areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual, + areNumbersEqual, + areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual, + arePrimitiveWrappersEqual, + areRegExpsEqual, + areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual, + areTypedArraysEqual: strict ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict) : areTypedArraysEqual, + areUrlsEqual, + unknownTagComparators: void 0 + }; + if (createCustomConfig) { + config = Object.assign({}, config, createCustomConfig(config)); + } + if (circular) { + const areArraysEqual2 = createIsCircular(config.areArraysEqual); + const areMapsEqual2 = createIsCircular(config.areMapsEqual); + const areObjectsEqual2 = createIsCircular(config.areObjectsEqual); + const areSetsEqual2 = createIsCircular(config.areSetsEqual); + config = Object.assign({}, config, { + areArraysEqual: areArraysEqual2, + areMapsEqual: areMapsEqual2, + areObjectsEqual: areObjectsEqual2, + areSetsEqual: areSetsEqual2 + }); + } + return config; +} +function createInternalEqualityComparator(compare) { + return function(a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) { + return compare(a, b, state); + }; +} +function createIsEqual({ circular, comparator, createState, equals, strict }) { + if (createState) { + return function isEqual(a, b) { + const { cache = circular ? /* @__PURE__ */ new WeakMap() : void 0, meta } = createState(); + return comparator(a, b, { + cache, + equals, + meta, + strict + }); + }; + } + if (circular) { + return function isEqual(a, b) { + return comparator(a, b, { + cache: /* @__PURE__ */ new WeakMap(), + equals, + meta: void 0, + strict + }); + }; + } + const state = { + cache: void 0, + equals, + meta: void 0, + strict + }; + return function isEqual(a, b) { + return comparator(a, b, state); + }; +} +var deepEqual = createCustomEqual(); +var strictDeepEqual = createCustomEqual({ strict: true }); +var circularDeepEqual = createCustomEqual({ circular: true }); +var strictCircularDeepEqual = createCustomEqual({ + circular: true, + strict: true +}); +var shallowEqual = createCustomEqual({ + createInternalComparator: () => sameValueZeroEqual +}); +var strictShallowEqual = createCustomEqual({ + strict: true, + createInternalComparator: () => sameValueZeroEqual +}); +var circularShallowEqual = createCustomEqual({ + circular: true, + createInternalComparator: () => sameValueZeroEqual +}); +var strictCircularShallowEqual = createCustomEqual({ + circular: true, + createInternalComparator: () => sameValueZeroEqual, + strict: true +}); +function createCustomEqual(options = {}) { + const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false } = options; + const config = createEqualityComparatorConfig(options); + const comparator = createEqualityComparator(config); + const equals = createCustomInternalComparator ? createCustomInternalComparator(comparator) : createInternalEqualityComparator(comparator); + return createIsEqual({ circular, comparator, createState, equals, strict }); +} + +// node_modules/@tiptap/react/dist/index.js +var import_react4 = __toESM(require_react()); +var import_with_selector = __toESM(require_with_selector()); +var import_jsx_runtime2 = __toESM(require_jsx_runtime()); +var import_react5 = __toESM(require_react()); +var import_jsx_runtime3 = __toESM(require_jsx_runtime()); +var import_react6 = __toESM(require_react()); +var import_jsx_runtime4 = __toESM(require_jsx_runtime()); +var import_react7 = __toESM(require_react()); +var import_react8 = __toESM(require_react()); +var import_react_dom2 = __toESM(require_react_dom()); +var import_jsx_runtime5 = __toESM(require_jsx_runtime()); +var import_jsx_runtime6 = __toESM(require_jsx_runtime()); +var import_react9 = __toESM(require_react()); +var import_jsx_runtime7 = __toESM(require_jsx_runtime()); +var import_react10 = __toESM(require_react()); +var import_jsx_runtime8 = __toESM(require_jsx_runtime()); +var mergeRefs = (...refs) => { + return (node) => { + refs.forEach((ref) => { + if (typeof ref === "function") { + ref(node); + } else if (ref) { + ; + ref.current = node; + } + }); + }; +}; +var Portals = ({ contentComponent }) => { + const renderers = (0, import_shim.useSyncExternalStore)( + contentComponent.subscribe, + contentComponent.getSnapshot, + contentComponent.getServerSnapshot + ); + return (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: Object.values(renderers) }); +}; +function getInstance() { + const subscribers = /* @__PURE__ */ new Set(); + let renderers = {}; + return { + /** + * Subscribe to the editor instance's changes. + */ + subscribe(callback) { + subscribers.add(callback); + return () => { + subscribers.delete(callback); + }; + }, + getSnapshot() { + return renderers; + }, + getServerSnapshot() { + return renderers; + }, + /** + * Adds a new NodeView Renderer to the editor. + */ + setRenderer(id, renderer) { + renderers = { + ...renderers, + [id]: import_react_dom.default.createPortal(renderer.reactElement, renderer.element, id) + }; + subscribers.forEach((subscriber) => subscriber()); + }, + /** + * Removes a NodeView Renderer from the editor. + */ + removeRenderer(id) { + const nextRenderers = { ...renderers }; + delete nextRenderers[id]; + renderers = nextRenderers; + subscribers.forEach((subscriber) => subscriber()); + } + }; +} +var PureEditorContent = class extends import_react2.default.Component { + constructor(props) { + var _a; + super(props); + this.editorContentRef = import_react2.default.createRef(); + this.initialized = false; + this.state = { + hasContentComponentInitialized: Boolean((_a = props.editor) == null ? void 0 : _a.contentComponent) + }; + } + componentDidMount() { + this.init(); + } + componentDidUpdate() { + this.init(); + } + init() { + var _a; + const editor = this.props.editor; + if (editor && !editor.isDestroyed && ((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) { + if (editor.contentComponent) { + return; + } + const element = this.editorContentRef.current; + element.append(...editor.view.dom.parentNode.childNodes); + editor.setOptions({ + element + }); + editor.contentComponent = getInstance(); + if (!this.state.hasContentComponentInitialized) { + this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => { + this.setState((prevState) => { + if (!prevState.hasContentComponentInitialized) { + return { + hasContentComponentInitialized: true + }; + } + return prevState; + }); + if (this.unsubscribeToContentComponent) { + this.unsubscribeToContentComponent(); + } + }); + } + editor.createNodeViews(); + this.initialized = true; + } + } + componentWillUnmount() { + var _a; + const editor = this.props.editor; + if (!editor) { + return; + } + this.initialized = false; + if (!editor.isDestroyed) { + editor.view.setProps({ + nodeViews: {} + }); + } + if (this.unsubscribeToContentComponent) { + this.unsubscribeToContentComponent(); + } + editor.contentComponent = null; + try { + if (!((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) { + return; + } + const newElement = document.createElement("div"); + newElement.append(...editor.view.dom.parentNode.childNodes); + editor.setOptions({ + element: newElement + }); + } catch { + } + } + render() { + const { editor, innerRef, ...rest } = this.props; + return (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [ + (0, import_jsx_runtime.jsx)("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }), + (editor == null ? void 0 : editor.contentComponent) && (0, import_jsx_runtime.jsx)(Portals, { contentComponent: editor.contentComponent }) + ] }); + } +}; +var EditorContentWithKey = (0, import_react2.forwardRef)( + (props, ref) => { + const key = import_react2.default.useMemo(() => { + return Math.floor(Math.random() * 4294967295).toString(); + }, [props.editor]); + return import_react2.default.createElement(PureEditorContent, { + key, + innerRef: ref, + ...props + }); + } +); +var EditorContent = import_react2.default.memo(EditorContentWithKey); +var useIsomorphicLayoutEffect = typeof window !== "undefined" ? import_react4.useLayoutEffect : import_react4.useEffect; +var EditorStateManager = class { + constructor(initialEditor) { + this.transactionNumber = 0; + this.lastTransactionNumber = 0; + this.subscribers = /* @__PURE__ */ new Set(); + this.editor = initialEditor; + this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }; + this.getSnapshot = this.getSnapshot.bind(this); + this.getServerSnapshot = this.getServerSnapshot.bind(this); + this.watch = this.watch.bind(this); + this.subscribe = this.subscribe.bind(this); + } + /** + * Get the current editor instance. + */ + getSnapshot() { + if (this.transactionNumber === this.lastTransactionNumber) { + return this.lastSnapshot; + } + this.lastTransactionNumber = this.transactionNumber; + this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }; + return this.lastSnapshot; + } + /** + * Always disable the editor on the server-side. + */ + getServerSnapshot() { + return { editor: null, transactionNumber: 0 }; + } + /** + * Subscribe to the editor instance's changes. + */ + subscribe(callback) { + this.subscribers.add(callback); + return () => { + this.subscribers.delete(callback); + }; + } + /** + * Watch the editor instance for changes. + */ + watch(nextEditor) { + this.editor = nextEditor; + if (this.editor) { + const fn = () => { + this.transactionNumber += 1; + this.subscribers.forEach((callback) => callback()); + }; + const currentEditor = this.editor; + currentEditor.on("transaction", fn); + return () => { + currentEditor.off("transaction", fn); + }; + } + return void 0; + } +}; +function useEditorState(options) { + var _a; + const [editorStateManager] = (0, import_react4.useState)(() => new EditorStateManager(options.editor)); + const selectedState = (0, import_with_selector.useSyncExternalStoreWithSelector)( + editorStateManager.subscribe, + editorStateManager.getSnapshot, + editorStateManager.getServerSnapshot, + options.selector, + (_a = options.equalityFn) != null ? _a : deepEqual + ); + useIsomorphicLayoutEffect(() => { + return editorStateManager.watch(options.editor); + }, [options.editor, editorStateManager]); + (0, import_react4.useDebugValue)(selectedState); + return selectedState; +} +var isDev = true; +var isSSR = typeof window === "undefined"; +var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next); +var EditorInstanceManager = class _EditorInstanceManager { + constructor(options) { + this.editor = null; + this.subscriptions = /* @__PURE__ */ new Set(); + this.isComponentMounted = false; + this.previousDeps = null; + this.instanceId = ""; + this.options = options; + this.subscriptions = /* @__PURE__ */ new Set(); + this.setEditor(this.getInitialEditor()); + this.scheduleDestroy(); + this.getEditor = this.getEditor.bind(this); + this.getServerSnapshot = this.getServerSnapshot.bind(this); + this.subscribe = this.subscribe.bind(this); + this.refreshEditorInstance = this.refreshEditorInstance.bind(this); + this.scheduleDestroy = this.scheduleDestroy.bind(this); + this.onRender = this.onRender.bind(this); + this.createEditor = this.createEditor.bind(this); + } + setEditor(editor) { + this.editor = editor; + this.instanceId = Math.random().toString(36).slice(2, 9); + this.subscriptions.forEach((cb) => cb()); + } + getInitialEditor() { + if (this.options.current.immediatelyRender === void 0) { + if (isSSR || isNext) { + if (isDev) { + throw new Error( + "Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches." + ); + } + return null; + } + return this.createEditor(); + } + if (this.options.current.immediatelyRender && isSSR && isDev) { + throw new Error( + "Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches." + ); + } + if (this.options.current.immediatelyRender) { + return this.createEditor(); + } + return null; + } + /** + * Create a new editor instance. And attach event listeners. + */ + createEditor() { + const optionsToApply = { + ...this.options.current, + // Always call the most recent version of the callback function by default + onBeforeCreate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onBeforeCreate) == null ? void 0 : _b.call(_a, ...args); + }, + onBlur: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onBlur) == null ? void 0 : _b.call(_a, ...args); + }, + onCreate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onCreate) == null ? void 0 : _b.call(_a, ...args); + }, + onDestroy: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onDestroy) == null ? void 0 : _b.call(_a, ...args); + }, + onFocus: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onFocus) == null ? void 0 : _b.call(_a, ...args); + }, + onSelectionUpdate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onSelectionUpdate) == null ? void 0 : _b.call(_a, ...args); + }, + onTransaction: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onTransaction) == null ? void 0 : _b.call(_a, ...args); + }, + onUpdate: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onUpdate) == null ? void 0 : _b.call(_a, ...args); + }, + onContentError: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onContentError) == null ? void 0 : _b.call(_a, ...args); + }, + onDrop: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onDrop) == null ? void 0 : _b.call(_a, ...args); + }, + onPaste: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onPaste) == null ? void 0 : _b.call(_a, ...args); + }, + onDelete: (...args) => { + var _a, _b; + return (_b = (_a = this.options.current).onDelete) == null ? void 0 : _b.call(_a, ...args); + } + }; + const editor = new Editor(optionsToApply); + return editor; + } + /** + * Get the current editor instance. + */ + getEditor() { + return this.editor; + } + /** + * Always disable the editor on the server-side. + */ + getServerSnapshot() { + return null; + } + /** + * Subscribe to the editor instance's changes. + */ + subscribe(onStoreChange) { + this.subscriptions.add(onStoreChange); + return () => { + this.subscriptions.delete(onStoreChange); + }; + } + static compareOptions(a, b) { + return Object.keys(a).every((key) => { + if ([ + "onCreate", + "onBeforeCreate", + "onDestroy", + "onUpdate", + "onTransaction", + "onFocus", + "onBlur", + "onSelectionUpdate", + "onContentError", + "onDrop", + "onPaste" + ].includes(key)) { + return true; + } + if (key === "extensions" && a.extensions && b.extensions) { + if (a.extensions.length !== b.extensions.length) { + return false; + } + return a.extensions.every((extension, index) => { + var _a; + if (extension !== ((_a = b.extensions) == null ? void 0 : _a[index])) { + return false; + } + return true; + }); + } + if (a[key] !== b[key]) { + return false; + } + return true; + }); + } + /** + * On each render, we will create, update, or destroy the editor instance. + * @param deps The dependencies to watch for changes + * @returns A cleanup function + */ + onRender(deps) { + return () => { + this.isComponentMounted = true; + clearTimeout(this.scheduledDestructionTimeout); + if (this.editor && !this.editor.isDestroyed && deps.length === 0) { + if (!_EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) { + this.editor.setOptions({ + ...this.options.current, + editable: this.editor.isEditable + }); + } + } else { + this.refreshEditorInstance(deps); + } + return () => { + this.isComponentMounted = false; + this.scheduleDestroy(); + }; + }; + } + /** + * Recreate the editor instance if the dependencies have changed. + */ + refreshEditorInstance(deps) { + if (this.editor && !this.editor.isDestroyed) { + if (this.previousDeps === null) { + this.previousDeps = deps; + return; + } + const depsAreEqual = this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index]); + if (depsAreEqual) { + return; + } + } + if (this.editor && !this.editor.isDestroyed) { + this.editor.destroy(); + } + this.setEditor(this.createEditor()); + this.previousDeps = deps; + } + /** + * Schedule the destruction of the editor instance. + * This will only destroy the editor if it was not mounted on the next tick. + * This is to avoid destroying the editor instance when it's actually still mounted. + */ + scheduleDestroy() { + const currentInstanceId = this.instanceId; + const currentEditor = this.editor; + this.scheduledDestructionTimeout = setTimeout(() => { + if (this.isComponentMounted && this.instanceId === currentInstanceId) { + if (currentEditor) { + currentEditor.setOptions(this.options.current); + } + return; + } + if (currentEditor && !currentEditor.isDestroyed) { + currentEditor.destroy(); + if (this.instanceId === currentInstanceId) { + this.setEditor(null); + } + } + }, 1); + } +}; +function useEditor(options = {}, deps = []) { + const mostRecentOptions = (0, import_react3.useRef)(options); + mostRecentOptions.current = options; + const [instanceManager] = (0, import_react3.useState)(() => new EditorInstanceManager(mostRecentOptions)); + const editor = (0, import_shim2.useSyncExternalStore)( + instanceManager.subscribe, + instanceManager.getEditor, + instanceManager.getServerSnapshot + ); + (0, import_react3.useDebugValue)(editor); + (0, import_react3.useEffect)(instanceManager.onRender(deps)); + useEditorState({ + editor, + selector: ({ transactionNumber }) => { + if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === void 0) { + return null; + } + if (options.immediatelyRender && transactionNumber === 0) { + return 0; + } + return transactionNumber + 1; + } + }); + return editor; +} +var EditorContext = (0, import_react.createContext)({ + editor: null +}); +var EditorConsumer = EditorContext.Consumer; +var useCurrentEditor = () => (0, import_react.useContext)(EditorContext); +function EditorProvider({ + children, + slotAfter, + slotBefore, + editorContainerProps = {}, + ...editorOptions +}) { + const editor = useEditor(editorOptions); + const contextValue = (0, import_react.useMemo)(() => ({ editor }), [editor]); + if (!editor) { + return null; + } + return (0, import_jsx_runtime2.jsxs)(EditorContext.Provider, { value: contextValue, children: [ + slotBefore, + (0, import_jsx_runtime2.jsx)(EditorConsumer, { children: ({ editor: currentEditor }) => (0, import_jsx_runtime2.jsx)(EditorContent, { editor: currentEditor, ...editorContainerProps }) }), + children, + slotAfter + ] }); +} +var ReactNodeViewContext = (0, import_react5.createContext)({ + onDragStart: () => { + }, + nodeViewContentChildren: void 0, + nodeViewContentRef: () => { + } +}); +var ReactNodeViewContentProvider = ({ children, content }) => { + return (0, import_react5.createElement)(ReactNodeViewContext.Provider, { value: { nodeViewContentChildren: content } }, children); +}; +var useReactNodeView = () => (0, import_react5.useContext)(ReactNodeViewContext); +function NodeViewContent({ + as: Tag = "div", + ...props +}) { + const { nodeViewContentRef, nodeViewContentChildren } = useReactNodeView(); + return ( + // @ts-ignore + (0, import_jsx_runtime3.jsx)( + Tag, + { + ...props, + ref: nodeViewContentRef, + "data-node-view-content": "", + style: { + whiteSpace: "pre-wrap", + ...props.style + }, + children: nodeViewContentChildren + } + ) + ); +} +var NodeViewWrapper = import_react6.default.forwardRef((props, ref) => { + const { onDragStart } = useReactNodeView(); + const Tag = props.as || "div"; + return ( + // @ts-ignore + (0, import_jsx_runtime4.jsx)( + Tag, + { + ...props, + ref, + "data-node-view-wrapper": "", + onDragStart, + style: { + whiteSpace: "normal", + ...props.style + } + } + ) + ); +}); +function isClassComponent(Component) { + return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent); +} +function isForwardRefComponent(Component) { + return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.forward_ref)" || Component.$$typeof.description === "react.forward_ref")); +} +function isMemoComponent(Component) { + return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.memo)" || Component.$$typeof.description === "react.memo")); +} +function canReceiveRef(Component) { + if (isClassComponent(Component)) { + return true; + } + if (isForwardRefComponent(Component)) { + return true; + } + if (isMemoComponent(Component)) { + const wrappedComponent = Component.type; + if (wrappedComponent) { + return isClassComponent(wrappedComponent) || isForwardRefComponent(wrappedComponent); + } + } + return false; +} +function isReact19Plus() { + try { + if (import_react8.version) { + const majorVersion = parseInt(import_react8.version.split(".")[0], 10); + return majorVersion >= 19; + } + } catch { + } + return false; +} +var ReactRenderer = class { + /** + * Immediately creates element and renders the provided React component. + */ + constructor(component, { editor, props = {}, as = "div", className = "" }) { + this.ref = null; + this.destroyed = false; + this.id = Math.floor(Math.random() * 4294967295).toString(); + this.component = component; + this.editor = editor; + this.props = props; + this.element = document.createElement(as); + this.element.classList.add("react-renderer"); + if (className) { + this.element.classList.add(...className.split(" ")); + } + if (this.editor.isInitialized) { + (0, import_react_dom2.flushSync)(() => { + this.render(); + }); + } else { + queueMicrotask(() => { + if (this.destroyed) { + return; + } + this.render(); + }); + } + } + /** + * Render the React component. + */ + render() { + var _a; + if (this.destroyed) { + return; + } + const Component = this.component; + const props = this.props; + const editor = this.editor; + const isReact19 = isReact19Plus(); + const componentCanReceiveRef = canReceiveRef(Component); + const elementProps = { ...props }; + if (elementProps.ref && !(isReact19 || componentCanReceiveRef)) { + delete elementProps.ref; + } + if (!elementProps.ref && (isReact19 || componentCanReceiveRef)) { + elementProps.ref = (ref) => { + this.ref = ref; + }; + } + this.reactElement = (0, import_jsx_runtime5.jsx)(Component, { ...elementProps }); + (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.setRenderer(this.id, this); + } + /** + * Re-renders the React component with new props. + */ + updateProps(props = {}) { + if (this.destroyed) { + return; + } + this.props = { + ...this.props, + ...props + }; + this.render(); + } + /** + * Destroy the React component. + */ + destroy() { + var _a; + this.destroyed = true; + const editor = this.editor; + (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.removeRenderer(this.id); + try { + if (this.element && this.element.parentNode) { + this.element.parentNode.removeChild(this.element); + } + } catch { + } + } + /** + * Update the attributes of the element that holds the React component. + */ + updateAttributes(attributes) { + Object.keys(attributes).forEach((key) => { + this.element.setAttribute(key, attributes[key]); + }); + } +}; +var ReactMarkViewContext = import_react7.default.createContext({ + markViewContentRef: () => { + } +}); +var MarkViewContent = (props) => { + const { as: Tag = "span", ...rest } = props; + const { markViewContentRef } = import_react7.default.useContext(ReactMarkViewContext); + return ( + // @ts-ignore + (0, import_jsx_runtime6.jsx)(Tag, { ...rest, ref: markViewContentRef, "data-mark-view-content": "" }) + ); +}; +var ReactMarkView = class extends MarkView { + constructor(component, props, options) { + super(component, props, options); + const { as = "span", attrs, className = "" } = options || {}; + const componentProps = { ...props, updateAttributes: this.updateAttributes.bind(this) }; + this.contentDOMElement = document.createElement("span"); + const markViewContentRef = (el) => { + if (el && !el.contains(this.contentDOMElement)) { + el.appendChild(this.contentDOMElement); + } + }; + const context = { + markViewContentRef + }; + const ReactMarkViewProvider = import_react7.default.memo((componentProps2) => { + return (0, import_jsx_runtime6.jsx)(ReactMarkViewContext.Provider, { value: context, children: import_react7.default.createElement(component, componentProps2) }); + }); + ReactMarkViewProvider.displayName = "ReactMarkView"; + this.renderer = new ReactRenderer(ReactMarkViewProvider, { + editor: props.editor, + props: componentProps, + as, + className: `mark-${props.mark.type.name} ${className}`.trim() + }); + if (attrs) { + this.renderer.updateAttributes(attrs); + } + } + get dom() { + return this.renderer.element; + } + get contentDOM() { + return this.contentDOMElement; + } +}; +function ReactMarkViewRenderer(component, options = {}) { + return (props) => new ReactMarkView(component, props, options); +} +var ReactNodeView = class extends NodeView { + constructor(component, props, options) { + super(component, props, options); + this.selectionRafId = null; + this.cachedExtensionWithSyncedStorage = null; + if (!this.node.isLeaf) { + if (this.options.contentDOMElementTag) { + this.contentDOMElement = document.createElement(this.options.contentDOMElementTag); + } else { + this.contentDOMElement = document.createElement(this.node.isInline ? "span" : "div"); + } + this.contentDOMElement.dataset.nodeViewContentReact = ""; + this.contentDOMElement.dataset.nodeViewWrapper = ""; + this.contentDOMElement.style.whiteSpace = "inherit"; + const contentTarget = this.dom.querySelector("[data-node-view-content]"); + if (!contentTarget) { + return; + } + contentTarget.appendChild(this.contentDOMElement); + } + } + /** + * Returns a proxy of the extension that redirects storage access to the editor's mutable storage. + * This preserves the original prototype chain (instanceof checks, methods like configure/extend work). + * Cached to avoid proxy creation on every update. + */ + get extensionWithSyncedStorage() { + if (!this.cachedExtensionWithSyncedStorage) { + const editor = this.editor; + const extension = this.extension; + this.cachedExtensionWithSyncedStorage = new Proxy(extension, { + get(target, prop, receiver) { + var _a; + if (prop === "storage") { + return (_a = editor.storage[extension.name]) != null ? _a : {}; + } + return Reflect.get(target, prop, receiver); + } + }); + } + return this.cachedExtensionWithSyncedStorage; + } + /** + * Setup the React component. + * Called on initialization. + */ + mount() { + const props = { + editor: this.editor, + node: this.node, + decorations: this.decorations, + innerDecorations: this.innerDecorations, + view: this.view, + selected: false, + extension: this.extensionWithSyncedStorage, + HTMLAttributes: this.HTMLAttributes, + getPos: () => this.getPos(), + updateAttributes: (attributes = {}) => this.updateAttributes(attributes), + deleteNode: () => this.deleteNode(), + ref: (0, import_react9.createRef)() + }; + if (!this.component.displayName) { + const capitalizeFirstChar = (string) => { + return string.charAt(0).toUpperCase() + string.substring(1); + }; + this.component.displayName = capitalizeFirstChar(this.extension.name); + } + const onDragStart = this.onDragStart.bind(this); + const nodeViewContentRef = (element) => { + if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) { + if (element.hasAttribute("data-node-view-wrapper")) { + element.removeAttribute("data-node-view-wrapper"); + } + element.appendChild(this.contentDOMElement); + } + }; + const context = { onDragStart, nodeViewContentRef }; + const Component = this.component; + const ReactNodeViewProvider = (0, import_react9.memo)((componentProps) => { + return (0, import_jsx_runtime7.jsx)(ReactNodeViewContext.Provider, { value: context, children: (0, import_react9.createElement)(Component, componentProps) }); + }); + ReactNodeViewProvider.displayName = "ReactNodeView"; + let as = this.node.isInline ? "span" : "div"; + if (this.options.as) { + as = this.options.as; + } + const { className = "" } = this.options; + this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this); + this.renderer = new ReactRenderer(ReactNodeViewProvider, { + editor: this.editor, + props, + as, + className: `node-${this.node.type.name} ${className}`.trim() + }); + this.editor.on("selectionUpdate", this.handleSelectionUpdate); + this.updateElementAttributes(); + } + /** + * Return the DOM element. + * This is the element that will be used to display the node view. + */ + get dom() { + var _a; + if (this.renderer.element.firstElementChild && !((_a = this.renderer.element.firstElementChild) == null ? void 0 : _a.hasAttribute("data-node-view-wrapper"))) { + throw Error("Please use the NodeViewWrapper component for your node view."); + } + return this.renderer.element; + } + /** + * Return the content DOM element. + * This is the element that will be used to display the rich-text content of the node. + */ + get contentDOM() { + if (this.node.isLeaf) { + return null; + } + return this.contentDOMElement; + } + /** + * On editor selection update, check if the node is selected. + * If it is, call `selectNode`, otherwise call `deselectNode`. + */ + handleSelectionUpdate() { + if (this.selectionRafId) { + cancelAnimationFrame(this.selectionRafId); + this.selectionRafId = null; + } + this.selectionRafId = requestAnimationFrame(() => { + this.selectionRafId = null; + const { from, to } = this.editor.state.selection; + const pos = this.getPos(); + if (typeof pos !== "number") { + return; + } + if (from <= pos && to >= pos + this.node.nodeSize) { + if (this.renderer.props.selected) { + return; + } + this.selectNode(); + } else { + if (!this.renderer.props.selected) { + return; + } + this.deselectNode(); + } + }); + } + /** + * On update, update the React component. + * To prevent unnecessary updates, the `update` option can be used. + */ + update(node, decorations, innerDecorations) { + const rerenderComponent = (props) => { + this.renderer.updateProps(props); + if (typeof this.options.attrs === "function") { + this.updateElementAttributes(); + } + }; + if (node.type !== this.node.type) { + return false; + } + if (typeof this.options.update === "function") { + const oldNode = this.node; + const oldDecorations = this.decorations; + const oldInnerDecorations = this.innerDecorations; + this.node = node; + this.decorations = decorations; + this.innerDecorations = innerDecorations; + return this.options.update({ + oldNode, + oldDecorations, + newNode: node, + newDecorations: decorations, + oldInnerDecorations, + innerDecorations, + updateProps: () => rerenderComponent({ node, decorations, innerDecorations, extension: this.extensionWithSyncedStorage }) + }); + } + if (node === this.node && this.decorations === decorations && this.innerDecorations === innerDecorations) { + return true; + } + this.node = node; + this.decorations = decorations; + this.innerDecorations = innerDecorations; + rerenderComponent({ node, decorations, innerDecorations, extension: this.extensionWithSyncedStorage }); + return true; + } + /** + * Select the node. + * Add the `selected` prop and the `ProseMirror-selectednode` class. + */ + selectNode() { + this.renderer.updateProps({ + selected: true + }); + this.renderer.element.classList.add("ProseMirror-selectednode"); + } + /** + * Deselect the node. + * Remove the `selected` prop and the `ProseMirror-selectednode` class. + */ + deselectNode() { + this.renderer.updateProps({ + selected: false + }); + this.renderer.element.classList.remove("ProseMirror-selectednode"); + } + /** + * Destroy the React component instance. + */ + destroy() { + this.renderer.destroy(); + this.editor.off("selectionUpdate", this.handleSelectionUpdate); + this.contentDOMElement = null; + if (this.selectionRafId) { + cancelAnimationFrame(this.selectionRafId); + this.selectionRafId = null; + } + } + /** + * Update the attributes of the top-level element that holds the React component. + * Applying the attributes defined in the `attrs` option. + */ + updateElementAttributes() { + if (this.options.attrs) { + let attrsObj = {}; + if (typeof this.options.attrs === "function") { + const extensionAttributes = this.editor.extensionManager.attributes; + const HTMLAttributes = getRenderedAttributes(this.node, extensionAttributes); + attrsObj = this.options.attrs({ node: this.node, HTMLAttributes }); + } else { + attrsObj = this.options.attrs; + } + this.renderer.updateAttributes(attrsObj); + } + } +}; +function ReactNodeViewRenderer(component, options) { + return (props) => { + if (!props.editor.contentComponent) { + return {}; + } + return new ReactNodeView(component, props, options); + }; +} +var TiptapContext = (0, import_react10.createContext)({ + get editor() { + throw new Error("useTiptap must be used within a provider"); + } +}); +TiptapContext.displayName = "TiptapContext"; +var useTiptap = () => (0, import_react10.useContext)(TiptapContext); +function useTiptapState(selector, equalityFn) { + const { editor } = useTiptap(); + return useEditorState({ + editor, + selector, + equalityFn + }); +} +function TiptapWrapper({ editor, instance, children }) { + const resolvedEditor = editor != null ? editor : instance; + if (!resolvedEditor) { + throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop."); + } + const tiptapContextValue = (0, import_react10.useMemo)(() => ({ editor: resolvedEditor }), [resolvedEditor]); + const legacyContextValue = (0, import_react10.useMemo)(() => ({ editor: resolvedEditor }), [resolvedEditor]); + return (0, import_jsx_runtime8.jsx)(EditorContext.Provider, { value: legacyContextValue, children: (0, import_jsx_runtime8.jsx)(TiptapContext.Provider, { value: tiptapContextValue, children }) }); +} +TiptapWrapper.displayName = "Tiptap"; +function TiptapContent({ ...rest }) { + const { editor } = useTiptap(); + return (0, import_jsx_runtime8.jsx)(EditorContent, { editor, ...rest }); +} +TiptapContent.displayName = "Tiptap.Content"; +var Tiptap = Object.assign(TiptapWrapper, { + /** + * The Tiptap Content component that renders the EditorContent with the editor instance from the context. + * @see TiptapContent + */ + Content: TiptapContent +}); +export { + CommandManager, + Editor, + EditorConsumer, + EditorContent, + EditorContext, + EditorProvider, + Extendable, + Extension, + Fragment6 as Fragment, + InputRule, + MappablePosition, + Mark, + MarkView, + MarkViewContent, + Node3 as Node, + NodePos, + NodeView, + NodeViewContent, + NodeViewWrapper, + PasteRule, + PureEditorContent, + ReactMarkView, + ReactMarkViewContext, + ReactMarkViewRenderer, + ReactNodeView, + ReactNodeViewContentProvider, + ReactNodeViewContext, + ReactNodeViewRenderer, + ReactRenderer, + ResizableNodeView, + ResizableNodeview, + Tiptap, + TiptapContent, + TiptapContext, + TiptapWrapper, + Tracker, + callOrReturn, + canInsertNode, + combineTransactionSteps, + commands_exports as commands, + createAtomBlockMarkdownSpec, + createBlockMarkdownSpec, + createChainableState, + createDocument, + h as createElement, + createInlineMarkdownSpec, + createMappablePosition, + createNodeFromContent, + createStyleTag, + defaultBlockAt, + deleteProps, + elementFromString, + escapeForRegEx, + extensions_exports as extensions, + findChildren, + findChildrenInRange, + findDuplicates, + findParentNode, + findParentNodeClosestToPos, + flattenExtensions, + fromString, + generateHTML, + generateJSON, + generateText, + getAttributes, + getAttributesFromExtensions, + getChangedRanges, + getDebugJSON, + getExtensionField, + getHTMLFromFragment, + getMarkAttributes, + getMarkRange, + getMarkType, + getMarksBetween, + getNodeAtPosition, + getNodeAttributes, + getNodeType, + getRenderedAttributes, + getSchema, + getSchemaByResolvedExtensions, + getSchemaTypeByName, + getSchemaTypeNameByName, + getSplittedAttributes, + getText, + getTextBetween, + getTextContentFromNodes, + getTextSerializersFromSchema, + getUpdatedPosition, + h, + injectExtensionAttributesToParseRule, + inputRulesPlugin, + isActive, + isAndroid, + isAtEndOfNode, + isAtStartOfNode, + isEmptyObject, + isExtensionRulesEnabled, + isFirefox, + isFunction, + isList, + isMacOS, + isMarkActive, + isNodeActive, + isNodeEmpty, + isNodeSelection, + isNumber, + isPlainObject, + isRegExp, + isSafari, + isString, + isTextSelection, + isiOS, + markInputRule, + markPasteRule, + markdown_exports as markdown, + mergeAttributes, + mergeDeep, + minMax, + nodeInputRule, + nodePasteRule, + objectIncludes, + parseAttributes, + parseIndentedBlocks, + pasteRulesPlugin, + posToDOMRect, + removeDuplicates, + renderNestedMarkdownContent, + resolveExtensions, + resolveFocusPosition, + rewriteUnknownContent, + selectionToInsertionEnd, + serializeAttributes, + sortExtensions, + splitExtensions, + textInputRule, + textPasteRule, + textblockTypeInputRule, + updateMarkViewAttributes, + useCurrentEditor, + useEditor, + useEditorState, + useReactNodeView, + useTiptap, + useTiptapState, + wrappingInputRule +}; +/*! Bundled license information: + +use-sync-external-store/cjs/use-sync-external-store-shim.development.js: + (** + * @license React + * use-sync-external-store-shim.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + *) + +use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js: + (** + * @license React + * use-sync-external-store-shim/with-selector.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + *) +*/ +//# sourceMappingURL=@tiptap_react.js.map diff --git a/frontend/node_modules/.vite/deps/@tiptap_react.js.map b/frontend/node_modules/.vite/deps/@tiptap_react.js.map new file mode 100644 index 00000000..0634100b --- /dev/null +++ b/frontend/node_modules/.vite/deps/@tiptap_react.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../use-sync-external-store/cjs/use-sync-external-store-shim.development.js", "../../use-sync-external-store/shim/index.js", "../../use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js", "../../use-sync-external-store/shim/with-selector.js", "../../@tiptap/react/src/Context.tsx", "../../@tiptap/react/src/EditorContent.tsx", "../../@tiptap/react/src/useEditor.ts", "../../@tiptap/react/src/useEditorState.ts", "../../@tiptap/react/src/useReactNodeView.ts", "../../@tiptap/react/src/NodeViewContent.tsx", "../../@tiptap/react/src/NodeViewWrapper.tsx", "../../@tiptap/react/src/ReactMarkViewRenderer.tsx", "../../@tiptap/react/src/ReactRenderer.tsx", "../../@tiptap/react/src/ReactNodeViewRenderer.tsx", "../../@tiptap/react/src/Tiptap.tsx", "../../@tiptap/react/src/index.ts", "../../src/utils.ts", "../../src/equals.ts", "../../src/comparator.ts", "../../src/index.ts"], + "sourcesContent": ["/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n }\n function useSyncExternalStore$2(subscribe, getSnapshot) {\n didWarnOld18Alpha ||\n void 0 === React.startTransition ||\n ((didWarnOld18Alpha = !0),\n console.error(\n \"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release.\"\n ));\n var value = getSnapshot();\n if (!didWarnUncachedGetSnapshot) {\n var cachedValue = getSnapshot();\n objectIs(value, cachedValue) ||\n (console.error(\n \"The result of getSnapshot should be cached to avoid an infinite loop\"\n ),\n (didWarnUncachedGetSnapshot = !0));\n }\n cachedValue = useState({\n inst: { value: value, getSnapshot: getSnapshot }\n });\n var inst = cachedValue[0].inst,\n forceUpdate = cachedValue[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n }\n function checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n }\n function useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n }\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());\n var React = require(\"react\"),\n objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue,\n didWarnOld18Alpha = !1,\n didWarnUncachedGetSnapshot = !1,\n shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\n exports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());\n })();\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n", "/**\n * @license React\n * use-sync-external-store-shim/with-selector.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n }\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());\n var React = require(\"react\"),\n shim = require(\"use-sync-external-store/shim\"),\n objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useSyncExternalStore = shim.useSyncExternalStore,\n useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue;\n exports.useSyncExternalStoreWithSelector = function (\n subscribe,\n getSnapshot,\n getServerSnapshot,\n selector,\n isEqual\n ) {\n var instRef = useRef(null);\n if (null === instRef.current) {\n var inst = { hasValue: !1, value: null };\n instRef.current = inst;\n } else inst = instRef.current;\n instRef = useMemo(\n function () {\n function memoizedSelector(nextSnapshot) {\n if (!hasMemo) {\n hasMemo = !0;\n memoizedSnapshot = nextSnapshot;\n nextSnapshot = selector(nextSnapshot);\n if (void 0 !== isEqual && inst.hasValue) {\n var currentSelection = inst.value;\n if (isEqual(currentSelection, nextSnapshot))\n return (memoizedSelection = currentSelection);\n }\n return (memoizedSelection = nextSnapshot);\n }\n currentSelection = memoizedSelection;\n if (objectIs(memoizedSnapshot, nextSnapshot))\n return currentSelection;\n var nextSelection = selector(nextSnapshot);\n if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))\n return (memoizedSnapshot = nextSnapshot), currentSelection;\n memoizedSnapshot = nextSnapshot;\n return (memoizedSelection = nextSelection);\n }\n var hasMemo = !1,\n memoizedSnapshot,\n memoizedSelection,\n maybeGetServerSnapshot =\n void 0 === getServerSnapshot ? null : getServerSnapshot;\n return [\n function () {\n return memoizedSelector(getSnapshot());\n },\n null === maybeGetServerSnapshot\n ? void 0\n : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n }\n ];\n },\n [getSnapshot, getServerSnapshot, selector, isEqual]\n );\n var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);\n useEffect(\n function () {\n inst.hasValue = !0;\n inst.value = value;\n },\n [value]\n );\n useDebugValue(value);\n return value;\n };\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());\n })();\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n", "import type { Editor } from '@tiptap/core'\nimport type { HTMLAttributes, ReactNode } from 'react'\nimport React, { createContext, useContext, useMemo } from 'react'\n\nimport { EditorContent } from './EditorContent.js'\nimport type { UseEditorOptions } from './useEditor.js'\nimport { useEditor } from './useEditor.js'\n\nexport type EditorContextValue = {\n editor: Editor | null\n}\n\nexport const EditorContext = createContext({\n editor: null,\n})\n\nexport const EditorConsumer = EditorContext.Consumer\n\n/**\n * A hook to get the current editor instance.\n */\nexport const useCurrentEditor = () => useContext(EditorContext)\n\nexport type EditorProviderProps = {\n children?: ReactNode\n slotBefore?: ReactNode\n slotAfter?: ReactNode\n editorContainerProps?: HTMLAttributes\n} & UseEditorOptions\n\n/**\n * This is the provider component for the editor.\n * It allows the editor to be accessible across the entire component tree\n * with `useCurrentEditor`.\n */\nexport function EditorProvider({\n children,\n slotAfter,\n slotBefore,\n editorContainerProps = {},\n ...editorOptions\n}: EditorProviderProps) {\n const editor = useEditor(editorOptions)\n const contextValue = useMemo(() => ({ editor }), [editor])\n\n if (!editor) {\n return null\n }\n\n return (\n \n {slotBefore}\n \n {({ editor: currentEditor }) => }\n \n {children}\n {slotAfter}\n \n )\n}\n", "import type { Editor } from '@tiptap/core'\nimport type { ForwardedRef, HTMLProps, LegacyRef, MutableRefObject } from 'react'\nimport React, { forwardRef } from 'react'\nimport ReactDOM from 'react-dom'\nimport { useSyncExternalStore } from 'use-sync-external-store/shim/index.js'\n\nimport type { ContentComponent, EditorWithContentComponent } from './Editor.js'\nimport type { ReactRenderer } from './ReactRenderer.js'\n\nconst mergeRefs = (...refs: Array | LegacyRef | undefined>) => {\n return (node: T) => {\n refs.forEach(ref => {\n if (typeof ref === 'function') {\n ref(node)\n } else if (ref) {\n ;(ref as MutableRefObject).current = node\n }\n })\n }\n}\n\n/**\n * This component renders all of the editor's node views.\n */\nconst Portals: React.FC<{ contentComponent: ContentComponent }> = ({ contentComponent }) => {\n // For performance reasons, we render the node view portals on state changes only\n const renderers = useSyncExternalStore(\n contentComponent.subscribe,\n contentComponent.getSnapshot,\n contentComponent.getServerSnapshot,\n )\n\n // This allows us to directly render the portals without any additional wrapper\n return <>{Object.values(renderers)}\n}\n\nexport interface EditorContentProps extends HTMLProps {\n editor: Editor | null\n innerRef?: ForwardedRef\n}\n\nfunction getInstance(): ContentComponent {\n const subscribers = new Set<() => void>()\n let renderers: Record = {}\n\n return {\n /**\n * Subscribe to the editor instance's changes.\n */\n subscribe(callback: () => void) {\n subscribers.add(callback)\n return () => {\n subscribers.delete(callback)\n }\n },\n getSnapshot() {\n return renderers\n },\n getServerSnapshot() {\n return renderers\n },\n /**\n * Adds a new NodeView Renderer to the editor.\n */\n setRenderer(id: string, renderer: ReactRenderer) {\n renderers = {\n ...renderers,\n [id]: ReactDOM.createPortal(renderer.reactElement, renderer.element, id),\n }\n\n subscribers.forEach(subscriber => subscriber())\n },\n /**\n * Removes a NodeView Renderer from the editor.\n */\n removeRenderer(id: string) {\n const nextRenderers = { ...renderers }\n\n delete nextRenderers[id]\n renderers = nextRenderers\n subscribers.forEach(subscriber => subscriber())\n },\n }\n}\n\nexport class PureEditorContent extends React.Component<\n EditorContentProps,\n { hasContentComponentInitialized: boolean }\n> {\n editorContentRef: React.RefObject\n\n initialized: boolean\n\n unsubscribeToContentComponent?: () => void\n\n constructor(props: EditorContentProps) {\n super(props)\n this.editorContentRef = React.createRef()\n this.initialized = false\n\n this.state = {\n hasContentComponentInitialized: Boolean((props.editor as EditorWithContentComponent | null)?.contentComponent),\n }\n }\n\n componentDidMount() {\n this.init()\n }\n\n componentDidUpdate() {\n this.init()\n }\n\n init() {\n const editor = this.props.editor as EditorWithContentComponent | null\n\n if (editor && !editor.isDestroyed && editor.view.dom?.parentNode) {\n if (editor.contentComponent) {\n return\n }\n\n const element = this.editorContentRef.current\n\n element.append(...editor.view.dom.parentNode.childNodes)\n\n editor.setOptions({\n element,\n })\n\n editor.contentComponent = getInstance()\n\n // Has the content component been initialized?\n if (!this.state.hasContentComponentInitialized) {\n // Subscribe to the content component\n this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {\n this.setState(prevState => {\n if (!prevState.hasContentComponentInitialized) {\n return {\n hasContentComponentInitialized: true,\n }\n }\n return prevState\n })\n\n // Unsubscribe to previous content component\n if (this.unsubscribeToContentComponent) {\n this.unsubscribeToContentComponent()\n }\n })\n }\n\n editor.createNodeViews()\n\n this.initialized = true\n }\n }\n\n componentWillUnmount() {\n const editor = this.props.editor as EditorWithContentComponent | null\n\n if (!editor) {\n return\n }\n\n this.initialized = false\n\n if (!editor.isDestroyed) {\n editor.view.setProps({\n nodeViews: {},\n })\n }\n\n if (this.unsubscribeToContentComponent) {\n this.unsubscribeToContentComponent()\n }\n\n editor.contentComponent = null\n\n // try to reset the editor element\n // may fail if this editor's view.dom was never initialized/mounted yet\n try {\n if (!editor.view.dom?.parentNode) {\n return\n }\n\n // TODO using the new editor.mount method might allow us to remove this\n const newElement = document.createElement('div')\n\n newElement.append(...editor.view.dom.parentNode.childNodes)\n\n editor.setOptions({\n element: newElement,\n })\n } catch {\n // do nothing, nothing to reset\n }\n }\n\n render() {\n const { editor, innerRef, ...rest } = this.props\n\n return (\n <>\n
\n {/* @ts-ignore */}\n {editor?.contentComponent && }\n \n )\n }\n}\n\n// EditorContent should be re-created whenever the Editor instance changes\nconst EditorContentWithKey = forwardRef(\n (props: Omit, ref) => {\n const key = React.useMemo(() => {\n return Math.floor(Math.random() * 0xffffffff).toString()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.editor])\n\n // Can't use JSX here because it conflicts with the type definition of Vue's JSX, so use createElement\n return React.createElement(PureEditorContent, {\n key,\n innerRef: ref,\n ...props,\n })\n },\n)\n\nexport const EditorContent = React.memo(EditorContentWithKey)\n", "import { type EditorOptions, Editor } from '@tiptap/core'\nimport type { DependencyList, MutableRefObject } from 'react'\nimport { useDebugValue, useEffect, useRef, useState } from 'react'\nimport { useSyncExternalStore } from 'use-sync-external-store/shim/index.js'\n\nimport { useEditorState } from './useEditorState.js'\n\n// @ts-ignore\nconst isDev = process.env.NODE_ENV !== 'production'\nconst isSSR = typeof window === 'undefined'\nconst isNext = isSSR || Boolean(typeof window !== 'undefined' && (window as any).next)\n\n/**\n * The options for the `useEditor` hook.\n */\nexport type UseEditorOptions = Partial & {\n /**\n * Whether to render the editor on the first render.\n * If client-side rendering, set this to `true`.\n * If server-side rendering, set this to `false`.\n * @default true\n */\n immediatelyRender?: boolean\n /**\n * Whether to re-render the editor on each transaction.\n * This is legacy behavior that will be removed in future versions.\n * @default false\n */\n shouldRerenderOnTransaction?: boolean\n}\n\n/**\n * This class handles the creation, destruction, and re-creation of the editor instance.\n */\nclass EditorInstanceManager {\n /**\n * The current editor instance.\n */\n private editor: Editor | null = null\n\n /**\n * The most recent options to apply to the editor.\n */\n private options: MutableRefObject\n\n /**\n * The subscriptions to notify when the editor instance\n * has been created or destroyed.\n */\n private subscriptions = new Set<() => void>()\n\n /**\n * A timeout to destroy the editor if it was not mounted within a time frame.\n */\n private scheduledDestructionTimeout: ReturnType | undefined\n\n /**\n * Whether the editor has been mounted.\n */\n private isComponentMounted = false\n\n /**\n * The most recent dependencies array.\n */\n private previousDeps: DependencyList | null = null\n\n /**\n * The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.\n */\n public instanceId = ''\n\n constructor(options: MutableRefObject) {\n this.options = options\n this.subscriptions = new Set<() => void>()\n this.setEditor(this.getInitialEditor())\n this.scheduleDestroy()\n\n this.getEditor = this.getEditor.bind(this)\n this.getServerSnapshot = this.getServerSnapshot.bind(this)\n this.subscribe = this.subscribe.bind(this)\n this.refreshEditorInstance = this.refreshEditorInstance.bind(this)\n this.scheduleDestroy = this.scheduleDestroy.bind(this)\n this.onRender = this.onRender.bind(this)\n this.createEditor = this.createEditor.bind(this)\n }\n\n private setEditor(editor: Editor | null) {\n this.editor = editor\n this.instanceId = Math.random().toString(36).slice(2, 9)\n\n // Notify all subscribers that the editor instance has been created\n this.subscriptions.forEach(cb => cb())\n }\n\n private getInitialEditor() {\n if (this.options.current.immediatelyRender === undefined) {\n if (isSSR || isNext) {\n if (isDev) {\n /**\n * Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd\n * and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches.\n */\n throw new Error(\n 'Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.',\n )\n }\n\n // Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production\n return null\n }\n\n // Default to immediately rendering when client-side rendering\n return this.createEditor()\n }\n\n if (this.options.current.immediatelyRender && isSSR && isDev) {\n // Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches.\n throw new Error(\n 'Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.',\n )\n }\n\n if (this.options.current.immediatelyRender) {\n return this.createEditor()\n }\n\n return null\n }\n\n /**\n * Create a new editor instance. And attach event listeners.\n */\n private createEditor(): Editor {\n const optionsToApply: Partial = {\n ...this.options.current,\n // Always call the most recent version of the callback function by default\n onBeforeCreate: (...args) => this.options.current.onBeforeCreate?.(...args),\n onBlur: (...args) => this.options.current.onBlur?.(...args),\n onCreate: (...args) => this.options.current.onCreate?.(...args),\n onDestroy: (...args) => this.options.current.onDestroy?.(...args),\n onFocus: (...args) => this.options.current.onFocus?.(...args),\n onSelectionUpdate: (...args) => this.options.current.onSelectionUpdate?.(...args),\n onTransaction: (...args) => this.options.current.onTransaction?.(...args),\n onUpdate: (...args) => this.options.current.onUpdate?.(...args),\n onContentError: (...args) => this.options.current.onContentError?.(...args),\n onDrop: (...args) => this.options.current.onDrop?.(...args),\n onPaste: (...args) => this.options.current.onPaste?.(...args),\n onDelete: (...args) => this.options.current.onDelete?.(...args),\n }\n const editor = new Editor(optionsToApply)\n\n // no need to keep track of the event listeners, they will be removed when the editor is destroyed\n\n return editor\n }\n\n /**\n * Get the current editor instance.\n */\n getEditor(): Editor | null {\n return this.editor\n }\n\n /**\n * Always disable the editor on the server-side.\n */\n getServerSnapshot(): null {\n return null\n }\n\n /**\n * Subscribe to the editor instance's changes.\n */\n subscribe(onStoreChange: () => void) {\n this.subscriptions.add(onStoreChange)\n\n return () => {\n this.subscriptions.delete(onStoreChange)\n }\n }\n\n static compareOptions(a: UseEditorOptions, b: UseEditorOptions) {\n return (Object.keys(a) as (keyof UseEditorOptions)[]).every(key => {\n if (\n [\n 'onCreate',\n 'onBeforeCreate',\n 'onDestroy',\n 'onUpdate',\n 'onTransaction',\n 'onFocus',\n 'onBlur',\n 'onSelectionUpdate',\n 'onContentError',\n 'onDrop',\n 'onPaste',\n ].includes(key)\n ) {\n // we don't want to compare callbacks, they are always different and only registered once\n return true\n }\n\n // We often encourage putting extensions inlined in the options object, so we will do a slightly deeper comparison here\n if (key === 'extensions' && a.extensions && b.extensions) {\n if (a.extensions.length !== b.extensions.length) {\n return false\n }\n return a.extensions.every((extension, index) => {\n if (extension !== b.extensions?.[index]) {\n return false\n }\n return true\n })\n }\n if (a[key] !== b[key]) {\n // if any of the options have changed, we should update the editor options\n return false\n }\n return true\n })\n }\n\n /**\n * On each render, we will create, update, or destroy the editor instance.\n * @param deps The dependencies to watch for changes\n * @returns A cleanup function\n */\n onRender(deps: DependencyList) {\n // The returned callback will run on each render\n return () => {\n this.isComponentMounted = true\n // Cleanup any scheduled destructions, since we are currently rendering\n clearTimeout(this.scheduledDestructionTimeout)\n\n if (this.editor && !this.editor.isDestroyed && deps.length === 0) {\n // if the editor does exist & deps are empty, we don't need to re-initialize the editor generally\n if (!EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) {\n // But, the options are different, so we need to update the editor options\n // Still, this is faster than re-creating the editor\n this.editor.setOptions({\n ...this.options.current,\n editable: this.editor.isEditable,\n })\n }\n } else {\n // When the editor:\n // - does not yet exist\n // - is destroyed\n // - the deps array changes\n // We need to destroy the editor instance and re-initialize it\n this.refreshEditorInstance(deps)\n }\n\n return () => {\n this.isComponentMounted = false\n this.scheduleDestroy()\n }\n }\n }\n\n /**\n * Recreate the editor instance if the dependencies have changed.\n */\n private refreshEditorInstance(deps: DependencyList) {\n if (this.editor && !this.editor.isDestroyed) {\n // Editor instance already exists\n if (this.previousDeps === null) {\n // If lastDeps has not yet been initialized, reuse the current editor instance\n this.previousDeps = deps\n return\n }\n const depsAreEqual =\n this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index])\n\n if (depsAreEqual) {\n // deps exist and are equal, no need to recreate\n return\n }\n }\n\n if (this.editor && !this.editor.isDestroyed) {\n // Destroy the editor instance if it exists\n this.editor.destroy()\n }\n\n this.setEditor(this.createEditor())\n\n // Update the lastDeps to the current deps\n this.previousDeps = deps\n }\n\n /**\n * Schedule the destruction of the editor instance.\n * This will only destroy the editor if it was not mounted on the next tick.\n * This is to avoid destroying the editor instance when it's actually still mounted.\n */\n private scheduleDestroy() {\n const currentInstanceId = this.instanceId\n const currentEditor = this.editor\n\n // Wait two ticks to see if the component is still mounted\n this.scheduledDestructionTimeout = setTimeout(() => {\n if (this.isComponentMounted && this.instanceId === currentInstanceId) {\n // If still mounted on the following tick, with the same instanceId, do not destroy the editor\n if (currentEditor) {\n // just re-apply options as they might have changed\n currentEditor.setOptions(this.options.current)\n }\n return\n }\n if (currentEditor && !currentEditor.isDestroyed) {\n currentEditor.destroy()\n if (this.instanceId === currentInstanceId) {\n this.setEditor(null)\n }\n }\n // This allows the effect to run again between ticks\n // which may save us from having to re-create the editor\n }, 1)\n }\n}\n\n/**\n * This hook allows you to create an editor instance.\n * @param options The editor options\n * @param deps The dependencies to watch for changes\n * @returns The editor instance\n * @example const editor = useEditor({ extensions: [...] })\n */\nexport function useEditor(\n options: UseEditorOptions & { immediatelyRender: false },\n deps?: DependencyList,\n): Editor | null\n\n/**\n * This hook allows you to create an editor instance.\n * @param options The editor options\n * @param deps The dependencies to watch for changes\n * @returns The editor instance\n * @example const editor = useEditor({ extensions: [...] })\n */\nexport function useEditor(options: UseEditorOptions, deps?: DependencyList): Editor\n\nexport function useEditor(options: UseEditorOptions = {}, deps: DependencyList = []): Editor | null {\n const mostRecentOptions = useRef(options)\n\n mostRecentOptions.current = options\n\n const [instanceManager] = useState(() => new EditorInstanceManager(mostRecentOptions))\n\n const editor = useSyncExternalStore(\n instanceManager.subscribe,\n instanceManager.getEditor,\n instanceManager.getServerSnapshot,\n )\n\n useDebugValue(editor)\n\n // This effect will handle creating/updating the editor instance\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useEffect(instanceManager.onRender(deps))\n\n // The default behavior is to re-render on each transaction\n // This is legacy behavior that will be removed in future versions\n useEditorState({\n editor,\n selector: ({ transactionNumber }) => {\n if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === undefined) {\n // This will prevent the editor from re-rendering on each transaction\n return null\n }\n\n // This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true`\n if (options.immediatelyRender && transactionNumber === 0) {\n return 0\n }\n return transactionNumber + 1\n },\n })\n\n return editor\n}\n", "import type { Editor } from '@tiptap/core'\nimport { deepEqual } from 'fast-equals'\nimport { useDebugValue, useEffect, useLayoutEffect, useState } from 'react'\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js'\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect\n\nexport type EditorStateSnapshot = {\n editor: TEditor\n transactionNumber: number\n}\n\nexport type UseEditorStateOptions = {\n /**\n * The editor instance.\n */\n editor: TEditor\n /**\n * A selector function to determine the value to compare for re-rendering.\n */\n selector: (context: EditorStateSnapshot) => TSelectorResult\n /**\n * A custom equality function to determine if the editor should re-render.\n * @default `deepEqual` from `fast-deep-equal`\n */\n equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean\n}\n\n/**\n * To synchronize the editor instance with the component state,\n * we need to create a separate instance that is not affected by the component re-renders.\n */\nclass EditorStateManager {\n private transactionNumber = 0\n\n private lastTransactionNumber = 0\n\n private lastSnapshot: EditorStateSnapshot\n\n private editor: TEditor\n\n private subscribers = new Set<() => void>()\n\n constructor(initialEditor: TEditor) {\n this.editor = initialEditor\n this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }\n\n this.getSnapshot = this.getSnapshot.bind(this)\n this.getServerSnapshot = this.getServerSnapshot.bind(this)\n this.watch = this.watch.bind(this)\n this.subscribe = this.subscribe.bind(this)\n }\n\n /**\n * Get the current editor instance.\n */\n getSnapshot(): EditorStateSnapshot {\n if (this.transactionNumber === this.lastTransactionNumber) {\n return this.lastSnapshot\n }\n this.lastTransactionNumber = this.transactionNumber\n this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }\n return this.lastSnapshot\n }\n\n /**\n * Always disable the editor on the server-side.\n */\n getServerSnapshot(): EditorStateSnapshot {\n return { editor: null, transactionNumber: 0 }\n }\n\n /**\n * Subscribe to the editor instance's changes.\n */\n subscribe(callback: () => void): () => void {\n this.subscribers.add(callback)\n return () => {\n this.subscribers.delete(callback)\n }\n }\n\n /**\n * Watch the editor instance for changes.\n */\n watch(nextEditor: Editor | null): undefined | (() => void) {\n this.editor = nextEditor as TEditor\n\n if (this.editor) {\n /**\n * This will force a re-render when the editor state changes.\n * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.\n * This could be more efficient, but it's a good trade-off for now.\n */\n const fn = () => {\n this.transactionNumber += 1\n this.subscribers.forEach(callback => callback())\n }\n\n const currentEditor = this.editor\n\n currentEditor.on('transaction', fn)\n return () => {\n currentEditor.off('transaction', fn)\n }\n }\n\n return undefined\n }\n}\n\n/**\n * This hook allows you to watch for changes on the editor instance.\n * It will allow you to select a part of the editor state and re-render the component when it changes.\n * @example\n * ```tsx\n * const editor = useEditor({...options})\n * const { currentSelection } = useEditorState({\n * editor,\n * selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),\n * })\n */\nexport function useEditorState(\n options: UseEditorStateOptions,\n): TSelectorResult\n/**\n * This hook allows you to watch for changes on the editor instance.\n * It will allow you to select a part of the editor state and re-render the component when it changes.\n * @example\n * ```tsx\n * const editor = useEditor({...options})\n * const { currentSelection } = useEditorState({\n * editor,\n * selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),\n * })\n */\nexport function useEditorState(\n options: UseEditorStateOptions,\n): TSelectorResult | null\n\n/**\n * This hook allows you to watch for changes on the editor instance.\n * It will allow you to select a part of the editor state and re-render the component when it changes.\n * @example\n * ```tsx\n * const editor = useEditor({...options})\n * const { currentSelection } = useEditorState({\n * editor,\n * selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),\n * })\n */\nexport function useEditorState(\n options: UseEditorStateOptions | UseEditorStateOptions,\n): TSelectorResult | null {\n const [editorStateManager] = useState(() => new EditorStateManager(options.editor))\n\n // Using the `useSyncExternalStore` hook to sync the editor instance with the component state\n const selectedState = useSyncExternalStoreWithSelector(\n editorStateManager.subscribe,\n editorStateManager.getSnapshot,\n editorStateManager.getServerSnapshot,\n options.selector as UseEditorStateOptions['selector'],\n options.equalityFn ?? deepEqual,\n )\n\n useIsomorphicLayoutEffect(() => {\n return editorStateManager.watch(options.editor)\n }, [options.editor, editorStateManager])\n\n useDebugValue(selectedState)\n\n return selectedState\n}\n", "import type { ReactNode } from 'react'\nimport { createContext, createElement, useContext } from 'react'\n\nexport interface ReactNodeViewContextProps {\n onDragStart?: (event: DragEvent) => void\n nodeViewContentRef?: (element: HTMLElement | null) => void\n /**\n * This allows you to add children into the NodeViewContent component.\n * This is useful when statically rendering the content of a node view.\n */\n nodeViewContentChildren?: ReactNode\n}\n\nexport const ReactNodeViewContext = createContext({\n onDragStart: () => {\n // no-op\n },\n nodeViewContentChildren: undefined,\n nodeViewContentRef: () => {\n // no-op\n },\n})\n\nexport const ReactNodeViewContentProvider = ({ children, content }: { children: ReactNode; content: ReactNode }) => {\n return createElement(ReactNodeViewContext.Provider, { value: { nodeViewContentChildren: content } }, children)\n}\n\nexport const useReactNodeView = () => useContext(ReactNodeViewContext)\n", "import type { ComponentProps } from 'react'\nimport React from 'react'\n\nimport { useReactNodeView } from './useReactNodeView.js'\n\nexport type NodeViewContentProps = {\n as?: NoInfer\n} & ComponentProps\n\nexport function NodeViewContent({\n as: Tag = 'div' as T,\n ...props\n}: NodeViewContentProps) {\n const { nodeViewContentRef, nodeViewContentChildren } = useReactNodeView()\n\n return (\n // @ts-ignore\n \n {nodeViewContentChildren}\n \n )\n}\n", "import React from 'react'\n\nimport { useReactNodeView } from './useReactNodeView.js'\n\nexport interface NodeViewWrapperProps {\n [key: string]: any\n as?: React.ElementType\n}\n\nexport const NodeViewWrapper: React.FC = React.forwardRef((props, ref) => {\n const { onDragStart } = useReactNodeView()\n const Tag = props.as || 'div'\n\n return (\n // @ts-ignore\n \n )\n})\n", "/* eslint-disable @typescript-eslint/no-shadow */\nimport type { MarkViewProps, MarkViewRenderer, MarkViewRendererOptions } from '@tiptap/core'\nimport { MarkView } from '@tiptap/core'\nimport React from 'react'\n\n// import { flushSync } from 'react-dom'\nimport { ReactRenderer } from './ReactRenderer.js'\n\nexport interface MarkViewContextProps {\n markViewContentRef: (element: HTMLElement | null) => void\n}\nexport const ReactMarkViewContext = React.createContext({\n markViewContentRef: () => {\n // do nothing\n },\n})\n\nexport type MarkViewContentProps = {\n as?: T\n} & Omit, 'as'>\n\nexport const MarkViewContent = (\n props: MarkViewContentProps,\n) => {\n const { as: Tag = 'span', ...rest } = props\n const { markViewContentRef } = React.useContext(ReactMarkViewContext)\n\n return (\n // @ts-ignore\n \n )\n}\n\nexport interface ReactMarkViewRendererOptions extends MarkViewRendererOptions {\n /**\n * The tag name of the element wrapping the React component.\n */\n as?: string\n className?: string\n attrs?: { [key: string]: string }\n}\n\nexport class ReactMarkView extends MarkView, ReactMarkViewRendererOptions> {\n renderer: ReactRenderer\n contentDOMElement: HTMLElement\n\n constructor(\n component: React.ComponentType,\n props: MarkViewProps,\n options?: Partial,\n ) {\n super(component, props, options)\n\n const { as = 'span', attrs, className = '' } = options || {}\n const componentProps = { ...props, updateAttributes: this.updateAttributes.bind(this) } satisfies MarkViewProps\n\n this.contentDOMElement = document.createElement('span')\n\n const markViewContentRef: MarkViewContextProps['markViewContentRef'] = el => {\n if (el && !el.contains(this.contentDOMElement)) {\n el.appendChild(this.contentDOMElement)\n }\n }\n const context: MarkViewContextProps = {\n markViewContentRef,\n }\n\n // For performance reasons, we memoize the provider component\n // And all of the things it requires are declared outside of the component, so it doesn't need to re-render\n const ReactMarkViewProvider: React.FunctionComponent = React.memo(componentProps => {\n return (\n \n {React.createElement(component, componentProps)}\n \n )\n })\n\n ReactMarkViewProvider.displayName = 'ReactMarkView'\n\n this.renderer = new ReactRenderer(ReactMarkViewProvider, {\n editor: props.editor,\n props: componentProps,\n as,\n className: `mark-${props.mark.type.name} ${className}`.trim(),\n })\n\n if (attrs) {\n this.renderer.updateAttributes(attrs)\n }\n }\n\n get dom() {\n return this.renderer.element\n }\n\n get contentDOM() {\n return this.contentDOMElement\n }\n}\n\nexport function ReactMarkViewRenderer(\n component: React.ComponentType,\n options: Partial = {},\n): MarkViewRenderer {\n return props => new ReactMarkView(component, props, options)\n}\n", "import type { Editor } from '@tiptap/core'\nimport type {\n ComponentClass,\n ForwardRefExoticComponent,\n FunctionComponent,\n PropsWithoutRef,\n ReactNode,\n RefAttributes,\n} from 'react'\nimport { version as reactVersion } from 'react'\nimport { flushSync } from 'react-dom'\n\nimport type { EditorWithContentComponent } from './Editor.js'\n\n/**\n * Check if a component is a class component.\n * @param Component\n * @returns {boolean}\n */\nfunction isClassComponent(Component: any) {\n return !!(typeof Component === 'function' && Component.prototype && Component.prototype.isReactComponent)\n}\n\n/**\n * Check if a component is a forward ref component.\n * @param Component\n * @returns {boolean}\n */\nfunction isForwardRefComponent(Component: any) {\n return !!(\n typeof Component === 'object' &&\n Component.$$typeof &&\n (Component.$$typeof.toString() === 'Symbol(react.forward_ref)' ||\n Component.$$typeof.description === 'react.forward_ref')\n )\n}\n\n/**\n * Check if a component is a memoized component.\n * @param Component\n * @returns {boolean}\n */\nfunction isMemoComponent(Component: any) {\n return !!(\n typeof Component === 'object' &&\n Component.$$typeof &&\n (Component.$$typeof.toString() === 'Symbol(react.memo)' || Component.$$typeof.description === 'react.memo')\n )\n}\n\n/**\n * Check if a component can safely receive a ref prop.\n * This includes class components, forwardRef components, and memoized components\n * that wrap forwardRef or class components.\n * @param Component\n * @returns {boolean}\n */\nfunction canReceiveRef(Component: any) {\n // Check if it's a class component\n if (isClassComponent(Component)) {\n return true\n }\n\n // Check if it's a forwardRef component\n if (isForwardRefComponent(Component)) {\n return true\n }\n\n // Check if it's a memoized component\n if (isMemoComponent(Component)) {\n // For memoized components, check the wrapped component\n const wrappedComponent = Component.type\n if (wrappedComponent) {\n return isClassComponent(wrappedComponent) || isForwardRefComponent(wrappedComponent)\n }\n }\n\n return false\n}\n\n/**\n * Check if we're running React 19+ by detecting if function components support ref props\n * @returns {boolean}\n */\nfunction isReact19Plus(): boolean {\n // React 19 is detected by checking React version if available\n // In practice, we'll use a more conservative approach and assume React 18 behavior\n // unless we can definitively detect React 19\n try {\n // @ts-ignore\n if (reactVersion) {\n const majorVersion = parseInt(reactVersion.split('.')[0], 10)\n return majorVersion >= 19\n }\n } catch {\n // Fallback to React 18 behavior if we can't determine version\n }\n return false\n}\n\nexport interface ReactRendererOptions {\n /**\n * The editor instance.\n * @type {Editor}\n */\n editor: Editor\n\n /**\n * The props for the component.\n * @type {Record}\n * @default {}\n */\n props?: Record\n\n /**\n * The tag name of the element.\n * @type {string}\n * @default 'div'\n */\n as?: string\n\n /**\n * The class name of the element.\n * @type {string}\n * @default ''\n * @example 'foo bar'\n */\n className?: string\n}\n\ntype ComponentType =\n | ComponentClass

\n | FunctionComponent

\n | ForwardRefExoticComponent & RefAttributes>\n\n/**\n * The ReactRenderer class. It's responsible for rendering React components inside the editor.\n * @example\n * new ReactRenderer(MyComponent, {\n * editor,\n * props: {\n * foo: 'bar',\n * },\n * as: 'span',\n * })\n */\nexport class ReactRenderer = object> {\n id: string\n\n editor: Editor\n\n component: any\n\n element: HTMLElement\n\n props: P\n\n reactElement: ReactNode\n\n ref: R | null = null\n\n /**\n * Flag to track if the renderer has been destroyed, preventing queued or asynchronous renders from executing after teardown.\n */\n destroyed = false\n\n /**\n * Immediately creates element and renders the provided React component.\n */\n constructor(\n component: ComponentType,\n { editor, props = {}, as = 'div', className = '' }: ReactRendererOptions,\n ) {\n this.id = Math.floor(Math.random() * 0xffffffff).toString()\n this.component = component\n this.editor = editor as EditorWithContentComponent\n this.props = props as P\n this.element = document.createElement(as)\n this.element.classList.add('react-renderer')\n\n if (className) {\n this.element.classList.add(...className.split(' '))\n }\n\n // If the editor is already initialized, we will need to\n // synchronously render the component to ensure it renders\n // together with Prosemirror's rendering.\n if (this.editor.isInitialized) {\n flushSync(() => {\n this.render()\n })\n } else {\n queueMicrotask(() => {\n if (this.destroyed) {\n return\n }\n this.render()\n })\n }\n }\n\n /**\n * Render the React component.\n */\n render(): void {\n if (this.destroyed) {\n return\n }\n\n const Component = this.component\n const props = this.props\n const editor = this.editor as EditorWithContentComponent\n\n // Handle ref forwarding with React 18/19 compatibility\n const isReact19 = isReact19Plus()\n const componentCanReceiveRef = canReceiveRef(Component)\n\n const elementProps = { ...props }\n\n // Always remove ref if the component cannot receive it (unless React 19+)\n if (elementProps.ref && !(isReact19 || componentCanReceiveRef)) {\n delete elementProps.ref\n }\n\n // Only assign our own ref if allowed\n if (!elementProps.ref && (isReact19 || componentCanReceiveRef)) {\n // @ts-ignore - Setting ref prop for compatible components\n elementProps.ref = (ref: R) => {\n this.ref = ref\n }\n }\n\n this.reactElement = \n\n editor?.contentComponent?.setRenderer(this.id, this)\n }\n\n /**\n * Re-renders the React component with new props.\n */\n updateProps(props: Record = {}): void {\n if (this.destroyed) {\n return\n }\n\n this.props = {\n ...this.props,\n ...props,\n }\n\n this.render()\n }\n\n /**\n * Destroy the React component.\n */\n destroy(): void {\n this.destroyed = true\n const editor = this.editor as EditorWithContentComponent\n\n editor?.contentComponent?.removeRenderer(this.id)\n // If the consumer appended the element to the document (for example\n // many demos append the renderer element to document.body), make sure\n // we remove it here to avoid leaking DOM nodes / React roots.\n try {\n if (this.element && this.element.parentNode) {\n this.element.parentNode.removeChild(this.element)\n }\n } catch {\n // ignore DOM removal errors\n }\n }\n\n /**\n * Update the attributes of the element that holds the React component.\n */\n updateAttributes(attributes: Record): void {\n Object.keys(attributes).forEach(key => {\n this.element.setAttribute(key, attributes[key])\n })\n }\n}\n", "import type {\n DecorationWithType,\n Editor,\n NodeViewRenderer,\n NodeViewRendererOptions,\n NodeViewRendererProps,\n} from '@tiptap/core'\nimport { getRenderedAttributes, NodeView } from '@tiptap/core'\nimport type { Node, Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { Decoration, DecorationSource, NodeView as ProseMirrorNodeView } from '@tiptap/pm/view'\nimport type { ComponentType, NamedExoticComponent } from 'react'\nimport { createElement, createRef, memo } from 'react'\n\nimport type { EditorWithContentComponent } from './Editor.js'\nimport { ReactRenderer } from './ReactRenderer.js'\nimport type { ReactNodeViewProps } from './types.js'\nimport type { ReactNodeViewContextProps } from './useReactNodeView.js'\nimport { ReactNodeViewContext } from './useReactNodeView.js'\n\nexport interface ReactNodeViewRendererOptions extends NodeViewRendererOptions {\n /**\n * This function is called when the node view is updated.\n * It allows you to compare the old node with the new node and decide if the component should update.\n */\n update:\n | ((props: {\n oldNode: ProseMirrorNode\n oldDecorations: readonly Decoration[]\n oldInnerDecorations: DecorationSource\n newNode: ProseMirrorNode\n newDecorations: readonly Decoration[]\n innerDecorations: DecorationSource\n updateProps: () => void\n }) => boolean)\n | null\n /**\n * The tag name of the element wrapping the React component.\n */\n as?: string\n /**\n * The class name of the element wrapping the React component.\n */\n className?: string\n /**\n * Attributes that should be applied to the element wrapping the React component.\n * If this is a function, it will be called each time the node view is updated.\n * If this is an object, it will be applied once when the node view is mounted.\n */\n attrs?:\n | Record\n | ((props: { node: ProseMirrorNode; HTMLAttributes: Record }) => Record)\n}\n\nexport class ReactNodeView<\n T = HTMLElement,\n Component extends ComponentType> = ComponentType>,\n NodeEditor extends Editor = Editor,\n Options extends ReactNodeViewRendererOptions = ReactNodeViewRendererOptions,\n> extends NodeView {\n /**\n * The renderer instance.\n */\n renderer!: ReactRenderer>\n\n /**\n * The element that holds the rich-text content of the node.\n */\n contentDOMElement!: HTMLElement | null\n\n /**\n * The requestAnimationFrame ID used for selection updates.\n */\n selectionRafId: number | null = null\n\n constructor(component: Component, props: NodeViewRendererProps, options?: Partial) {\n super(component, props, options)\n\n if (!this.node.isLeaf) {\n if (this.options.contentDOMElementTag) {\n this.contentDOMElement = document.createElement(this.options.contentDOMElementTag)\n } else {\n this.contentDOMElement = document.createElement(this.node.isInline ? 'span' : 'div')\n }\n\n this.contentDOMElement.dataset.nodeViewContentReact = ''\n this.contentDOMElement.dataset.nodeViewWrapper = ''\n\n // For some reason the whiteSpace prop is not inherited properly in Chrome and Safari\n // With this fix it seems to work fine\n // See: https://github.com/ueberdosis/tiptap/issues/1197\n this.contentDOMElement.style.whiteSpace = 'inherit'\n\n const contentTarget = this.dom.querySelector('[data-node-view-content]')\n\n if (!contentTarget) {\n return\n }\n\n contentTarget.appendChild(this.contentDOMElement)\n }\n }\n\n private cachedExtensionWithSyncedStorage: NodeViewRendererProps['extension'] | null = null\n\n /**\n * Returns a proxy of the extension that redirects storage access to the editor's mutable storage.\n * This preserves the original prototype chain (instanceof checks, methods like configure/extend work).\n * Cached to avoid proxy creation on every update.\n */\n get extensionWithSyncedStorage(): NodeViewRendererProps['extension'] {\n if (!this.cachedExtensionWithSyncedStorage) {\n const editor = this.editor\n const extension = this.extension\n\n this.cachedExtensionWithSyncedStorage = new Proxy(extension, {\n get(target, prop, receiver) {\n if (prop === 'storage') {\n return editor.storage[extension.name as keyof typeof editor.storage] ?? {}\n }\n return Reflect.get(target, prop, receiver)\n },\n })\n }\n\n return this.cachedExtensionWithSyncedStorage\n }\n\n /**\n * Setup the React component.\n * Called on initialization.\n */\n mount() {\n const props = {\n editor: this.editor,\n node: this.node,\n decorations: this.decorations as DecorationWithType[],\n innerDecorations: this.innerDecorations,\n view: this.view,\n selected: false,\n extension: this.extensionWithSyncedStorage,\n HTMLAttributes: this.HTMLAttributes,\n getPos: () => this.getPos(),\n updateAttributes: (attributes = {}) => this.updateAttributes(attributes),\n deleteNode: () => this.deleteNode(),\n ref: createRef(),\n } satisfies ReactNodeViewProps\n\n if (!(this.component as any).displayName) {\n const capitalizeFirstChar = (string: string): string => {\n return string.charAt(0).toUpperCase() + string.substring(1)\n }\n\n this.component.displayName = capitalizeFirstChar(this.extension.name)\n }\n\n const onDragStart = this.onDragStart.bind(this)\n const nodeViewContentRef: ReactNodeViewContextProps['nodeViewContentRef'] = element => {\n if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {\n // remove the nodeViewWrapper attribute from the element\n if (element.hasAttribute('data-node-view-wrapper')) {\n element.removeAttribute('data-node-view-wrapper')\n }\n element.appendChild(this.contentDOMElement)\n }\n }\n const context = { onDragStart, nodeViewContentRef }\n const Component = this.component\n // For performance reasons, we memoize the provider component\n // And all of the things it requires are declared outside of the component, so it doesn't need to re-render\n const ReactNodeViewProvider: NamedExoticComponent> = memo(componentProps => {\n return (\n \n {createElement(Component, componentProps)}\n \n )\n })\n\n ReactNodeViewProvider.displayName = 'ReactNodeView'\n\n let as = this.node.isInline ? 'span' : 'div'\n\n if (this.options.as) {\n as = this.options.as\n }\n\n const { className = '' } = this.options\n\n this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this)\n\n this.renderer = new ReactRenderer(ReactNodeViewProvider, {\n editor: this.editor,\n props,\n as,\n className: `node-${this.node.type.name} ${className}`.trim(),\n })\n\n this.editor.on('selectionUpdate', this.handleSelectionUpdate)\n this.updateElementAttributes()\n }\n\n /**\n * Return the DOM element.\n * This is the element that will be used to display the node view.\n */\n get dom() {\n if (\n this.renderer.element.firstElementChild &&\n !this.renderer.element.firstElementChild?.hasAttribute('data-node-view-wrapper')\n ) {\n throw Error('Please use the NodeViewWrapper component for your node view.')\n }\n\n return this.renderer.element\n }\n\n /**\n * Return the content DOM element.\n * This is the element that will be used to display the rich-text content of the node.\n */\n get contentDOM() {\n if (this.node.isLeaf) {\n return null\n }\n\n return this.contentDOMElement\n }\n\n /**\n * On editor selection update, check if the node is selected.\n * If it is, call `selectNode`, otherwise call `deselectNode`.\n */\n handleSelectionUpdate() {\n if (this.selectionRafId) {\n cancelAnimationFrame(this.selectionRafId)\n this.selectionRafId = null\n }\n\n this.selectionRafId = requestAnimationFrame(() => {\n this.selectionRafId = null\n const { from, to } = this.editor.state.selection\n const pos = this.getPos()\n if (typeof pos !== 'number') {\n return\n }\n\n if (from <= pos && to >= pos + this.node.nodeSize) {\n if (this.renderer.props.selected) {\n return\n }\n\n this.selectNode()\n } else {\n if (!this.renderer.props.selected) {\n return\n }\n\n this.deselectNode()\n }\n })\n }\n\n /**\n * On update, update the React component.\n * To prevent unnecessary updates, the `update` option can be used.\n */\n update(node: Node, decorations: readonly Decoration[], innerDecorations: DecorationSource): boolean {\n const rerenderComponent = (props?: Record) => {\n this.renderer.updateProps(props)\n if (typeof this.options.attrs === 'function') {\n this.updateElementAttributes()\n }\n }\n\n if (node.type !== this.node.type) {\n return false\n }\n\n if (typeof this.options.update === 'function') {\n const oldNode = this.node\n const oldDecorations = this.decorations\n const oldInnerDecorations = this.innerDecorations\n\n this.node = node\n this.decorations = decorations\n this.innerDecorations = innerDecorations\n\n return this.options.update({\n oldNode,\n oldDecorations,\n newNode: node,\n newDecorations: decorations,\n oldInnerDecorations,\n innerDecorations,\n updateProps: () =>\n rerenderComponent({ node, decorations, innerDecorations, extension: this.extensionWithSyncedStorage }),\n })\n }\n\n if (node === this.node && this.decorations === decorations && this.innerDecorations === innerDecorations) {\n return true\n }\n\n this.node = node\n this.decorations = decorations\n this.innerDecorations = innerDecorations\n\n rerenderComponent({ node, decorations, innerDecorations, extension: this.extensionWithSyncedStorage })\n\n return true\n }\n\n /**\n * Select the node.\n * Add the `selected` prop and the `ProseMirror-selectednode` class.\n */\n selectNode() {\n this.renderer.updateProps({\n selected: true,\n })\n this.renderer.element.classList.add('ProseMirror-selectednode')\n }\n\n /**\n * Deselect the node.\n * Remove the `selected` prop and the `ProseMirror-selectednode` class.\n */\n deselectNode() {\n this.renderer.updateProps({\n selected: false,\n })\n this.renderer.element.classList.remove('ProseMirror-selectednode')\n }\n\n /**\n * Destroy the React component instance.\n */\n destroy() {\n this.renderer.destroy()\n this.editor.off('selectionUpdate', this.handleSelectionUpdate)\n this.contentDOMElement = null\n\n if (this.selectionRafId) {\n cancelAnimationFrame(this.selectionRafId)\n this.selectionRafId = null\n }\n }\n\n /**\n * Update the attributes of the top-level element that holds the React component.\n * Applying the attributes defined in the `attrs` option.\n */\n updateElementAttributes() {\n if (this.options.attrs) {\n let attrsObj: Record = {}\n\n if (typeof this.options.attrs === 'function') {\n const extensionAttributes = this.editor.extensionManager.attributes\n const HTMLAttributes = getRenderedAttributes(this.node, extensionAttributes)\n\n attrsObj = this.options.attrs({ node: this.node, HTMLAttributes })\n } else {\n attrsObj = this.options.attrs\n }\n\n this.renderer.updateAttributes(attrsObj)\n }\n }\n}\n\n/**\n * Create a React node view renderer.\n */\nexport function ReactNodeViewRenderer(\n component: ComponentType>,\n options?: Partial,\n): NodeViewRenderer {\n return props => {\n // try to get the parent component\n // this is important for vue devtools to show the component hierarchy correctly\n // maybe it’s `undefined` because isn’t rendered yet\n if (!(props.editor as EditorWithContentComponent).contentComponent) {\n return {} as unknown as ProseMirrorNodeView\n }\n\n return new ReactNodeView(component, props, options)\n }\n}\n", "import type { ReactNode } from 'react'\nimport { createContext, useContext, useMemo } from 'react'\n\nimport { EditorContext } from './Context.js'\nimport type { Editor, EditorContentProps, EditorStateSnapshot } from './index.js'\nimport { EditorContent, useEditorState } from './index.js'\n\n/**\n * The shape of the React context used by the `` components.\n *\n * The editor instance is always available when using the default `useEditor`\n * configuration. For SSR scenarios where `immediatelyRender: false` is used,\n * consider using the legacy `EditorProvider` pattern instead.\n */\nexport type TiptapContextType = {\n /** The Tiptap editor instance. */\n editor: Editor\n}\n\n/**\n * React context that stores the current editor instance.\n *\n * Use `useTiptap()` to read from this context in child components.\n */\nexport const TiptapContext = createContext({\n get editor(): Editor {\n throw new Error('useTiptap must be used within a provider')\n },\n})\n\nTiptapContext.displayName = 'TiptapContext'\n\n/**\n * Hook to read the Tiptap context and access the editor instance.\n *\n * This is a small convenience wrapper around `useContext(TiptapContext)`.\n * The editor is always available when used within a `` provider.\n *\n * @returns The current `TiptapContextType` value from the provider.\n *\n * @example\n * ```tsx\n * import { useTiptap } from '@tiptap/react'\n *\n * function Toolbar() {\n * const { editor } = useTiptap()\n *\n * return (\n * \n * )\n * }\n * ```\n */\nexport const useTiptap = () => useContext(TiptapContext)\n\n/**\n * Select a slice of the editor state using the context-provided editor.\n *\n * This is a thin wrapper around `useEditorState` that reads the `editor`\n * instance from `useTiptap()` so callers don't have to pass it manually.\n *\n * @typeParam TSelectorResult - The type returned by the selector.\n * @param selector - Function that receives the editor state snapshot and\n * returns the piece of state you want to subscribe to.\n * @param equalityFn - Optional function to compare previous/next selected\n * values and avoid unnecessary updates.\n * @returns The selected slice of the editor state.\n *\n * @example\n * ```tsx\n * function WordCount() {\n * const wordCount = useTiptapState(state => {\n * const text = state.editor.state.doc.textContent\n * return text.split(/\\s+/).filter(Boolean).length\n * })\n *\n * return {wordCount} words\n * }\n * ```\n */\nexport function useTiptapState(\n selector: (context: EditorStateSnapshot) => TSelectorResult,\n equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean,\n) {\n const { editor } = useTiptap()\n\n return useEditorState({\n editor,\n selector,\n equalityFn,\n })\n}\n\n/**\n * Props for the `Tiptap` root/provider component.\n */\nexport type TiptapWrapperProps = {\n /**\n * The editor instance to provide to child components.\n * Use `useEditor()` to create this instance.\n */\n editor?: Editor\n\n /**\n * @deprecated Use `editor` instead. Will be removed in the next major version.\n */\n instance?: Editor\n\n children: ReactNode\n}\n\n/**\n * Top-level provider component that makes the editor instance available via\n * React context to all child components.\n *\n * This component also provides backwards compatibility with the legacy\n * `EditorContext`, so components using `useCurrentEditor()` will work\n * inside a `` provider.\n *\n * @param props - Component props.\n * @returns A context provider element wrapping `children`.\n *\n * @example\n * ```tsx\n * import { Tiptap, useEditor } from '@tiptap/react'\n *\n * function App() {\n * const editor = useEditor({ extensions: [...] })\n *\n * return (\n * \n * \n * \n * \n * )\n * }\n * ```\n */\nexport function TiptapWrapper({ editor, instance, children }: TiptapWrapperProps) {\n const resolvedEditor = editor ?? instance\n\n if (!resolvedEditor) {\n throw new Error('Tiptap: An editor instance is required. Pass a non-null `editor` prop.')\n }\n\n const tiptapContextValue = useMemo(() => ({ editor: resolvedEditor }), [resolvedEditor])\n\n // Provide backwards compatibility with the legacy EditorContext\n // so components using useCurrentEditor() work inside \n const legacyContextValue = useMemo(() => ({ editor: resolvedEditor }), [resolvedEditor])\n\n return (\n \n {children}\n \n )\n}\n\nTiptapWrapper.displayName = 'Tiptap'\n\n/**\n * Convenience component that renders `EditorContent` using the context-provided\n * editor instance. Use this instead of manually passing the `editor` prop.\n *\n * @param props - All `EditorContent` props except `editor` and `ref`.\n * @returns An `EditorContent` element bound to the context editor.\n *\n * @example\n * ```tsx\n * // inside a Tiptap provider\n * \n * ```\n */\nexport function TiptapContent({ ...rest }: Omit) {\n const { editor } = useTiptap()\n\n return \n}\n\nTiptapContent.displayName = 'Tiptap.Content'\n\n/**\n * Root `Tiptap` component. Use it as the provider for all child components.\n *\n * The exported object includes the `Content` subcomponent for rendering the\n * editor content area.\n *\n * This component provides both the new `TiptapContext` (accessed via `useTiptap()`)\n * and the legacy `EditorContext` (accessed via `useCurrentEditor()`) for\n * backwards compatibility.\n *\n * For bubble menus and floating menus, import them separately from\n * `@tiptap/react/menus` to keep floating-ui as an optional dependency.\n *\n * @example\n * ```tsx\n * import { Tiptap, useEditor } from '@tiptap/react'\n * import { BubbleMenu } from '@tiptap/react/menus'\n *\n * function App() {\n * const editor = useEditor({ extensions: [...] })\n *\n * return (\n * \n * \n * \n * \n * \n * \n * )\n * }\n * ```\n */\nexport const Tiptap = Object.assign(TiptapWrapper, {\n /**\n * The Tiptap Content component that renders the EditorContent with the editor instance from the context.\n * @see TiptapContent\n */\n Content: TiptapContent,\n})\n\nexport default Tiptap\n", "export * from './Context.js'\nexport * from './EditorContent.js'\nexport * from './NodeViewContent.js'\nexport * from './NodeViewWrapper.js'\nexport * from './ReactMarkViewRenderer.js'\nexport * from './ReactNodeViewRenderer.js'\nexport * from './ReactRenderer.js'\nexport * from './Tiptap.js'\nexport * from './types.js'\nexport * from './useEditor.js'\nexport * from './useEditorState.js'\nexport * from './useReactNodeView.js'\nexport * from '@tiptap/core'\n", "import type {\n AnyEqualityComparator,\n Cache,\n CircularState,\n Dictionary,\n State,\n TypeEqualityComparator,\n} from './internalTypes.js';\n\nconst { getOwnPropertyNames, getOwnPropertySymbols } = Object;\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst { hasOwnProperty } = Object.prototype;\n\n/**\n * Combine two comparators into a single comparators.\n */\nexport function combineComparators(\n comparatorA: AnyEqualityComparator,\n comparatorB: AnyEqualityComparator,\n) {\n return function isEqual(a: A, b: B, state: State) {\n return comparatorA(a, b, state) && comparatorB(a, b, state);\n };\n}\n\n/**\n * Wrap the provided `areItemsEqual` method to manage the circular state, allowing\n * for circular references to be safely included in the comparison without creating\n * stack overflows.\n */\nexport function createIsCircular>(\n areItemsEqual: AreItemsEqual,\n): AreItemsEqual {\n return function isCircular(a: any, b: any, state: CircularState>) {\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\n return areItemsEqual(a, b, state);\n }\n\n const { cache } = state;\n\n const cachedA = cache.get(a);\n const cachedB = cache.get(b);\n\n if (cachedA && cachedB) {\n return cachedA === b && cachedB === a;\n }\n\n cache.set(a, b);\n cache.set(b, a);\n\n const result = areItemsEqual(a, b, state);\n\n cache.delete(a);\n cache.delete(b);\n\n return result;\n } as AreItemsEqual;\n}\n\n/**\n * Get the `@@toStringTag` of the value, if it exists.\n */\nexport function getShortTag(value: any): string | undefined {\n return value != null ? (value[Symbol.toStringTag] as string) : undefined;\n}\n\n/**\n * Get the properties to strictly examine, which include both own properties that are\n * not enumerable and symbol properties.\n */\nexport function getStrictProperties(object: Dictionary): Array {\n return (getOwnPropertyNames(object) as Array).concat(getOwnPropertySymbols(object));\n}\n\n/**\n * Whether the object contains the property passed as an own property.\n */\nexport const hasOwn =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Object.hasOwn || ((object: Dictionary, property: number | string | symbol) => hasOwnProperty.call(object, property));\n\n/**\n * Whether the values passed are strictly equal or both NaN.\n */\nexport function sameValueZeroEqual(a: any, b: any): boolean {\n return a === b || (!a && !b && a !== a && b !== b);\n}\n", "import type { Dictionary, PrimitiveWrapper, State, TypedArray } from './internalTypes.js';\nimport { getStrictProperties, hasOwn, sameValueZeroEqual } from './utils.js';\n\nconst PREACT_VNODE = '__v';\nconst PREACT_OWNER = '__o';\nconst REACT_OWNER = '_owner';\n\nconst { getOwnPropertyDescriptor, keys } = Object;\n\n/**\n * Whether the array buffers are equal in value.\n */\nexport function areArrayBuffersEqual(a: ArrayBuffer, b: ArrayBuffer): boolean {\n return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b));\n}\n\n/**\n * Whether the arrays are equal in value.\n */\nexport function areArraysEqual(a: any[], b: any[], state: State) {\n let index = a.length;\n\n if (b.length !== index) {\n return false;\n }\n\n while (index-- > 0) {\n if (!state.equals(a[index], b[index], index, index, a, b, state)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the dataviews are equal in value.\n */\nexport function areDataViewsEqual(a: DataView, b: DataView): boolean {\n return (\n a.byteLength === b.byteLength\n && areTypedArraysEqual(\n new Uint8Array(a.buffer, a.byteOffset, a.byteLength),\n new Uint8Array(b.buffer, b.byteOffset, b.byteLength),\n )\n );\n}\n\n/**\n * Whether the dates passed are equal in value.\n */\nexport function areDatesEqual(a: Date, b: Date): boolean {\n return sameValueZeroEqual(a.getTime(), b.getTime());\n}\n\n/**\n * Whether the errors passed are equal in value.\n */\nexport function areErrorsEqual(a: Error, b: Error): boolean {\n return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack;\n}\n\n/**\n * Whether the functions passed are equal in value.\n */\nexport function areFunctionsEqual(a: (...args: any[]) => any, b: (...args: any[]) => any): boolean {\n return a === b;\n}\n\n/**\n * Whether the `Map`s are equal in value.\n */\nexport function areMapsEqual(a: Map, b: Map, state: State): boolean {\n const size = a.size;\n\n if (size !== b.size) {\n return false;\n }\n\n if (!size) {\n return true;\n }\n\n const matchedIndices = new Array(size);\n const aIterable = a.entries();\n\n let aResult: IteratorResult<[any, any]>;\n let bResult: IteratorResult<[any, any]>;\n let index = 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n\n const bIterable = b.entries();\n\n let hasMatch = false;\n let matchIndex = 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n\n if (matchedIndices[matchIndex]) {\n matchIndex++;\n continue;\n }\n\n const aEntry = aResult.value;\n const bEntry = bResult.value;\n\n if (\n state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state)\n && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)\n ) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n\n matchIndex++;\n }\n\n if (!hasMatch) {\n return false;\n }\n\n index++;\n }\n\n return true;\n}\n\n/**\n * Whether the numbers are equal in value.\n */\nexport const areNumbersEqual = sameValueZeroEqual;\n\n/**\n * Whether the objects are equal in value.\n */\nexport function areObjectsEqual(a: Dictionary, b: Dictionary, state: State): boolean {\n const properties = keys(a);\n\n let index = properties.length;\n\n if (keys(b).length !== index) {\n return false;\n }\n\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n if (!isPropertyEqual(a, b, state, properties[index]!)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the objects are equal in value with strict property checking.\n */\nexport function areObjectsEqualStrict(a: Dictionary, b: Dictionary, state: State): boolean {\n const properties = getStrictProperties(a);\n\n let index = properties.length;\n\n if (getStrictProperties(b).length !== index) {\n return false;\n }\n\n let property: string | symbol;\n let descriptorA: ReturnType;\n let descriptorB: ReturnType;\n\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n property = properties[index]!;\n\n if (!isPropertyEqual(a, b, state, property)) {\n return false;\n }\n\n descriptorA = getOwnPropertyDescriptor(a, property);\n descriptorB = getOwnPropertyDescriptor(b, property);\n\n if (\n (descriptorA || descriptorB)\n && (!descriptorA\n || !descriptorB\n || descriptorA.configurable !== descriptorB.configurable\n || descriptorA.enumerable !== descriptorB.enumerable\n || descriptorA.writable !== descriptorB.writable)\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the primitive wrappers passed are equal in value.\n */\nexport function arePrimitiveWrappersEqual(a: PrimitiveWrapper, b: PrimitiveWrapper): boolean {\n return sameValueZeroEqual(a.valueOf(), b.valueOf());\n}\n\n/**\n * Whether the regexps passed are equal in value.\n */\nexport function areRegExpsEqual(a: RegExp, b: RegExp): boolean {\n return a.source === b.source && a.flags === b.flags;\n}\n\n/**\n * Whether the `Set`s are equal in value.\n */\nexport function areSetsEqual(a: Set, b: Set, state: State): boolean {\n const size = a.size;\n\n if (size !== b.size) {\n return false;\n }\n\n if (!size) {\n return true;\n }\n\n const matchedIndices = new Array(size);\n const aIterable = a.values();\n\n let aResult: IteratorResult;\n let bResult: IteratorResult;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n\n const bIterable = b.values();\n\n let hasMatch = false;\n let matchIndex = 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n\n if (\n !matchedIndices[matchIndex]\n && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)\n ) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n\n matchIndex++;\n }\n\n if (!hasMatch) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the TypedArray instances are equal in value.\n */\nexport function areTypedArraysEqual(a: TypedArray, b: TypedArray) {\n let index = a.byteLength;\n\n if (b.byteLength !== index || a.byteOffset !== b.byteOffset) {\n return false;\n }\n\n while (index-- > 0) {\n if (a[index] !== b[index]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Whether the URL instances are equal in value.\n */\nexport function areUrlsEqual(a: URL, b: URL): boolean {\n return (\n a.hostname === b.hostname\n && a.pathname === b.pathname\n && a.protocol === b.protocol\n && a.port === b.port\n && a.hash === b.hash\n && a.username === b.username\n && a.password === b.password\n );\n}\n\nfunction isPropertyEqual(a: Dictionary, b: Dictionary, state: State, property: string | symbol) {\n if (\n (property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE)\n && (a.$$typeof || b.$$typeof)\n ) {\n return true;\n }\n\n return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state);\n}\n", "import {\n areArrayBuffersEqual,\n areArraysEqual as areArraysEqualDefault,\n areDataViewsEqual,\n areDatesEqual as areDatesEqualDefault,\n areErrorsEqual as areErrorsEqualDefault,\n areFunctionsEqual as areFunctionsEqualDefault,\n areMapsEqual as areMapsEqualDefault,\n areNumbersEqual as areNumbersEqualDefault,\n areObjectsEqual as areObjectsEqualDefault,\n areObjectsEqualStrict as areObjectsEqualStrictDefault,\n arePrimitiveWrappersEqual as arePrimitiveWrappersEqualDefault,\n areRegExpsEqual as areRegExpsEqualDefault,\n areSetsEqual as areSetsEqualDefault,\n areTypedArraysEqual as areTypedArraysEqualDefault,\n areUrlsEqual as areUrlsEqualDefault,\n} from './equals.js';\nimport type {\n ComparatorConfig,\n CreateState,\n CustomEqualCreatorOptions,\n EqualityComparator,\n InternalEqualityComparator,\n State,\n} from './internalTypes.js';\nimport { combineComparators, createIsCircular, getShortTag } from './utils.js';\n\nconst ARRAY_BUFFER_TAG = '[object ArrayBuffer]';\nconst ARGUMENTS_TAG = '[object Arguments]';\nconst BOOLEAN_TAG = '[object Boolean]';\nconst DATA_VIEW_TAG = '[object DataView]';\nconst DATE_TAG = '[object Date]';\nconst ERROR_TAG = '[object Error]';\nconst MAP_TAG = '[object Map]';\nconst NUMBER_TAG = '[object Number]';\nconst OBJECT_TAG = '[object Object]';\nconst REG_EXP_TAG = '[object RegExp]';\nconst SET_TAG = '[object Set]';\nconst STRING_TAG = '[object String]';\nconst TYPED_ARRAY_TAGS: Record = {\n '[object Int8Array]': true,\n '[object Uint8Array]': true,\n '[object Uint8ClampedArray]': true,\n '[object Int16Array]': true,\n '[object Uint16Array]': true,\n '[object Int32Array]': true,\n '[object Uint32Array]': true,\n '[object Float16Array]': true,\n '[object Float32Array]': true,\n '[object Float64Array]': true,\n '[object BigInt64Array]': true,\n '[object BigUint64Array]': true,\n};\nconst URL_TAG = '[object URL]';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst toString = Object.prototype.toString;\n\ninterface CreateIsEqualOptions {\n circular: boolean;\n comparator: EqualityComparator;\n createState: CreateState | undefined;\n equals: InternalEqualityComparator;\n strict: boolean;\n}\n\n/**\n * Create a comparator method based on the type-specific equality comparators passed.\n */\nexport function createEqualityComparator({\n areArrayBuffersEqual,\n areArraysEqual,\n areDataViewsEqual,\n areDatesEqual,\n areErrorsEqual,\n areFunctionsEqual,\n areMapsEqual,\n areNumbersEqual,\n areObjectsEqual,\n arePrimitiveWrappersEqual,\n areRegExpsEqual,\n areSetsEqual,\n areTypedArraysEqual,\n areUrlsEqual,\n unknownTagComparators,\n}: ComparatorConfig): EqualityComparator {\n /**\n * compare the value of the two objects and return true if they are equivalent in values\n */\n return function comparator(a: any, b: any, state: State): boolean {\n // If the items are strictly equal, no need to do a value comparison.\n if (a === b) {\n return true;\n }\n\n // If either of the items are nullish and fail the strictly equal check\n // above, then they must be unequal.\n if (a == null || b == null) {\n return false;\n }\n\n const type = typeof a;\n\n if (type !== typeof b) {\n return false;\n }\n\n if (type !== 'object') {\n if (type === 'number') {\n return areNumbersEqual(a, b, state);\n }\n\n if (type === 'function') {\n return areFunctionsEqual(a, b, state);\n }\n\n // If a primitive value that is not strictly equal, it must be unequal.\n return false;\n }\n\n const constructor = a.constructor;\n\n // Checks are listed in order of commonality of use-case:\n // 1. Common complex object types (plain object, array)\n // 2. Common data values (date, regexp)\n // 3. Less-common complex object types (map, set)\n // 4. Less-common data values (promise, primitive wrappers)\n // Inherently this is both subjective and assumptive, however\n // when reviewing comparable libraries in the wild this order\n // appears to be generally consistent.\n\n // Constructors should match, otherwise there is potential for false positives\n // between class and subclass or custom object and POJO.\n if (constructor !== b.constructor) {\n return false;\n }\n\n // `isPlainObject` only checks against the object's own realm. Cross-realm\n // comparisons are rare, and will be handled in the ultimate fallback, so\n // we can avoid capturing the string tag.\n if (constructor === Object) {\n return areObjectsEqual(a, b, state);\n }\n\n // `isArray()` works on subclasses and is cross-realm, so we can avoid capturing\n // the string tag or doing an `instanceof` check.\n if (Array.isArray(a)) {\n return areArraysEqual(a, b, state);\n }\n\n // Try to fast-path equality checks for other complex object types in the\n // same realm to avoid capturing the string tag. Strict equality is used\n // instead of `instanceof` because it is more performant for the common\n // use-case. If someone is subclassing a native class, it will be handled\n // with the string tag comparison.\n\n if (constructor === Date) {\n return areDatesEqual(a, b, state);\n }\n\n if (constructor === RegExp) {\n return areRegExpsEqual(a, b, state);\n }\n\n if (constructor === Map) {\n return areMapsEqual(a, b, state);\n }\n\n if (constructor === Set) {\n return areSetsEqual(a, b, state);\n }\n\n // Since this is a custom object, capture the string tag to determing its type.\n // This is reasonably performant in modern environments like v8 and SpiderMonkey.\n const tag = toString.call(a);\n\n if (tag === DATE_TAG) {\n return areDatesEqual(a, b, state);\n }\n\n // For RegExp, the properties are not enumerable, and therefore will give false positives if\n // tested like a standard object.\n if (tag === REG_EXP_TAG) {\n return areRegExpsEqual(a, b, state);\n }\n\n if (tag === MAP_TAG) {\n return areMapsEqual(a, b, state);\n }\n\n if (tag === SET_TAG) {\n return areSetsEqual(a, b, state);\n }\n\n if (tag === OBJECT_TAG) {\n // The exception for value comparison is custom `Promise`-like class instances. These should\n // be treated the same as standard `Promise` objects, which means strict equality, and if\n // it reaches this point then that strict equality comparison has already failed.\n return typeof a.then !== 'function' && typeof b.then !== 'function' && areObjectsEqual(a, b, state);\n }\n\n // If a URL tag, it should be tested explicitly. Like RegExp, the properties are not\n // enumerable, and therefore will give false positives if tested like a standard object.\n if (tag === URL_TAG) {\n return areUrlsEqual(a, b, state);\n }\n\n // If an error tag, it should be tested explicitly. Like RegExp, the properties are not\n // enumerable, and therefore will give false positives if tested like a standard object.\n if (tag === ERROR_TAG) {\n return areErrorsEqual(a, b, state);\n }\n\n // If an arguments tag, it should be treated as a standard object.\n if (tag === ARGUMENTS_TAG) {\n return areObjectsEqual(a, b, state);\n }\n\n if (TYPED_ARRAY_TAGS[tag]) {\n return areTypedArraysEqual(a, b, state);\n }\n\n if (tag === ARRAY_BUFFER_TAG) {\n return areArrayBuffersEqual(a, b, state);\n }\n\n if (tag === DATA_VIEW_TAG) {\n return areDataViewsEqual(a, b, state);\n }\n\n // As the penultimate fallback, check if the values passed are primitive wrappers. This\n // is very rare in modern JS, which is why it is deprioritized compared to all other object\n // types.\n if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) {\n return arePrimitiveWrappersEqual(a, b, state);\n }\n\n if (unknownTagComparators) {\n let unknownTagComparator = unknownTagComparators[tag];\n\n if (!unknownTagComparator) {\n const shortTag = getShortTag(a);\n\n if (shortTag) {\n unknownTagComparator = unknownTagComparators[shortTag];\n }\n }\n\n // If the custom config has an unknown tag comparator that matches the captured tag or the\n // @@toStringTag, it is the source of truth for whether the values are equal.\n if (unknownTagComparator) {\n return unknownTagComparator(a, b, state);\n }\n }\n\n // If not matching any tags that require a specific type of comparison, then we hard-code false because\n // the only thing remaining is strict equality, which has already been compared. This is for a few reasons:\n // - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only\n // comparison that can be made.\n // - For types that can be introspected, but rarely have requirements to be compared\n // (`ArrayBuffer`, `DataView`, etc.), the cost is avoided to prioritize the common\n // use-cases (may be included in a future release, if requested enough).\n // - For types that can be introspected but do not have an objective definition of what\n // equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare.\n // In all cases, these decisions should be reevaluated based on changes to the language and\n // common development practices.\n return false;\n };\n}\n\n/**\n * Create the configuration object used for building comparators.\n */\nexport function createEqualityComparatorConfig({\n circular,\n createCustomConfig,\n strict,\n}: CustomEqualCreatorOptions): ComparatorConfig {\n let config = {\n areArrayBuffersEqual,\n areArraysEqual: strict ? areObjectsEqualStrictDefault : areArraysEqualDefault,\n areDataViewsEqual,\n areDatesEqual: areDatesEqualDefault,\n areErrorsEqual: areErrorsEqualDefault,\n areFunctionsEqual: areFunctionsEqualDefault,\n areMapsEqual: strict ? combineComparators(areMapsEqualDefault, areObjectsEqualStrictDefault) : areMapsEqualDefault,\n areNumbersEqual: areNumbersEqualDefault,\n areObjectsEqual: strict ? areObjectsEqualStrictDefault : areObjectsEqualDefault,\n arePrimitiveWrappersEqual: arePrimitiveWrappersEqualDefault,\n areRegExpsEqual: areRegExpsEqualDefault,\n areSetsEqual: strict ? combineComparators(areSetsEqualDefault, areObjectsEqualStrictDefault) : areSetsEqualDefault,\n areTypedArraysEqual: strict\n ? combineComparators(areTypedArraysEqualDefault, areObjectsEqualStrictDefault)\n : areTypedArraysEqualDefault,\n areUrlsEqual: areUrlsEqualDefault,\n unknownTagComparators: undefined,\n };\n\n if (createCustomConfig) {\n config = Object.assign({}, config, createCustomConfig(config));\n }\n\n if (circular) {\n const areArraysEqual = createIsCircular(config.areArraysEqual);\n const areMapsEqual = createIsCircular(config.areMapsEqual);\n const areObjectsEqual = createIsCircular(config.areObjectsEqual);\n const areSetsEqual = createIsCircular(config.areSetsEqual);\n\n config = Object.assign({}, config, {\n areArraysEqual,\n areMapsEqual,\n areObjectsEqual,\n areSetsEqual,\n });\n }\n\n return config;\n}\n\n/**\n * Default equality comparator pass-through, used as the standard `isEqual` creator for\n * use inside the built comparator.\n */\nexport function createInternalEqualityComparator(\n compare: EqualityComparator,\n): InternalEqualityComparator {\n return function (\n a: any,\n b: any,\n _indexOrKeyA: any,\n _indexOrKeyB: any,\n _parentA: any,\n _parentB: any,\n state: State,\n ) {\n return compare(a, b, state);\n };\n}\n\n/**\n * Create the `isEqual` function used by the consuming application.\n */\nexport function createIsEqual({ circular, comparator, createState, equals, strict }: CreateIsEqualOptions) {\n if (createState) {\n return function isEqual(a: A, b: B): boolean {\n const { cache = circular ? new WeakMap() : undefined, meta } = createState();\n\n return comparator(a, b, {\n cache,\n equals,\n meta,\n strict,\n } as State);\n };\n }\n\n if (circular) {\n return function isEqual(a: A, b: B): boolean {\n return comparator(a, b, {\n cache: new WeakMap(),\n equals,\n meta: undefined as Meta,\n strict,\n } as State);\n };\n }\n\n const state = {\n cache: undefined,\n equals,\n meta: undefined,\n strict,\n } as State;\n\n return function isEqual(a: A, b: B): boolean {\n return comparator(a, b, state);\n };\n}\n", "import {\n createEqualityComparatorConfig,\n createEqualityComparator,\n createInternalEqualityComparator,\n createIsEqual,\n} from './comparator.js';\nimport type { CustomEqualCreatorOptions } from './internalTypes.js';\nimport { sameValueZeroEqual } from './utils.js';\n\nexport { sameValueZeroEqual };\nexport type {\n AnyEqualityComparator,\n Cache,\n CircularState,\n ComparatorConfig,\n CreateCustomComparatorConfig,\n CreateState,\n CustomEqualCreatorOptions,\n DefaultState,\n Dictionary,\n EqualityComparator,\n EqualityComparatorCreator,\n InternalEqualityComparator,\n PrimitiveWrapper,\n State,\n TypeEqualityComparator,\n TypedArray,\n} from './internalTypes.js';\n\n/**\n * Whether the items passed are deeply-equal in value.\n */\nexport const deepEqual = createCustomEqual();\n\n/**\n * Whether the items passed are deeply-equal in value based on strict comparison.\n */\nexport const strictDeepEqual = createCustomEqual({ strict: true });\n\n/**\n * Whether the items passed are deeply-equal in value, including circular references.\n */\nexport const circularDeepEqual = createCustomEqual({ circular: true });\n\n/**\n * Whether the items passed are deeply-equal in value, including circular references,\n * based on strict comparison.\n */\nexport const strictCircularDeepEqual = createCustomEqual({\n circular: true,\n strict: true,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value.\n */\nexport const shallowEqual = createCustomEqual({\n createInternalComparator: () => sameValueZeroEqual,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value based on strict comparison\n */\nexport const strictShallowEqual = createCustomEqual({\n strict: true,\n createInternalComparator: () => sameValueZeroEqual,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value, including circular references.\n */\nexport const circularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueZeroEqual,\n});\n\n/**\n * Whether the items passed are shallowly-equal in value, including circular references,\n * based on strict comparison.\n */\nexport const strictCircularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueZeroEqual,\n strict: true,\n});\n\n/**\n * Create a custom equality comparison method.\n *\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\n * where the standard methods are not performant enough, but can also be used to provide\n * support for legacy environments that do not support expected features like\n * `RegExp.prototype.flags` out of the box.\n */\nexport function createCustomEqual(options: CustomEqualCreatorOptions = {}) {\n const {\n circular = false,\n createInternalComparator: createCustomInternalComparator,\n createState,\n strict = false,\n } = options;\n\n const config = createEqualityComparatorConfig(options);\n const comparator = createEqualityComparator(config);\n const equals = createCustomInternalComparator\n ? createCustomInternalComparator(comparator)\n : createInternalEqualityComparator(comparator);\n\n return createIsEqual({ circular, comparator, createState, equals, strict });\n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OAAO,OAAO,eAAe;;;;;EAKjD,SAAS;AACX,CAAC;", + "names": ["React", "useState", "useLayoutEffect", "useEffect", "useDebugValue", "React", "useSyncExternalStore", "useRef", "useEffect", "useMemo", "useDebugValue", "import_react", "import_react", "import_shim", "areArrayBuffersEqual", "areArraysEqual", "areDataViewsEqual", "areDatesEqual", "areErrorsEqual", "areFunctionsEqual", "areMapsEqual", "areNumbersEqual", "areObjectsEqual", "arePrimitiveWrappersEqual", "areRegExpsEqual", "areSetsEqual", "areTypedArraysEqual", "areUrlsEqual", "areObjectsEqualStrictDefault", "areArraysEqualDefault", "areMapsEqualDefault", "areObjectsEqualDefault", "areSetsEqualDefault", "areTypedArraysEqualDefault", "import_react", "import_jsx_runtime", "import_react", "import_react_dom", "import_jsx_runtime", "import_react", "import_jsx_runtime", "ReactDOM", "React", "useState", "useSyncExternalStore", "useDebugValue", "useEffect", "jsxs", "jsx", "createContext", "useContext", "reactVersion", "componentProps", "createElement", "useMemo"] +} diff --git a/frontend/node_modules/.vite/deps/@tiptap_starter-kit.js b/frontend/node_modules/.vite/deps/@tiptap_starter-kit.js new file mode 100644 index 00000000..0e994a49 --- /dev/null +++ b/frontend/node_modules/.vite/deps/@tiptap_starter-kit.js @@ -0,0 +1,3464 @@ +import { + Link +} from "./chunk-MX7X7RGK.js"; +import { + Decoration, + DecorationSet, + Extension, + Fragment, + Mapping, + Mark, + Node3, + NodeSelection, + Plugin, + PluginKey, + Selection, + Slice, + TextSelection, + callOrReturn, + canInsertNode, + dropPoint, + getExtensionField, + getNodeAtPosition, + getNodeType, + getRenderedAttributes, + isAtEndOfNode, + isAtStartOfNode, + isNodeActive, + isNodeEmpty, + isNodeSelection, + keydownHandler, + markInputRule, + markPasteRule, + mergeAttributes, + nodeInputRule, + parseIndentedBlocks, + renderNestedMarkdownContent, + textblockTypeInputRule, + wrappingInputRule +} from "./chunk-YRIELJS7.js"; +import "./chunk-4MBMRILA.js"; + +// node_modules/@tiptap/core/dist/jsx-runtime/jsx-runtime.js +var h = (tag, attributes) => { + if (tag === "slot") { + return 0; + } + if (tag instanceof Function) { + return tag(attributes); + } + const { children, ...rest } = attributes != null ? attributes : {}; + if (tag === "svg") { + throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead"); + } + return [tag, rest, children]; +}; + +// node_modules/@tiptap/extension-blockquote/dist/index.js +var inputRegex = /^\s*>\s$/; +var Blockquote = Node3.create({ + name: "blockquote", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + content: "block+", + group: "block", + defining: true, + parseHTML() { + return [{ tag: "blockquote" }]; + }, + renderHTML({ HTMLAttributes }) { + return h("blockquote", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: h("slot", {}) }); + }, + parseMarkdown: (token, helpers) => { + return helpers.createNode("blockquote", void 0, helpers.parseChildren(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + const prefix = ">"; + const result = []; + node.content.forEach((child) => { + const childContent = h2.renderChildren([child]); + const lines = childContent.split("\n"); + const linesWithPrefix = lines.map((line) => { + if (line.trim() === "") { + return prefix; + } + return `${prefix} ${line}`; + }); + result.push(linesWithPrefix.join("\n")); + }); + return result.join(` +${prefix} +`); + }, + addCommands() { + return { + setBlockquote: () => ({ commands }) => { + return commands.wrapIn(this.name); + }, + toggleBlockquote: () => ({ commands }) => { + return commands.toggleWrap(this.name); + }, + unsetBlockquote: () => ({ commands }) => { + return commands.lift(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-b": () => this.editor.commands.toggleBlockquote() + }; + }, + addInputRules() { + return [ + wrappingInputRule({ + find: inputRegex, + type: this.type + }) + ]; + } +}); + +// node_modules/@tiptap/extension-bold/dist/index.js +var starInputRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/; +var starPasteRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g; +var underscoreInputRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/; +var underscorePasteRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g; +var Bold = Mark.create({ + name: "bold", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "strong" + }, + { + tag: "b", + getAttrs: (node) => node.style.fontWeight !== "normal" && null + }, + { + style: "font-weight=400", + clearMark: (mark) => mark.type.name === this.name + }, + { + style: "font-weight", + getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return h("strong", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: h("slot", {}) }); + }, + markdownTokenName: "strong", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("bold", helpers.parseInline(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + return `**${h2.renderChildren(node)}**`; + }, + addCommands() { + return { + setBold: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleBold: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetBold: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-b": () => this.editor.commands.toggleBold(), + "Mod-B": () => this.editor.commands.toggleBold() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: starInputRegex, + type: this.type + }), + markInputRule({ + find: underscoreInputRegex, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: starPasteRegex, + type: this.type + }), + markPasteRule({ + find: underscorePasteRegex, + type: this.type + }) + ]; + } +}); + +// node_modules/@tiptap/extension-code/dist/index.js +var inputRegex2 = /(^|[^`])`([^`]+)`(?!`)$/; +var pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g; +var Code = Mark.create({ + name: "code", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + excludes: "_", + code: true, + exitable: true, + parseHTML() { + return [{ tag: "code" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["code", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "codespan", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("code", [{ type: "text", text: token.text || "" }]); + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return `\`${h2.renderChildren(node.content)}\``; + }, + addCommands() { + return { + setCode: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleCode: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetCode: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-e": () => this.editor.commands.toggleCode() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: inputRegex2, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: pasteRegex, + type: this.type + }) + ]; + } +}); + +// node_modules/@tiptap/extension-code-block/dist/index.js +var DEFAULT_TAB_SIZE = 4; +var backtickInputRegex = /^```([a-z]+)?[\s\n]$/; +var tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/; +var CodeBlock = Node3.create({ + name: "codeBlock", + addOptions() { + return { + languageClassPrefix: "language-", + exitOnTripleEnter: true, + exitOnArrowDown: true, + defaultLanguage: null, + enableTabIndentation: false, + tabSize: DEFAULT_TAB_SIZE, + HTMLAttributes: {} + }; + }, + content: "text*", + marks: "", + group: "block", + code: true, + defining: true, + addAttributes() { + return { + language: { + default: this.options.defaultLanguage, + parseHTML: (element) => { + var _a; + const { languageClassPrefix } = this.options; + if (!languageClassPrefix) { + return null; + } + const classNames = [...((_a = element.firstElementChild) == null ? void 0 : _a.classList) || []]; + const languages = classNames.filter((className) => className.startsWith(languageClassPrefix)).map((className) => className.replace(languageClassPrefix, "")); + const language = languages[0]; + if (!language) { + return null; + } + return language; + }, + rendered: false + } + }; + }, + parseHTML() { + return [ + { + tag: "pre", + preserveWhitespace: "full" + } + ]; + }, + renderHTML({ node, HTMLAttributes }) { + return [ + "pre", + mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), + [ + "code", + { + class: node.attrs.language ? this.options.languageClassPrefix + node.attrs.language : null + }, + 0 + ] + ]; + }, + markdownTokenName: "code", + parseMarkdown: (token, helpers) => { + var _a; + if (((_a = token.raw) == null ? void 0 : _a.startsWith("```")) === false && token.codeBlockStyle !== "indented") { + return []; + } + return helpers.createNode( + "codeBlock", + { language: token.lang || null }, + token.text ? [helpers.createTextNode(token.text)] : [] + ); + }, + renderMarkdown: (node, h2) => { + var _a; + let output = ""; + const language = ((_a = node.attrs) == null ? void 0 : _a.language) || ""; + if (!node.content) { + output = `\`\`\`${language} + +\`\`\``; + } else { + const lines = [`\`\`\`${language}`, h2.renderChildren(node.content), "```"]; + output = lines.join("\n"); + } + return output; + }, + addCommands() { + return { + setCodeBlock: (attributes) => ({ commands }) => { + return commands.setNode(this.name, attributes); + }, + toggleCodeBlock: (attributes) => ({ commands }) => { + return commands.toggleNode(this.name, "paragraph", attributes); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Alt-c": () => this.editor.commands.toggleCodeBlock(), + // remove code block when at start of document or code block is empty + Backspace: () => { + const { empty, $anchor } = this.editor.state.selection; + const isAtStart = $anchor.pos === 1; + if (!empty || $anchor.parent.type.name !== this.name) { + return false; + } + if (isAtStart || !$anchor.parent.textContent.length) { + return this.editor.commands.clearNodes(); + } + return false; + }, + // handle tab indentation + Tab: ({ editor }) => { + var _a; + if (!this.options.enableTabIndentation) { + return false; + } + const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE; + const { state } = editor; + const { selection } = state; + const { $from, empty } = selection; + if ($from.parent.type !== this.type) { + return false; + } + const indent = " ".repeat(tabSize); + if (empty) { + return editor.commands.insertContent(indent); + } + return editor.commands.command(({ tr }) => { + const { from: from2, to } = selection; + const text = state.doc.textBetween(from2, to, "\n", "\n"); + const lines = text.split("\n"); + const indentedText = lines.map((line) => indent + line).join("\n"); + tr.replaceWith(from2, to, state.schema.text(indentedText)); + return true; + }); + }, + // handle shift+tab reverse indentation + "Shift-Tab": ({ editor }) => { + var _a; + if (!this.options.enableTabIndentation) { + return false; + } + const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE; + const { state } = editor; + const { selection } = state; + const { $from, empty } = selection; + if ($from.parent.type !== this.type) { + return false; + } + if (empty) { + return editor.commands.command(({ tr }) => { + var _a2; + const { pos } = $from; + const codeBlockStart = $from.start(); + const codeBlockEnd = $from.end(); + const allText = state.doc.textBetween(codeBlockStart, codeBlockEnd, "\n", "\n"); + const lines = allText.split("\n"); + let currentLineIndex = 0; + let charCount = 0; + const relativeCursorPos = pos - codeBlockStart; + for (let i = 0; i < lines.length; i += 1) { + if (charCount + lines[i].length >= relativeCursorPos) { + currentLineIndex = i; + break; + } + charCount += lines[i].length + 1; + } + const currentLine = lines[currentLineIndex]; + const leadingSpaces = ((_a2 = currentLine.match(/^ */)) == null ? void 0 : _a2[0]) || ""; + const spacesToRemove = Math.min(leadingSpaces.length, tabSize); + if (spacesToRemove === 0) { + return true; + } + let lineStartPos = codeBlockStart; + for (let i = 0; i < currentLineIndex; i += 1) { + lineStartPos += lines[i].length + 1; + } + tr.delete(lineStartPos, lineStartPos + spacesToRemove); + const cursorPosInLine = pos - lineStartPos; + if (cursorPosInLine <= spacesToRemove) { + tr.setSelection(TextSelection.create(tr.doc, lineStartPos)); + } + return true; + }); + } + return editor.commands.command(({ tr }) => { + const { from: from2, to } = selection; + const text = state.doc.textBetween(from2, to, "\n", "\n"); + const lines = text.split("\n"); + const reverseIndentText = lines.map((line) => { + var _a2; + const leadingSpaces = ((_a2 = line.match(/^ */)) == null ? void 0 : _a2[0]) || ""; + const spacesToRemove = Math.min(leadingSpaces.length, tabSize); + return line.slice(spacesToRemove); + }).join("\n"); + tr.replaceWith(from2, to, state.schema.text(reverseIndentText)); + return true; + }); + }, + // exit node on triple enter + Enter: ({ editor }) => { + if (!this.options.exitOnTripleEnter) { + return false; + } + const { state } = editor; + const { selection } = state; + const { $from, empty } = selection; + if (!empty || $from.parent.type !== this.type) { + return false; + } + const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2; + const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n"); + if (!isAtEnd || !endsWithDoubleNewline) { + return false; + } + return editor.chain().command(({ tr }) => { + tr.delete($from.pos - 2, $from.pos); + return true; + }).exitCode().run(); + }, + // exit node on arrow down + ArrowDown: ({ editor }) => { + if (!this.options.exitOnArrowDown) { + return false; + } + const { state } = editor; + const { selection, doc } = state; + const { $from, empty } = selection; + if (!empty || $from.parent.type !== this.type) { + return false; + } + const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2; + if (!isAtEnd) { + return false; + } + const after = $from.after(); + if (after === void 0) { + return false; + } + const nodeAfter = doc.nodeAt(after); + if (nodeAfter) { + return editor.commands.command(({ tr }) => { + tr.setSelection(Selection.near(doc.resolve(after))); + return true; + }); + } + return editor.commands.exitCode(); + } + }; + }, + addInputRules() { + return [ + textblockTypeInputRule({ + find: backtickInputRegex, + type: this.type, + getAttributes: (match) => ({ + language: match[1] + }) + }), + textblockTypeInputRule({ + find: tildeInputRegex, + type: this.type, + getAttributes: (match) => ({ + language: match[1] + }) + }) + ]; + }, + addProseMirrorPlugins() { + return [ + // this plugin creates a code block for pasted content from VS Code + // we can also detect the copied code language + new Plugin({ + key: new PluginKey("codeBlockVSCodeHandler"), + props: { + handlePaste: (view, event) => { + if (!event.clipboardData) { + return false; + } + if (this.editor.isActive(this.type.name)) { + return false; + } + const text = event.clipboardData.getData("text/plain"); + const vscode = event.clipboardData.getData("vscode-editor-data"); + const vscodeData = vscode ? JSON.parse(vscode) : void 0; + const language = vscodeData == null ? void 0 : vscodeData.mode; + if (!text || !language) { + return false; + } + const { tr, schema } = view.state; + const textNode = schema.text(text.replace(/\r\n?/g, "\n")); + tr.replaceSelectionWith(this.type.create({ language }, textNode)); + if (tr.selection.$from.parent.type !== this.type) { + tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2)))); + } + tr.setMeta("paste", true); + view.dispatch(tr); + return true; + } + } + }) + ]; + } +}); + +// node_modules/@tiptap/extension-document/dist/index.js +var Document = Node3.create({ + name: "doc", + topNode: true, + content: "block+", + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n\n"); + } +}); + +// node_modules/@tiptap/extension-hard-break/dist/index.js +var HardBreak = Node3.create({ + name: "hardBreak", + markdownTokenName: "br", + addOptions() { + return { + keepMarks: true, + HTMLAttributes: {} + }; + }, + inline: true, + group: "inline", + selectable: false, + linebreakReplacement: true, + parseHTML() { + return [{ tag: "br" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["br", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; + }, + renderText() { + return "\n"; + }, + renderMarkdown: () => ` +`, + parseMarkdown: () => { + return { + type: "hardBreak" + }; + }, + addCommands() { + return { + setHardBreak: () => ({ commands, chain, state, editor }) => { + return commands.first([ + () => commands.exitCode(), + () => commands.command(() => { + const { selection, storedMarks } = state; + if (selection.$from.parent.type.spec.isolating) { + return false; + } + const { keepMarks } = this.options; + const { splittableMarks } = editor.extensionManager; + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + return chain().insertContent({ type: this.name }).command(({ tr, dispatch }) => { + if (dispatch && marks && keepMarks) { + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr.ensureMarks(filteredMarks); + } + return true; + }).run(); + }) + ]); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Enter": () => this.editor.commands.setHardBreak(), + "Shift-Enter": () => this.editor.commands.setHardBreak() + }; + } +}); + +// node_modules/@tiptap/extension-heading/dist/index.js +var Heading = Node3.create({ + name: "heading", + addOptions() { + return { + levels: [1, 2, 3, 4, 5, 6], + HTMLAttributes: {} + }; + }, + content: "inline*", + group: "block", + defining: true, + addAttributes() { + return { + level: { + default: 1, + rendered: false + } + }; + }, + parseHTML() { + return this.options.levels.map((level) => ({ + tag: `h${level}`, + attrs: { level } + })); + }, + renderHTML({ node, HTMLAttributes }) { + const hasLevel = this.options.levels.includes(node.attrs.level); + const level = hasLevel ? node.attrs.level : this.options.levels[0]; + return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + parseMarkdown: (token, helpers) => { + return helpers.createNode("heading", { level: token.depth || 1 }, helpers.parseInline(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + var _a; + const level = ((_a = node.attrs) == null ? void 0 : _a.level) ? parseInt(node.attrs.level, 10) : 1; + const headingChars = "#".repeat(level); + if (!node.content) { + return ""; + } + return `${headingChars} ${h2.renderChildren(node.content)}`; + }, + addCommands() { + return { + setHeading: (attributes) => ({ commands }) => { + if (!this.options.levels.includes(attributes.level)) { + return false; + } + return commands.setNode(this.name, attributes); + }, + toggleHeading: (attributes) => ({ commands }) => { + if (!this.options.levels.includes(attributes.level)) { + return false; + } + return commands.toggleNode(this.name, "paragraph", attributes); + } + }; + }, + addKeyboardShortcuts() { + return this.options.levels.reduce( + (items, level) => ({ + ...items, + ...{ + [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }) + } + }), + {} + ); + }, + addInputRules() { + return this.options.levels.map((level) => { + return textblockTypeInputRule({ + find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\s$`), + type: this.type, + getAttributes: { + level + } + }); + }); + } +}); + +// node_modules/@tiptap/extension-horizontal-rule/dist/index.js +var HorizontalRule = Node3.create({ + name: "horizontalRule", + addOptions() { + return { + HTMLAttributes: {}, + nextNodeType: "paragraph" + }; + }, + group: "block", + parseHTML() { + return [{ tag: "hr" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["hr", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; + }, + markdownTokenName: "hr", + parseMarkdown: (token, helpers) => { + return helpers.createNode("horizontalRule"); + }, + renderMarkdown: () => { + return "---"; + }, + addCommands() { + return { + setHorizontalRule: () => ({ chain, state }) => { + if (!canInsertNode(state, state.schema.nodes[this.name])) { + return false; + } + const { selection } = state; + const { $to: $originTo } = selection; + const currentChain = chain(); + if (isNodeSelection(selection)) { + currentChain.insertContentAt($originTo.pos, { + type: this.name + }); + } else { + currentChain.insertContent({ type: this.name }); + } + return currentChain.command(({ state: chainState, tr, dispatch }) => { + if (dispatch) { + const { $to } = tr.selection; + const posAfter = $to.end(); + if ($to.nodeAfter) { + if ($to.nodeAfter.isTextblock) { + tr.setSelection(TextSelection.create(tr.doc, $to.pos + 1)); + } else if ($to.nodeAfter.isBlock) { + tr.setSelection(NodeSelection.create(tr.doc, $to.pos)); + } else { + tr.setSelection(TextSelection.create(tr.doc, $to.pos)); + } + } else { + const nodeType = chainState.schema.nodes[this.options.nextNodeType] || $to.parent.type.contentMatch.defaultType; + const node = nodeType == null ? void 0 : nodeType.create(); + if (node) { + tr.insert(posAfter, node); + tr.setSelection(TextSelection.create(tr.doc, posAfter + 1)); + } + } + tr.scrollIntoView(); + } + return true; + }).run(); + } + }; + }, + addInputRules() { + return [ + nodeInputRule({ + find: /^(?:---|—-|___\s|\*\*\*\s)$/, + type: this.type + }) + ]; + } +}); + +// node_modules/@tiptap/extension-italic/dist/index.js +var starInputRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/; +var starPasteRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g; +var underscoreInputRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/; +var underscorePasteRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g; +var Italic = Mark.create({ + name: "italic", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "em" + }, + { + tag: "i", + getAttrs: (node) => node.style.fontStyle !== "normal" && null + }, + { + style: "font-style=normal", + clearMark: (mark) => mark.type.name === this.name + }, + { + style: "font-style=italic" + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["em", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + addCommands() { + return { + setItalic: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleItalic: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetItalic: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + markdownTokenName: "em", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("italic", helpers.parseInline(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + return `*${h2.renderChildren(node)}*`; + }, + addKeyboardShortcuts() { + return { + "Mod-i": () => this.editor.commands.toggleItalic(), + "Mod-I": () => this.editor.commands.toggleItalic() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: starInputRegex2, + type: this.type + }), + markInputRule({ + find: underscoreInputRegex2, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: starPasteRegex2, + type: this.type + }), + markPasteRule({ + find: underscorePasteRegex2, + type: this.type + }) + ]; + } +}); + +// node_modules/@tiptap/extension-list/dist/index.js +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var ListItemName = "listItem"; +var TextStyleName = "textStyle"; +var bulletListInputRegex = /^\s*([-+*])\s$/; +var BulletList = Node3.create({ + name: "bulletList", + addOptions() { + return { + itemTypeName: "listItem", + HTMLAttributes: {}, + keepMarks: false, + keepAttributes: false + }; + }, + group: "block list", + content() { + return `${this.options.itemTypeName}+`; + }, + parseHTML() { + return [{ tag: "ul" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "list", + parseMarkdown: (token, helpers) => { + if (token.type !== "list" || token.ordered) { + return []; + } + return { + type: "bulletList", + content: token.items ? helpers.parseChildren(token.items) : [] + }; + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n"); + }, + markdownOptions: { + indentsContent: true + }, + addCommands() { + return { + toggleBulletList: () => ({ commands, chain }) => { + if (this.options.keepAttributes) { + return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run(); + } + return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-8": () => this.editor.commands.toggleBulletList() + }; + }, + addInputRules() { + let inputRule = wrappingInputRule({ + find: bulletListInputRegex, + type: this.type + }); + if (this.options.keepMarks || this.options.keepAttributes) { + inputRule = wrappingInputRule({ + find: bulletListInputRegex, + type: this.type, + keepMarks: this.options.keepMarks, + keepAttributes: this.options.keepAttributes, + getAttributes: () => { + return this.editor.getAttributes(TextStyleName); + }, + editor: this.editor + }); + } + return [inputRule]; + } +}); +var ListItem = Node3.create({ + name: "listItem", + addOptions() { + return { + HTMLAttributes: {}, + bulletListTypeName: "bulletList", + orderedListTypeName: "orderedList" + }; + }, + content: "paragraph block*", + defining: true, + parseHTML() { + return [ + { + tag: "li" + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["li", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "list_item", + parseMarkdown: (token, helpers) => { + if (token.type !== "list_item") { + return []; + } + let content = []; + if (token.tokens && token.tokens.length > 0) { + const hasParagraphTokens = token.tokens.some((t) => t.type === "paragraph"); + if (hasParagraphTokens) { + content = helpers.parseChildren(token.tokens); + } else { + const firstToken = token.tokens[0]; + if (firstToken && firstToken.type === "text" && firstToken.tokens && firstToken.tokens.length > 0) { + const inlineContent = helpers.parseInline(firstToken.tokens); + content = [ + { + type: "paragraph", + content: inlineContent + } + ]; + if (token.tokens.length > 1) { + const remainingTokens = token.tokens.slice(1); + const additionalContent = helpers.parseChildren(remainingTokens); + content.push(...additionalContent); + } + } else { + content = helpers.parseChildren(token.tokens); + } + } + } + if (content.length === 0) { + content = [ + { + type: "paragraph", + content: [] + } + ]; + } + return { + type: "listItem", + content + }; + }, + renderMarkdown: (node, h2, ctx) => { + return renderNestedMarkdownContent( + node, + h2, + (context) => { + var _a, _b; + if (context.parentType === "bulletList") { + return "- "; + } + if (context.parentType === "orderedList") { + const start = ((_b = (_a = context.meta) == null ? void 0 : _a.parentAttrs) == null ? void 0 : _b.start) || 1; + return `${start + context.index}. `; + } + return "- "; + }, + ctx + ); + }, + addKeyboardShortcuts() { + return { + Enter: () => this.editor.commands.splitListItem(this.name), + Tab: () => this.editor.commands.sinkListItem(this.name), + "Shift-Tab": () => this.editor.commands.liftListItem(this.name) + }; + } +}); +var listHelpers_exports = {}; +__export(listHelpers_exports, { + findListItemPos: () => findListItemPos, + getNextListDepth: () => getNextListDepth, + handleBackspace: () => handleBackspace, + handleDelete: () => handleDelete, + hasListBefore: () => hasListBefore, + hasListItemAfter: () => hasListItemAfter, + hasListItemBefore: () => hasListItemBefore, + listItemHasSubList: () => listItemHasSubList, + nextListIsDeeper: () => nextListIsDeeper, + nextListIsHigher: () => nextListIsHigher +}); +var findListItemPos = (typeOrName, state) => { + const { $from } = state.selection; + const nodeType = getNodeType(typeOrName, state.schema); + let currentNode = null; + let currentDepth = $from.depth; + let currentPos = $from.pos; + let targetDepth = null; + while (currentDepth > 0 && targetDepth === null) { + currentNode = $from.node(currentDepth); + if (currentNode.type === nodeType) { + targetDepth = currentDepth; + } else { + currentDepth -= 1; + currentPos -= 1; + } + } + if (targetDepth === null) { + return null; + } + return { $pos: state.doc.resolve(currentPos), depth: targetDepth }; +}; +var getNextListDepth = (typeOrName, state) => { + const listItemPos = findListItemPos(typeOrName, state); + if (!listItemPos) { + return false; + } + const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4); + return depth; +}; +var hasListBefore = (editorState, name, parentListTypes) => { + const { $anchor } = editorState.selection; + const previousNodePos = Math.max(0, $anchor.pos - 2); + const previousNode = editorState.doc.resolve(previousNodePos).node(); + if (!previousNode || !parentListTypes.includes(previousNode.type.name)) { + return false; + } + return true; +}; +var hasListItemBefore = (typeOrName, state) => { + var _a; + const { $anchor } = state.selection; + const $targetPos = state.doc.resolve($anchor.pos - 2); + if ($targetPos.index() === 0) { + return false; + } + if (((_a = $targetPos.nodeBefore) == null ? void 0 : _a.type.name) !== typeOrName) { + return false; + } + return true; +}; +var listItemHasSubList = (typeOrName, state, node) => { + if (!node) { + return false; + } + const nodeType = getNodeType(typeOrName, state.schema); + let hasSubList = false; + node.descendants((child) => { + if (child.type === nodeType) { + hasSubList = true; + } + }); + return hasSubList; +}; +var handleBackspace = (editor, name, parentListTypes) => { + if (editor.commands.undoInputRule()) { + return true; + } + if (editor.state.selection.from !== editor.state.selection.to) { + return false; + } + if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) { + const { $anchor } = editor.state.selection; + const $listPos = editor.state.doc.resolve($anchor.before() - 1); + const listDescendants = []; + $listPos.node().descendants((node, pos) => { + if (node.type.name === name) { + listDescendants.push({ node, pos }); + } + }); + const lastItem = listDescendants.at(-1); + if (!lastItem) { + return false; + } + const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1); + return editor.chain().cut({ from: $anchor.start() - 1, to: $anchor.end() + 1 }, $lastItemPos.end()).joinForward().run(); + } + if (!isNodeActive(editor.state, name)) { + return false; + } + if (!isAtStartOfNode(editor.state)) { + return false; + } + const listItemPos = findListItemPos(name, editor.state); + if (!listItemPos) { + return false; + } + const $prev = editor.state.doc.resolve(listItemPos.$pos.pos - 2); + const prevNode = $prev.node(listItemPos.depth); + const previousListItemHasSubList = listItemHasSubList(name, editor.state, prevNode); + if (hasListItemBefore(name, editor.state) && !previousListItemHasSubList) { + return editor.commands.joinItemBackward(); + } + return editor.chain().liftListItem(name).run(); +}; +var nextListIsDeeper = (typeOrName, state) => { + const listDepth = getNextListDepth(typeOrName, state); + const listItemPos = findListItemPos(typeOrName, state); + if (!listItemPos || !listDepth) { + return false; + } + if (listDepth > listItemPos.depth) { + return true; + } + return false; +}; +var nextListIsHigher = (typeOrName, state) => { + const listDepth = getNextListDepth(typeOrName, state); + const listItemPos = findListItemPos(typeOrName, state); + if (!listItemPos || !listDepth) { + return false; + } + if (listDepth < listItemPos.depth) { + return true; + } + return false; +}; +var handleDelete = (editor, name) => { + if (!isNodeActive(editor.state, name)) { + return false; + } + if (!isAtEndOfNode(editor.state, name)) { + return false; + } + const { selection } = editor.state; + const { $from, $to } = selection; + if (!selection.empty && $from.sameParent($to)) { + return false; + } + if (nextListIsDeeper(name, editor.state)) { + return editor.chain().focus(editor.state.selection.from + 4).lift(name).joinBackward().run(); + } + if (nextListIsHigher(name, editor.state)) { + return editor.chain().joinForward().joinBackward().run(); + } + return editor.commands.joinItemForward(); +}; +var hasListItemAfter = (typeOrName, state) => { + var _a; + const { $anchor } = state.selection; + const $targetPos = state.doc.resolve($anchor.pos - $anchor.parentOffset - 2); + if ($targetPos.index() === $targetPos.parent.childCount - 1) { + return false; + } + if (((_a = $targetPos.nodeAfter) == null ? void 0 : _a.type.name) !== typeOrName) { + return false; + } + return true; +}; +var ListKeymap = Extension.create({ + name: "listKeymap", + addOptions() { + return { + listTypes: [ + { + itemName: "listItem", + wrapperNames: ["bulletList", "orderedList"] + }, + { + itemName: "taskItem", + wrapperNames: ["taskList"] + } + ] + }; + }, + addKeyboardShortcuts() { + return { + Delete: ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleDelete(editor, itemName)) { + handled = true; + } + }); + return handled; + }, + "Mod-Delete": ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleDelete(editor, itemName)) { + handled = true; + } + }); + return handled; + }, + Backspace: ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName, wrapperNames }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleBackspace(editor, itemName, wrapperNames)) { + handled = true; + } + }); + return handled; + }, + "Mod-Backspace": ({ editor }) => { + let handled = false; + this.options.listTypes.forEach(({ itemName, wrapperNames }) => { + if (editor.state.schema.nodes[itemName] === void 0) { + return; + } + if (handleBackspace(editor, itemName, wrapperNames)) { + handled = true; + } + }); + return handled; + } + }; + } +}); +var ORDERED_LIST_ITEM_REGEX = /^(\s*)(\d+)\.\s+(.*)$/; +var INDENTED_LINE_REGEX = /^\s/; +function collectOrderedListItems(lines) { + const listItems = []; + let currentLineIndex = 0; + let consumed = 0; + while (currentLineIndex < lines.length) { + const line = lines[currentLineIndex]; + const match = line.match(ORDERED_LIST_ITEM_REGEX); + if (!match) { + break; + } + const [, indent, number, content] = match; + const indentLevel = indent.length; + let itemContent = content; + let nextLineIndex = currentLineIndex + 1; + const itemLines = [line]; + while (nextLineIndex < lines.length) { + const nextLine = lines[nextLineIndex]; + const nextMatch = nextLine.match(ORDERED_LIST_ITEM_REGEX); + if (nextMatch) { + break; + } + if (nextLine.trim() === "") { + itemLines.push(nextLine); + itemContent += "\n"; + nextLineIndex += 1; + } else if (nextLine.match(INDENTED_LINE_REGEX)) { + itemLines.push(nextLine); + itemContent += ` +${nextLine.slice(indentLevel + 2)}`; + nextLineIndex += 1; + } else { + break; + } + } + listItems.push({ + indent: indentLevel, + number: parseInt(number, 10), + content: itemContent.trim(), + raw: itemLines.join("\n") + }); + consumed = nextLineIndex; + currentLineIndex = nextLineIndex; + } + return [listItems, consumed]; +} +function buildNestedStructure(items, baseIndent, lexer) { + var _a; + const result = []; + let currentIndex = 0; + while (currentIndex < items.length) { + const item = items[currentIndex]; + if (item.indent === baseIndent) { + const contentLines = item.content.split("\n"); + const mainText = ((_a = contentLines[0]) == null ? void 0 : _a.trim()) || ""; + const tokens = []; + if (mainText) { + tokens.push({ + type: "paragraph", + raw: mainText, + tokens: lexer.inlineTokens(mainText) + }); + } + const additionalContent = contentLines.slice(1).join("\n").trim(); + if (additionalContent) { + const blockTokens = lexer.blockTokens(additionalContent); + tokens.push(...blockTokens); + } + let lookAheadIndex = currentIndex + 1; + const nestedItems = []; + while (lookAheadIndex < items.length && items[lookAheadIndex].indent > baseIndent) { + nestedItems.push(items[lookAheadIndex]); + lookAheadIndex += 1; + } + if (nestedItems.length > 0) { + const nextIndent = Math.min(...nestedItems.map((nestedItem) => nestedItem.indent)); + const nestedListItems = buildNestedStructure(nestedItems, nextIndent, lexer); + tokens.push({ + type: "list", + ordered: true, + start: nestedItems[0].number, + items: nestedListItems, + raw: nestedItems.map((nestedItem) => nestedItem.raw).join("\n") + }); + } + result.push({ + type: "list_item", + raw: item.raw, + tokens + }); + currentIndex = lookAheadIndex; + } else { + currentIndex += 1; + } + } + return result; +} +function parseListItems(items, helpers) { + return items.map((item) => { + if (item.type !== "list_item") { + return helpers.parseChildren([item])[0]; + } + const content = []; + if (item.tokens && item.tokens.length > 0) { + item.tokens.forEach((itemToken) => { + if (itemToken.type === "paragraph" || itemToken.type === "list" || itemToken.type === "blockquote" || itemToken.type === "code") { + content.push(...helpers.parseChildren([itemToken])); + } else if (itemToken.type === "text" && itemToken.tokens) { + const inlineContent = helpers.parseChildren([itemToken]); + content.push({ + type: "paragraph", + content: inlineContent + }); + } else { + const parsed = helpers.parseChildren([itemToken]); + if (parsed.length > 0) { + content.push(...parsed); + } + } + }); + } + return { + type: "listItem", + content + }; + }); +} +var ListItemName2 = "listItem"; +var TextStyleName2 = "textStyle"; +var orderedListInputRegex = /^(\d+)\.\s$/; +var OrderedList = Node3.create({ + name: "orderedList", + addOptions() { + return { + itemTypeName: "listItem", + HTMLAttributes: {}, + keepMarks: false, + keepAttributes: false + }; + }, + group: "block list", + content() { + return `${this.options.itemTypeName}+`; + }, + addAttributes() { + return { + start: { + default: 1, + parseHTML: (element) => { + return element.hasAttribute("start") ? parseInt(element.getAttribute("start") || "", 10) : 1; + } + }, + type: { + default: null, + parseHTML: (element) => element.getAttribute("type") + } + }; + }, + parseHTML() { + return [ + { + tag: "ol" + } + ]; + }, + renderHTML({ HTMLAttributes }) { + const { start, ...attributesWithoutStart } = HTMLAttributes; + return start === 1 ? ["ol", mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0] : ["ol", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "list", + parseMarkdown: (token, helpers) => { + if (token.type !== "list" || !token.ordered) { + return []; + } + const startValue = token.start || 1; + const content = token.items ? parseListItems(token.items, helpers) : []; + if (startValue !== 1) { + return { + type: "orderedList", + attrs: { start: startValue }, + content + }; + } + return { + type: "orderedList", + content + }; + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n"); + }, + markdownTokenizer: { + name: "orderedList", + level: "block", + start: (src) => { + const match = src.match(/^(\s*)(\d+)\.\s+/); + const index = match == null ? void 0 : match.index; + return index !== void 0 ? index : -1; + }, + tokenize: (src, _tokens, lexer) => { + var _a; + const lines = src.split("\n"); + const [listItems, consumed] = collectOrderedListItems(lines); + if (listItems.length === 0) { + return void 0; + } + const items = buildNestedStructure(listItems, 0, lexer); + if (items.length === 0) { + return void 0; + } + const startValue = ((_a = listItems[0]) == null ? void 0 : _a.number) || 1; + return { + type: "list", + ordered: true, + start: startValue, + items, + raw: lines.slice(0, consumed).join("\n") + }; + } + }, + markdownOptions: { + indentsContent: true + }, + addCommands() { + return { + toggleOrderedList: () => ({ commands, chain }) => { + if (this.options.keepAttributes) { + return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName2, this.editor.getAttributes(TextStyleName2)).run(); + } + return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-7": () => this.editor.commands.toggleOrderedList() + }; + }, + addInputRules() { + let inputRule = wrappingInputRule({ + find: orderedListInputRegex, + type: this.type, + getAttributes: (match) => ({ start: +match[1] }), + joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1] + }); + if (this.options.keepMarks || this.options.keepAttributes) { + inputRule = wrappingInputRule({ + find: orderedListInputRegex, + type: this.type, + keepMarks: this.options.keepMarks, + keepAttributes: this.options.keepAttributes, + getAttributes: (match) => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName2) }), + joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1], + editor: this.editor + }); + } + return [inputRule]; + } +}); +var inputRegex3 = /^\s*(\[([( |x])?\])\s$/; +var TaskItem = Node3.create({ + name: "taskItem", + addOptions() { + return { + nested: false, + HTMLAttributes: {}, + taskListTypeName: "taskList", + a11y: void 0 + }; + }, + content() { + return this.options.nested ? "paragraph block*" : "paragraph+"; + }, + defining: true, + addAttributes() { + return { + checked: { + default: false, + keepOnSplit: false, + parseHTML: (element) => { + const dataChecked = element.getAttribute("data-checked"); + return dataChecked === "" || dataChecked === "true"; + }, + renderHTML: (attributes) => ({ + "data-checked": attributes.checked + }) + } + }; + }, + parseHTML() { + return [ + { + tag: `li[data-type="${this.name}"]`, + priority: 51 + } + ]; + }, + renderHTML({ node, HTMLAttributes }) { + return [ + "li", + mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { + "data-type": this.name + }), + [ + "label", + [ + "input", + { + type: "checkbox", + checked: node.attrs.checked ? "checked" : null + } + ], + ["span"] + ], + ["div", 0] + ]; + }, + parseMarkdown: (token, h2) => { + const content = []; + if (token.tokens && token.tokens.length > 0) { + content.push(h2.createNode("paragraph", {}, h2.parseInline(token.tokens))); + } else if (token.text) { + content.push(h2.createNode("paragraph", {}, [h2.createNode("text", { text: token.text })])); + } else { + content.push(h2.createNode("paragraph", {}, [])); + } + if (token.nestedTokens && token.nestedTokens.length > 0) { + const nestedContent = h2.parseChildren(token.nestedTokens); + content.push(...nestedContent); + } + return h2.createNode("taskItem", { checked: token.checked || false }, content); + }, + renderMarkdown: (node, h2) => { + var _a; + const checkedChar = ((_a = node.attrs) == null ? void 0 : _a.checked) ? "x" : " "; + const prefix = `- [${checkedChar}] `; + return renderNestedMarkdownContent(node, h2, prefix); + }, + addKeyboardShortcuts() { + const shortcuts = { + Enter: () => this.editor.commands.splitListItem(this.name), + "Shift-Tab": () => this.editor.commands.liftListItem(this.name) + }; + if (!this.options.nested) { + return shortcuts; + } + return { + ...shortcuts, + Tab: () => this.editor.commands.sinkListItem(this.name) + }; + }, + addNodeView() { + return ({ node, HTMLAttributes, getPos, editor }) => { + const listItem = document.createElement("li"); + const checkboxWrapper = document.createElement("label"); + const checkboxStyler = document.createElement("span"); + const checkbox = document.createElement("input"); + const content = document.createElement("div"); + const updateA11Y = (currentNode) => { + var _a, _b; + checkbox.ariaLabel = ((_b = (_a = this.options.a11y) == null ? void 0 : _a.checkboxLabel) == null ? void 0 : _b.call(_a, currentNode, checkbox.checked)) || `Task item checkbox for ${currentNode.textContent || "empty task item"}`; + }; + updateA11Y(node); + checkboxWrapper.contentEditable = "false"; + checkbox.type = "checkbox"; + checkbox.addEventListener("mousedown", (event) => event.preventDefault()); + checkbox.addEventListener("change", (event) => { + if (!editor.isEditable && !this.options.onReadOnlyChecked) { + checkbox.checked = !checkbox.checked; + return; + } + const { checked } = event.target; + if (editor.isEditable && typeof getPos === "function") { + editor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr }) => { + const position = getPos(); + if (typeof position !== "number") { + return false; + } + const currentNode = tr.doc.nodeAt(position); + tr.setNodeMarkup(position, void 0, { + ...currentNode == null ? void 0 : currentNode.attrs, + checked + }); + return true; + }).run(); + } + if (!editor.isEditable && this.options.onReadOnlyChecked) { + if (!this.options.onReadOnlyChecked(node, checked)) { + checkbox.checked = !checkbox.checked; + } + } + }); + Object.entries(this.options.HTMLAttributes).forEach(([key, value]) => { + listItem.setAttribute(key, value); + }); + listItem.dataset.checked = node.attrs.checked; + checkbox.checked = node.attrs.checked; + checkboxWrapper.append(checkbox, checkboxStyler); + listItem.append(checkboxWrapper, content); + Object.entries(HTMLAttributes).forEach(([key, value]) => { + listItem.setAttribute(key, value); + }); + let prevRenderedAttributeKeys = new Set(Object.keys(HTMLAttributes)); + return { + dom: listItem, + contentDOM: content, + update: (updatedNode) => { + if (updatedNode.type !== this.type) { + return false; + } + listItem.dataset.checked = updatedNode.attrs.checked; + checkbox.checked = updatedNode.attrs.checked; + updateA11Y(updatedNode); + const extensionAttributes = editor.extensionManager.attributes; + const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes); + const newKeys = new Set(Object.keys(newHTMLAttributes)); + const staticAttrs = this.options.HTMLAttributes; + prevRenderedAttributeKeys.forEach((key) => { + if (!newKeys.has(key)) { + if (key in staticAttrs) { + listItem.setAttribute(key, staticAttrs[key]); + } else { + listItem.removeAttribute(key); + } + } + }); + Object.entries(newHTMLAttributes).forEach(([key, value]) => { + if (value === null || value === void 0) { + if (key in staticAttrs) { + listItem.setAttribute(key, staticAttrs[key]); + } else { + listItem.removeAttribute(key); + } + } else { + listItem.setAttribute(key, value); + } + }); + prevRenderedAttributeKeys = newKeys; + return true; + } + }; + }; + }, + addInputRules() { + return [ + wrappingInputRule({ + find: inputRegex3, + type: this.type, + getAttributes: (match) => ({ + checked: match[match.length - 1] === "x" + }) + }) + ]; + } +}); +var TaskList = Node3.create({ + name: "taskList", + addOptions() { + return { + itemTypeName: "taskItem", + HTMLAttributes: {} + }; + }, + group: "block list", + content() { + return `${this.options.itemTypeName}+`; + }, + parseHTML() { + return [ + { + tag: `ul[data-type="${this.name}"]`, + priority: 51 + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { "data-type": this.name }), 0]; + }, + parseMarkdown: (token, h2) => { + return h2.createNode("taskList", {}, h2.parseChildren(token.items || [])); + }, + renderMarkdown: (node, h2) => { + if (!node.content) { + return ""; + } + return h2.renderChildren(node.content, "\n"); + }, + markdownTokenizer: { + name: "taskList", + level: "block", + start(src) { + var _a; + const index = (_a = src.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)) == null ? void 0 : _a.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, tokens, lexer) { + const parseTaskListContent = (content) => { + const nestedResult = parseIndentedBlocks( + content, + { + itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, + extractItemData: (match) => ({ + indentLevel: match[1].length, + mainContent: match[4], + checked: match[3].toLowerCase() === "x" + }), + createToken: (data, nestedTokens) => ({ + type: "taskItem", + raw: "", + mainContent: data.mainContent, + indentLevel: data.indentLevel, + checked: data.checked, + text: data.mainContent, + tokens: lexer.inlineTokens(data.mainContent), + nestedTokens + }), + // Allow recursive nesting + customNestedParser: parseTaskListContent + }, + lexer + ); + if (nestedResult) { + return [ + { + type: "taskList", + raw: nestedResult.raw, + items: nestedResult.items + } + ]; + } + return lexer.blockTokens(content); + }; + const result = parseIndentedBlocks( + src, + { + itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, + extractItemData: (match) => ({ + indentLevel: match[1].length, + mainContent: match[4], + checked: match[3].toLowerCase() === "x" + }), + createToken: (data, nestedTokens) => ({ + type: "taskItem", + raw: "", + mainContent: data.mainContent, + indentLevel: data.indentLevel, + checked: data.checked, + text: data.mainContent, + tokens: lexer.inlineTokens(data.mainContent), + nestedTokens + }), + // Use the recursive parser for nested content + customNestedParser: parseTaskListContent + }, + lexer + ); + if (!result) { + return void 0; + } + return { + type: "taskList", + raw: result.raw, + items: result.items + }; + } + }, + markdownOptions: { + indentsContent: true + }, + addCommands() { + return { + toggleTaskList: () => ({ commands }) => { + return commands.toggleList(this.name, this.options.itemTypeName); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-9": () => this.editor.commands.toggleTaskList() + }; + } +}); +var ListKit = Extension.create({ + name: "listKit", + addExtensions() { + const extensions = []; + if (this.options.bulletList !== false) { + extensions.push(BulletList.configure(this.options.bulletList)); + } + if (this.options.listItem !== false) { + extensions.push(ListItem.configure(this.options.listItem)); + } + if (this.options.listKeymap !== false) { + extensions.push(ListKeymap.configure(this.options.listKeymap)); + } + if (this.options.orderedList !== false) { + extensions.push(OrderedList.configure(this.options.orderedList)); + } + if (this.options.taskItem !== false) { + extensions.push(TaskItem.configure(this.options.taskItem)); + } + if (this.options.taskList !== false) { + extensions.push(TaskList.configure(this.options.taskList)); + } + return extensions; + } +}); + +// node_modules/@tiptap/extension-paragraph/dist/index.js +var EMPTY_PARAGRAPH_MARKDOWN = " "; +var NBSP_CHAR = " "; +var Paragraph = Node3.create({ + name: "paragraph", + priority: 1e3, + addOptions() { + return { + HTMLAttributes: {} + }; + }, + group: "block", + content: "inline*", + parseHTML() { + return [{ tag: "p" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["p", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + parseMarkdown: (token, helpers) => { + const tokens = token.tokens || []; + if (tokens.length === 1 && tokens[0].type === "image") { + return helpers.parseChildren([tokens[0]]); + } + const content = helpers.parseInline(tokens); + if (content.length === 1 && content[0].type === "text" && (content[0].text === EMPTY_PARAGRAPH_MARKDOWN || content[0].text === NBSP_CHAR)) { + return helpers.createNode("paragraph", void 0, []); + } + return helpers.createNode("paragraph", void 0, content); + }, + renderMarkdown: (node, h2) => { + if (!node) { + return ""; + } + const content = Array.isArray(node.content) ? node.content : []; + if (content.length === 0) { + return EMPTY_PARAGRAPH_MARKDOWN; + } + return h2.renderChildren(content); + }, + addCommands() { + return { + setParagraph: () => ({ commands }) => { + return commands.setNode(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Alt-0": () => this.editor.commands.setParagraph() + }; + } +}); + +// node_modules/@tiptap/extension-strike/dist/index.js +var inputRegex4 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/; +var pasteRegex2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g; +var Strike = Mark.create({ + name: "strike", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "s" + }, + { + tag: "del" + }, + { + tag: "strike" + }, + { + style: "text-decoration", + consuming: false, + getAttrs: (style) => style.includes("line-through") ? {} : false + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["s", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "del", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("strike", helpers.parseInline(token.tokens || [])); + }, + renderMarkdown: (node, h2) => { + return `~~${h2.renderChildren(node)}~~`; + }, + addCommands() { + return { + setStrike: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleStrike: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetStrike: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-Shift-s": () => this.editor.commands.toggleStrike() + }; + }, + addInputRules() { + return [ + markInputRule({ + find: inputRegex4, + type: this.type + }) + ]; + }, + addPasteRules() { + return [ + markPasteRule({ + find: pasteRegex2, + type: this.type + }) + ]; + } +}); + +// node_modules/@tiptap/extension-text/dist/index.js +var Text = Node3.create({ + name: "text", + group: "inline", + parseMarkdown: (token) => { + return { + type: "text", + text: token.text || "" + }; + }, + renderMarkdown: (node) => node.text || "" +}); + +// node_modules/@tiptap/extension-underline/dist/index.js +var Underline = Mark.create({ + name: "underline", + addOptions() { + return { + HTMLAttributes: {} + }; + }, + parseHTML() { + return [ + { + tag: "u" + }, + { + style: "text-decoration", + consuming: false, + getAttrs: (style) => style.includes("underline") ? {} : false + } + ]; + }, + renderHTML({ HTMLAttributes }) { + return ["u", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + parseMarkdown(token, helpers) { + return helpers.applyMark(this.name || "underline", helpers.parseInline(token.tokens || [])); + }, + renderMarkdown(node, helpers) { + return `++${helpers.renderChildren(node)}++`; + }, + markdownTokenizer: { + name: "underline", + level: "inline", + start(src) { + return src.indexOf("++"); + }, + tokenize(src, _tokens, lexer) { + const rule = /^(\+\+)([\s\S]+?)(\+\+)/; + const match = rule.exec(src); + if (!match) { + return void 0; + } + const innerContent = match[2].trim(); + return { + type: "underline", + raw: match[0], + text: innerContent, + tokens: lexer.inlineTokens(innerContent) + }; + } + }, + addCommands() { + return { + setUnderline: () => ({ commands }) => { + return commands.setMark(this.name); + }, + toggleUnderline: () => ({ commands }) => { + return commands.toggleMark(this.name); + }, + unsetUnderline: () => ({ commands }) => { + return commands.unsetMark(this.name); + } + }; + }, + addKeyboardShortcuts() { + return { + "Mod-u": () => this.editor.commands.toggleUnderline(), + "Mod-U": () => this.editor.commands.toggleUnderline() + }; + } +}); + +// node_modules/prosemirror-dropcursor/dist/index.js +function dropCursor(options = {}) { + return new Plugin({ + view(editorView) { + return new DropCursorView(editorView, options); + } + }); +} +var DropCursorView = class { + constructor(editorView, options) { + var _a; + this.editorView = editorView; + this.cursorPos = null; + this.element = null; + this.timeout = -1; + this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1; + this.color = options.color === false ? void 0 : options.color || "black"; + this.class = options.class; + this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name) => { + let handler = (e) => { + this[name](e); + }; + editorView.dom.addEventListener(name, handler); + return { name, handler }; + }); + } + destroy() { + this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler)); + } + update(editorView, prevState) { + if (this.cursorPos != null && prevState.doc != editorView.state.doc) { + if (this.cursorPos > editorView.state.doc.content.size) + this.setCursor(null); + else + this.updateOverlay(); + } + } + setCursor(pos) { + if (pos == this.cursorPos) + return; + this.cursorPos = pos; + if (pos == null) { + this.element.parentNode.removeChild(this.element); + this.element = null; + } else { + this.updateOverlay(); + } + } + updateOverlay() { + let $pos = this.editorView.state.doc.resolve(this.cursorPos); + let isBlock = !$pos.parent.inlineContent, rect; + let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect(); + let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight; + if (isBlock) { + let before = $pos.nodeBefore, after = $pos.nodeAfter; + if (before || after) { + let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0)); + if (node) { + let nodeRect = node.getBoundingClientRect(); + let top = before ? nodeRect.bottom : nodeRect.top; + if (before && after) + top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2; + let halfWidth = this.width / 2 * scaleY; + rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth }; + } + } + } + if (!rect) { + let coords = this.editorView.coordsAtPos(this.cursorPos); + let halfWidth = this.width / 2 * scaleX; + rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom }; + } + let parent = this.editorView.dom.offsetParent; + if (!this.element) { + this.element = parent.appendChild(document.createElement("div")); + if (this.class) + this.element.className = this.class; + this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;"; + if (this.color) { + this.element.style.backgroundColor = this.color; + } + } + this.element.classList.toggle("prosemirror-dropcursor-block", isBlock); + this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock); + let parentLeft, parentTop; + if (!parent || parent == document.body && getComputedStyle(parent).position == "static") { + parentLeft = -pageXOffset; + parentTop = -pageYOffset; + } else { + let rect2 = parent.getBoundingClientRect(); + let parentScaleX = rect2.width / parent.offsetWidth, parentScaleY = rect2.height / parent.offsetHeight; + parentLeft = rect2.left - parent.scrollLeft * parentScaleX; + parentTop = rect2.top - parent.scrollTop * parentScaleY; + } + this.element.style.left = (rect.left - parentLeft) / scaleX + "px"; + this.element.style.top = (rect.top - parentTop) / scaleY + "px"; + this.element.style.width = (rect.right - rect.left) / scaleX + "px"; + this.element.style.height = (rect.bottom - rect.top) / scaleY + "px"; + } + scheduleRemoval(timeout) { + clearTimeout(this.timeout); + this.timeout = setTimeout(() => this.setCursor(null), timeout); + } + dragover(event) { + if (!this.editorView.editable) + return; + let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY }); + let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside); + let disableDropCursor = node && node.type.spec.disableDropCursor; + let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor; + if (pos && !disabled) { + let target = pos.pos; + if (this.editorView.dragging && this.editorView.dragging.slice) { + let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice); + if (point != null) + target = point; + } + this.setCursor(target); + this.scheduleRemoval(5e3); + } + } + dragend() { + this.scheduleRemoval(20); + } + drop() { + this.scheduleRemoval(20); + } + dragleave(event) { + if (!this.editorView.dom.contains(event.relatedTarget)) + this.setCursor(null); + } +}; + +// node_modules/prosemirror-gapcursor/dist/index.js +var GapCursor = class _GapCursor extends Selection { + /** + Create a gap cursor. + */ + constructor($pos) { + super($pos, $pos); + } + map(doc, mapping) { + let $pos = doc.resolve(mapping.map(this.head)); + return _GapCursor.valid($pos) ? new _GapCursor($pos) : Selection.near($pos); + } + content() { + return Slice.empty; + } + eq(other) { + return other instanceof _GapCursor && other.head == this.head; + } + toJSON() { + return { type: "gapcursor", pos: this.head }; + } + /** + @internal + */ + static fromJSON(doc, json) { + if (typeof json.pos != "number") + throw new RangeError("Invalid input for GapCursor.fromJSON"); + return new _GapCursor(doc.resolve(json.pos)); + } + /** + @internal + */ + getBookmark() { + return new GapBookmark(this.anchor); + } + /** + @internal + */ + static valid($pos) { + let parent = $pos.parent; + if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos)) + return false; + let override = parent.type.spec.allowGapCursor; + if (override != null) + return override; + let deflt = parent.contentMatchAt($pos.index()).defaultType; + return deflt && deflt.isTextblock; + } + /** + @internal + */ + static findGapCursorFrom($pos, dir, mustMove = false) { + search: for (; ; ) { + if (!mustMove && _GapCursor.valid($pos)) + return $pos; + let pos = $pos.pos, next = null; + for (let d = $pos.depth; ; d--) { + let parent = $pos.node(d); + if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) { + next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1); + break; + } else if (d == 0) { + return null; + } + pos += dir; + let $cur = $pos.doc.resolve(pos); + if (_GapCursor.valid($cur)) + return $cur; + } + for (; ; ) { + let inside = dir > 0 ? next.firstChild : next.lastChild; + if (!inside) { + if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) { + $pos = $pos.doc.resolve(pos + next.nodeSize * dir); + mustMove = false; + continue search; + } + break; + } + next = inside; + pos += dir; + let $cur = $pos.doc.resolve(pos); + if (_GapCursor.valid($cur)) + return $cur; + } + return null; + } + } +}; +GapCursor.prototype.visible = false; +GapCursor.findFrom = GapCursor.findGapCursorFrom; +Selection.jsonID("gapcursor", GapCursor); +var GapBookmark = class _GapBookmark { + constructor(pos) { + this.pos = pos; + } + map(mapping) { + return new _GapBookmark(mapping.map(this.pos)); + } + resolve(doc) { + let $pos = doc.resolve(this.pos); + return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos); + } +}; +function needsGap(type) { + return type.isAtom || type.spec.isolating || type.spec.createGapCursor; +} +function closedBefore($pos) { + for (let d = $pos.depth; d >= 0; d--) { + let index = $pos.index(d), parent = $pos.node(d); + if (index == 0) { + if (parent.type.spec.isolating) + return true; + continue; + } + for (let before = parent.child(index - 1); ; before = before.lastChild) { + if (before.childCount == 0 && !before.inlineContent || needsGap(before.type)) + return true; + if (before.inlineContent) + return false; + } + } + return true; +} +function closedAfter($pos) { + for (let d = $pos.depth; d >= 0; d--) { + let index = $pos.indexAfter(d), parent = $pos.node(d); + if (index == parent.childCount) { + if (parent.type.spec.isolating) + return true; + continue; + } + for (let after = parent.child(index); ; after = after.firstChild) { + if (after.childCount == 0 && !after.inlineContent || needsGap(after.type)) + return true; + if (after.inlineContent) + return false; + } + } + return true; +} +function gapCursor() { + return new Plugin({ + props: { + decorations: drawGapCursor, + createSelectionBetween(_view, $anchor, $head) { + return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null; + }, + handleClick, + handleKeyDown, + handleDOMEvents: { beforeinput } + } + }); +} +var handleKeyDown = keydownHandler({ + "ArrowLeft": arrow("horiz", -1), + "ArrowRight": arrow("horiz", 1), + "ArrowUp": arrow("vert", -1), + "ArrowDown": arrow("vert", 1) +}); +function arrow(axis, dir) { + const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left"; + return function(state, dispatch, view) { + let sel = state.selection; + let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty; + if (sel instanceof TextSelection) { + if (!view.endOfTextblock(dirStr) || $start.depth == 0) + return false; + mustMove = false; + $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before()); + } + let $found = GapCursor.findGapCursorFrom($start, dir, mustMove); + if (!$found) + return false; + if (dispatch) + dispatch(state.tr.setSelection(new GapCursor($found))); + return true; + }; +} +function handleClick(view, pos, event) { + if (!view || !view.editable) + return false; + let $pos = view.state.doc.resolve(pos); + if (!GapCursor.valid($pos)) + return false; + let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY }); + if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside))) + return false; + view.dispatch(view.state.tr.setSelection(new GapCursor($pos))); + return true; +} +function beforeinput(view, event) { + if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor)) + return false; + let { $from } = view.state.selection; + let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text); + if (!insert) + return false; + let frag = Fragment.empty; + for (let i = insert.length - 1; i >= 0; i--) + frag = Fragment.from(insert[i].createAndFill(null, frag)); + let tr = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0)); + tr.setSelection(TextSelection.near(tr.doc.resolve($from.pos + 1))); + view.dispatch(tr); + return false; +} +function drawGapCursor(state) { + if (!(state.selection instanceof GapCursor)) + return null; + let node = document.createElement("div"); + node.className = "ProseMirror-gapcursor"; + return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: "gapcursor" })]); +} + +// node_modules/rope-sequence/dist/index.js +var GOOD_LEAF_SIZE = 200; +var RopeSequence = function RopeSequence2() { +}; +RopeSequence.prototype.append = function append(other) { + if (!other.length) { + return this; + } + other = RopeSequence.from(other); + return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other); +}; +RopeSequence.prototype.prepend = function prepend(other) { + if (!other.length) { + return this; + } + return RopeSequence.from(other).append(this); +}; +RopeSequence.prototype.appendInner = function appendInner(other) { + return new Append(this, other); +}; +RopeSequence.prototype.slice = function slice(from2, to) { + if (from2 === void 0) from2 = 0; + if (to === void 0) to = this.length; + if (from2 >= to) { + return RopeSequence.empty; + } + return this.sliceInner(Math.max(0, from2), Math.min(this.length, to)); +}; +RopeSequence.prototype.get = function get(i) { + if (i < 0 || i >= this.length) { + return void 0; + } + return this.getInner(i); +}; +RopeSequence.prototype.forEach = function forEach(f, from2, to) { + if (from2 === void 0) from2 = 0; + if (to === void 0) to = this.length; + if (from2 <= to) { + this.forEachInner(f, from2, to, 0); + } else { + this.forEachInvertedInner(f, from2, to, 0); + } +}; +RopeSequence.prototype.map = function map(f, from2, to) { + if (from2 === void 0) from2 = 0; + if (to === void 0) to = this.length; + var result = []; + this.forEach(function(elt, i) { + return result.push(f(elt, i)); + }, from2, to); + return result; +}; +RopeSequence.from = function from(values) { + if (values instanceof RopeSequence) { + return values; + } + return values && values.length ? new Leaf(values) : RopeSequence.empty; +}; +var Leaf = function(RopeSequence3) { + function Leaf2(values) { + RopeSequence3.call(this); + this.values = values; + } + if (RopeSequence3) Leaf2.__proto__ = RopeSequence3; + Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); + Leaf2.prototype.constructor = Leaf2; + var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } }; + Leaf2.prototype.flatten = function flatten() { + return this.values; + }; + Leaf2.prototype.sliceInner = function sliceInner(from2, to) { + if (from2 == 0 && to == this.length) { + return this; + } + return new Leaf2(this.values.slice(from2, to)); + }; + Leaf2.prototype.getInner = function getInner(i) { + return this.values[i]; + }; + Leaf2.prototype.forEachInner = function forEachInner(f, from2, to, start) { + for (var i = from2; i < to; i++) { + if (f(this.values[i], start + i) === false) { + return false; + } + } + }; + Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) { + for (var i = from2 - 1; i >= to; i--) { + if (f(this.values[i], start + i) === false) { + return false; + } + } + }; + Leaf2.prototype.leafAppend = function leafAppend(other) { + if (this.length + other.length <= GOOD_LEAF_SIZE) { + return new Leaf2(this.values.concat(other.flatten())); + } + }; + Leaf2.prototype.leafPrepend = function leafPrepend(other) { + if (this.length + other.length <= GOOD_LEAF_SIZE) { + return new Leaf2(other.flatten().concat(this.values)); + } + }; + prototypeAccessors.length.get = function() { + return this.values.length; + }; + prototypeAccessors.depth.get = function() { + return 0; + }; + Object.defineProperties(Leaf2.prototype, prototypeAccessors); + return Leaf2; +}(RopeSequence); +RopeSequence.empty = new Leaf([]); +var Append = function(RopeSequence3) { + function Append2(left, right) { + RopeSequence3.call(this); + this.left = left; + this.right = right; + this.length = left.length + right.length; + this.depth = Math.max(left.depth, right.depth) + 1; + } + if (RopeSequence3) Append2.__proto__ = RopeSequence3; + Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); + Append2.prototype.constructor = Append2; + Append2.prototype.flatten = function flatten() { + return this.left.flatten().concat(this.right.flatten()); + }; + Append2.prototype.getInner = function getInner(i) { + return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length); + }; + Append2.prototype.forEachInner = function forEachInner(f, from2, to, start) { + var leftLen = this.left.length; + if (from2 < leftLen && this.left.forEachInner(f, from2, Math.min(to, leftLen), start) === false) { + return false; + } + if (to > leftLen && this.right.forEachInner(f, Math.max(from2 - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) { + return false; + } + }; + Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) { + var leftLen = this.left.length; + if (from2 > leftLen && this.right.forEachInvertedInner(f, from2 - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) { + return false; + } + if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from2, leftLen), to, start) === false) { + return false; + } + }; + Append2.prototype.sliceInner = function sliceInner(from2, to) { + if (from2 == 0 && to == this.length) { + return this; + } + var leftLen = this.left.length; + if (to <= leftLen) { + return this.left.slice(from2, to); + } + if (from2 >= leftLen) { + return this.right.slice(from2 - leftLen, to - leftLen); + } + return this.left.slice(from2, leftLen).append(this.right.slice(0, to - leftLen)); + }; + Append2.prototype.leafAppend = function leafAppend(other) { + var inner = this.right.leafAppend(other); + if (inner) { + return new Append2(this.left, inner); + } + }; + Append2.prototype.leafPrepend = function leafPrepend(other) { + var inner = this.left.leafPrepend(other); + if (inner) { + return new Append2(inner, this.right); + } + }; + Append2.prototype.appendInner = function appendInner2(other) { + if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) { + return new Append2(this.left, new Append2(this.right, other)); + } + return new Append2(this, other); + }; + return Append2; +}(RopeSequence); +var dist_default = RopeSequence; + +// node_modules/prosemirror-history/dist/index.js +var max_empty_items = 500; +var Branch = class _Branch { + constructor(items, eventCount) { + this.items = items; + this.eventCount = eventCount; + } + // Pop the latest event off the branch's history and apply it + // to a document transform. + popEvent(state, preserveItems) { + if (this.eventCount == 0) + return null; + let end = this.items.length; + for (; ; end--) { + let next = this.items.get(end - 1); + if (next.selection) { + --end; + break; + } + } + let remap, mapFrom; + if (preserveItems) { + remap = this.remapping(end, this.items.length); + mapFrom = remap.maps.length; + } + let transform = state.tr; + let selection, remaining; + let addAfter = [], addBefore = []; + this.items.forEach((item, i) => { + if (!item.step) { + if (!remap) { + remap = this.remapping(end, i + 1); + mapFrom = remap.maps.length; + } + mapFrom--; + addBefore.push(item); + return; + } + if (remap) { + addBefore.push(new Item(item.map)); + let step = item.step.map(remap.slice(mapFrom)), map2; + if (step && transform.maybeStep(step).doc) { + map2 = transform.mapping.maps[transform.mapping.maps.length - 1]; + addAfter.push(new Item(map2, void 0, void 0, addAfter.length + addBefore.length)); + } + mapFrom--; + if (map2) + remap.appendMap(map2, mapFrom); + } else { + transform.maybeStep(item.step); + } + if (item.selection) { + selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection; + remaining = new _Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1); + return false; + } + }, this.items.length, 0); + return { remaining, transform, selection }; + } + // Create a new branch with the given transform added. + addTransform(transform, selection, histOptions, preserveItems) { + let newItems = [], eventCount = this.eventCount; + let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null; + for (let i = 0; i < transform.steps.length; i++) { + let step = transform.steps[i].invert(transform.docs[i]); + let item = new Item(transform.mapping.maps[i], step, selection), merged; + if (merged = lastItem && lastItem.merge(item)) { + item = merged; + if (i) + newItems.pop(); + else + oldItems = oldItems.slice(0, oldItems.length - 1); + } + newItems.push(item); + if (selection) { + eventCount++; + selection = void 0; + } + if (!preserveItems) + lastItem = item; + } + let overflow = eventCount - histOptions.depth; + if (overflow > DEPTH_OVERFLOW) { + oldItems = cutOffEvents(oldItems, overflow); + eventCount -= overflow; + } + return new _Branch(oldItems.append(newItems), eventCount); + } + remapping(from2, to) { + let maps = new Mapping(); + this.items.forEach((item, i) => { + let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from2 ? maps.maps.length - item.mirrorOffset : void 0; + maps.appendMap(item.map, mirrorPos); + }, from2, to); + return maps; + } + addMaps(array) { + if (this.eventCount == 0) + return this; + return new _Branch(this.items.append(array.map((map2) => new Item(map2))), this.eventCount); + } + // When the collab module receives remote changes, the history has + // to know about those, so that it can adjust the steps that were + // rebased on top of the remote changes, and include the position + // maps for the remote changes in its array of items. + rebased(rebasedTransform, rebasedCount) { + if (!this.eventCount) + return this; + let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount); + let mapping = rebasedTransform.mapping; + let newUntil = rebasedTransform.steps.length; + let eventCount = this.eventCount; + this.items.forEach((item) => { + if (item.selection) + eventCount--; + }, start); + let iRebased = rebasedCount; + this.items.forEach((item) => { + let pos = mapping.getMirror(--iRebased); + if (pos == null) + return; + newUntil = Math.min(newUntil, pos); + let map2 = mapping.maps[pos]; + if (item.step) { + let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]); + let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos)); + if (selection) + eventCount++; + rebasedItems.push(new Item(map2, step, selection)); + } else { + rebasedItems.push(new Item(map2)); + } + }, start); + let newMaps = []; + for (let i = rebasedCount; i < newUntil; i++) + newMaps.push(new Item(mapping.maps[i])); + let items = this.items.slice(0, start).append(newMaps).append(rebasedItems); + let branch = new _Branch(items, eventCount); + if (branch.emptyItemCount() > max_empty_items) + branch = branch.compress(this.items.length - rebasedItems.length); + return branch; + } + emptyItemCount() { + let count = 0; + this.items.forEach((item) => { + if (!item.step) + count++; + }); + return count; + } + // Compressing a branch means rewriting it to push the air (map-only + // items) out. During collaboration, these naturally accumulate + // because each remote change adds one. The `upto` argument is used + // to ensure that only the items below a given level are compressed, + // because `rebased` relies on a clean, untouched set of items in + // order to associate old items with rebased steps. + compress(upto = this.items.length) { + let remap = this.remapping(0, upto), mapFrom = remap.maps.length; + let items = [], events = 0; + this.items.forEach((item, i) => { + if (i >= upto) { + items.push(item); + if (item.selection) + events++; + } else if (item.step) { + let step = item.step.map(remap.slice(mapFrom)), map2 = step && step.getMap(); + mapFrom--; + if (map2) + remap.appendMap(map2, mapFrom); + if (step) { + let selection = item.selection && item.selection.map(remap.slice(mapFrom)); + if (selection) + events++; + let newItem = new Item(map2.invert(), step, selection), merged, last = items.length - 1; + if (merged = items.length && items[last].merge(newItem)) + items[last] = merged; + else + items.push(newItem); + } + } else if (item.map) { + mapFrom--; + } + }, this.items.length, 0); + return new _Branch(dist_default.from(items.reverse()), events); + } +}; +Branch.empty = new Branch(dist_default.empty, 0); +function cutOffEvents(items, n) { + let cutPoint; + items.forEach((item, i) => { + if (item.selection && n-- == 0) { + cutPoint = i; + return false; + } + }); + return items.slice(cutPoint); +} +var Item = class _Item { + constructor(map2, step, selection, mirrorOffset) { + this.map = map2; + this.step = step; + this.selection = selection; + this.mirrorOffset = mirrorOffset; + } + merge(other) { + if (this.step && other.step && !other.selection) { + let step = other.step.merge(this.step); + if (step) + return new _Item(step.getMap().invert(), step, this.selection); + } + } +}; +var HistoryState = class { + constructor(done, undone, prevRanges, prevTime, prevComposition) { + this.done = done; + this.undone = undone; + this.prevRanges = prevRanges; + this.prevTime = prevTime; + this.prevComposition = prevComposition; + } +}; +var DEPTH_OVERFLOW = 20; +function applyTransaction(history2, state, tr, options) { + let historyTr = tr.getMeta(historyKey), rebased; + if (historyTr) + return historyTr.historyState; + if (tr.getMeta(closeHistoryKey)) + history2 = new HistoryState(history2.done, history2.undone, null, 0, -1); + let appended = tr.getMeta("appendedTransaction"); + if (tr.steps.length == 0) { + return history2; + } else if (appended && appended.getMeta(historyKey)) { + if (appended.getMeta(historyKey).redo) + return new HistoryState(history2.done.addTransform(tr, void 0, options, mustPreserveItems(state)), history2.undone, rangesFor(tr.mapping.maps), history2.prevTime, history2.prevComposition); + else + return new HistoryState(history2.done, history2.undone.addTransform(tr, void 0, options, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition); + } else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) { + let composition = tr.getMeta("composition"); + let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history2.prevRanges)); + let prevRanges = appended ? mapRanges(history2.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps); + return new HistoryState(history2.done.addTransform(tr, newGroup ? state.selection.getBookmark() : void 0, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history2.prevComposition : composition); + } else if (rebased = tr.getMeta("rebased")) { + return new HistoryState(history2.done.rebased(tr, rebased), history2.undone.rebased(tr, rebased), mapRanges(history2.prevRanges, tr.mapping), history2.prevTime, history2.prevComposition); + } else { + return new HistoryState(history2.done.addMaps(tr.mapping.maps), history2.undone.addMaps(tr.mapping.maps), mapRanges(history2.prevRanges, tr.mapping), history2.prevTime, history2.prevComposition); + } +} +function isAdjacentTo(transform, prevRanges) { + if (!prevRanges) + return false; + if (!transform.docChanged) + return true; + let adjacent = false; + transform.mapping.maps[0].forEach((start, end) => { + for (let i = 0; i < prevRanges.length; i += 2) + if (start <= prevRanges[i + 1] && end >= prevRanges[i]) + adjacent = true; + }); + return adjacent; +} +function rangesFor(maps) { + let result = []; + for (let i = maps.length - 1; i >= 0 && result.length == 0; i--) + maps[i].forEach((_from, _to, from2, to) => result.push(from2, to)); + return result; +} +function mapRanges(ranges, mapping) { + if (!ranges) + return null; + let result = []; + for (let i = 0; i < ranges.length; i += 2) { + let from2 = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1); + if (from2 <= to) + result.push(from2, to); + } + return result; +} +function histTransaction(history2, state, redo2) { + let preserveItems = mustPreserveItems(state); + let histOptions = historyKey.get(state).spec.config; + let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems); + if (!pop) + return null; + let selection = pop.selection.resolve(pop.transform.doc); + let added = (redo2 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems); + let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1); + return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist }); +} +var cachedPreserveItems = false; +var cachedPreserveItemsPlugins = null; +function mustPreserveItems(state) { + let plugins = state.plugins; + if (cachedPreserveItemsPlugins != plugins) { + cachedPreserveItems = false; + cachedPreserveItemsPlugins = plugins; + for (let i = 0; i < plugins.length; i++) + if (plugins[i].spec.historyPreserveItems) { + cachedPreserveItems = true; + break; + } + } + return cachedPreserveItems; +} +var historyKey = new PluginKey("history"); +var closeHistoryKey = new PluginKey("closeHistory"); +function history(config = {}) { + config = { + depth: config.depth || 100, + newGroupDelay: config.newGroupDelay || 500 + }; + return new Plugin({ + key: historyKey, + state: { + init() { + return new HistoryState(Branch.empty, Branch.empty, null, 0, -1); + }, + apply(tr, hist, state) { + return applyTransaction(hist, state, tr, config); + } + }, + config, + props: { + handleDOMEvents: { + beforeinput(view, e) { + let inputType = e.inputType; + let command = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null; + if (!command || !view.editable) + return false; + e.preventDefault(); + return command(view.state, view.dispatch); + } + } + } + }); +} +function buildCommand(redo2, scroll) { + return (state, dispatch) => { + let hist = historyKey.getState(state); + if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0) + return false; + if (dispatch) { + let tr = histTransaction(hist, state, redo2); + if (tr) + dispatch(scroll ? tr.scrollIntoView() : tr); + } + return true; + }; +} +var undo = buildCommand(false, true); +var redo = buildCommand(true, true); +var undoNoScroll = buildCommand(false, false); +var redoNoScroll = buildCommand(true, false); + +// node_modules/@tiptap/extensions/dist/index.js +var CharacterCount = Extension.create({ + name: "characterCount", + addOptions() { + return { + limit: null, + mode: "textSize", + textCounter: (text) => text.length, + wordCounter: (text) => text.split(" ").filter((word) => word !== "").length + }; + }, + addStorage() { + return { + characters: () => 0, + words: () => 0 + }; + }, + onBeforeCreate() { + this.storage.characters = (options) => { + const node = (options == null ? void 0 : options.node) || this.editor.state.doc; + const mode = (options == null ? void 0 : options.mode) || this.options.mode; + if (mode === "textSize") { + const text = node.textBetween(0, node.content.size, void 0, " "); + return this.options.textCounter(text); + } + return node.nodeSize; + }; + this.storage.words = (options) => { + const node = (options == null ? void 0 : options.node) || this.editor.state.doc; + const text = node.textBetween(0, node.content.size, " ", " "); + return this.options.wordCounter(text); + }; + }, + addProseMirrorPlugins() { + let initialEvaluationDone = false; + return [ + new Plugin({ + key: new PluginKey("characterCount"), + appendTransaction: (transactions, oldState, newState) => { + if (initialEvaluationDone) { + return; + } + const limit = this.options.limit; + if (limit === null || limit === void 0 || limit === 0) { + initialEvaluationDone = true; + return; + } + const initialContentSize = this.storage.characters({ node: newState.doc }); + if (initialContentSize > limit) { + const over = initialContentSize - limit; + const from2 = 0; + const to = over; + console.warn( + `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.` + ); + const tr = newState.tr.deleteRange(from2, to); + initialEvaluationDone = true; + return tr; + } + initialEvaluationDone = true; + }, + filterTransaction: (transaction, state) => { + const limit = this.options.limit; + if (!transaction.docChanged || limit === 0 || limit === null || limit === void 0) { + return true; + } + const oldSize = this.storage.characters({ node: state.doc }); + const newSize = this.storage.characters({ node: transaction.doc }); + if (newSize <= limit) { + return true; + } + if (oldSize > limit && newSize > limit && newSize <= oldSize) { + return true; + } + if (oldSize > limit && newSize > limit && newSize > oldSize) { + return false; + } + const isPaste = transaction.getMeta("paste"); + if (!isPaste) { + return false; + } + const pos = transaction.selection.$head.pos; + const over = newSize - limit; + const from2 = pos - over; + const to = pos; + transaction.deleteRange(from2, to); + const updatedSize = this.storage.characters({ node: transaction.doc }); + if (updatedSize > limit) { + return false; + } + return true; + } + }) + ]; + } +}); +var Dropcursor = Extension.create({ + name: "dropCursor", + addOptions() { + return { + color: "currentColor", + width: 1, + class: void 0 + }; + }, + addProseMirrorPlugins() { + return [dropCursor(this.options)]; + } +}); +var Focus = Extension.create({ + name: "focus", + addOptions() { + return { + className: "has-focus", + mode: "all" + }; + }, + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("focus"), + props: { + decorations: ({ doc, selection }) => { + const { isEditable, isFocused } = this.editor; + const { anchor } = selection; + const decorations = []; + if (!isEditable || !isFocused) { + return DecorationSet.create(doc, []); + } + let maxLevels = 0; + if (this.options.mode === "deepest") { + doc.descendants((node, pos) => { + if (node.isText) { + return; + } + const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1; + if (!isCurrent) { + return false; + } + maxLevels += 1; + }); + } + let currentLevel = 0; + doc.descendants((node, pos) => { + if (node.isText) { + return false; + } + const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1; + if (!isCurrent) { + return false; + } + currentLevel += 1; + const outOfScope = this.options.mode === "deepest" && maxLevels - currentLevel > 0 || this.options.mode === "shallowest" && currentLevel > 1; + if (outOfScope) { + return this.options.mode === "deepest"; + } + decorations.push( + Decoration.node(pos, pos + node.nodeSize, { + class: this.options.className + }) + ); + }); + return DecorationSet.create(doc, decorations); + } + } + }) + ]; + } +}); +var Gapcursor = Extension.create({ + name: "gapCursor", + addProseMirrorPlugins() { + return [gapCursor()]; + }, + extendNodeSchema(extension) { + var _a; + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + return { + allowGapCursor: (_a = callOrReturn(getExtensionField(extension, "allowGapCursor", context))) != null ? _a : null + }; + } +}); +var DEFAULT_DATA_ATTRIBUTE = "placeholder"; +function preparePlaceholderAttribute(attr) { + return attr.replace(/\s+/g, "-").replace(/[^a-zA-Z0-9-]/g, "").replace(/^[0-9-]+/, "").replace(/^-+/, "").toLowerCase(); +} +var Placeholder = Extension.create({ + name: "placeholder", + addOptions() { + return { + emptyEditorClass: "is-editor-empty", + emptyNodeClass: "is-empty", + dataAttribute: DEFAULT_DATA_ATTRIBUTE, + placeholder: "Write something …", + showOnlyWhenEditable: true, + showOnlyCurrent: true, + includeChildren: false + }; + }, + addProseMirrorPlugins() { + const dataAttribute = this.options.dataAttribute ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}` : `data-${DEFAULT_DATA_ATTRIBUTE}`; + return [ + new Plugin({ + key: new PluginKey("placeholder"), + props: { + decorations: ({ doc, selection }) => { + const active = this.editor.isEditable || !this.options.showOnlyWhenEditable; + const { anchor } = selection; + const decorations = []; + if (!active) { + return null; + } + const isEmptyDoc = this.editor.isEmpty; + doc.descendants((node, pos) => { + const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize; + const isEmpty = !node.isLeaf && isNodeEmpty(node); + if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) { + const classes = [this.options.emptyNodeClass]; + if (isEmptyDoc) { + classes.push(this.options.emptyEditorClass); + } + const decoration = Decoration.node(pos, pos + node.nodeSize, { + class: classes.join(" "), + [dataAttribute]: typeof this.options.placeholder === "function" ? this.options.placeholder({ + editor: this.editor, + node, + pos, + hasAnchor + }) : this.options.placeholder + }); + decorations.push(decoration); + } + return this.options.includeChildren; + }); + return DecorationSet.create(doc, decorations); + } + } + }) + ]; + } +}); +var Selection2 = Extension.create({ + name: "selection", + addOptions() { + return { + className: "selection" + }; + }, + addProseMirrorPlugins() { + const { editor, options } = this; + return [ + new Plugin({ + key: new PluginKey("selection"), + props: { + decorations(state) { + if (state.selection.empty || editor.isFocused || !editor.isEditable || isNodeSelection(state.selection) || editor.view.dragging) { + return null; + } + return DecorationSet.create(state.doc, [ + Decoration.inline(state.selection.from, state.selection.to, { + class: options.className + }) + ]); + } + } + }) + ]; + } +}); +function nodeEqualsType({ types, node }) { + return node && Array.isArray(types) && types.includes(node.type) || (node == null ? void 0 : node.type) === types; +} +var TrailingNode = Extension.create({ + name: "trailingNode", + addOptions() { + return { + node: void 0, + notAfter: [] + }; + }, + addProseMirrorPlugins() { + var _a; + const plugin = new PluginKey(this.name); + const defaultNode = this.options.node || ((_a = this.editor.schema.topNodeType.contentMatch.defaultType) == null ? void 0 : _a.name) || "paragraph"; + const disabledNodes = Object.entries(this.editor.schema.nodes).map(([, value]) => value).filter((node) => (this.options.notAfter || []).concat(defaultNode).includes(node.name)); + return [ + new Plugin({ + key: plugin, + appendTransaction: (_, __, state) => { + const { doc, tr, schema } = state; + const shouldInsertNodeAtEnd = plugin.getState(state); + const endPosition = doc.content.size; + const type = schema.nodes[defaultNode]; + if (!shouldInsertNodeAtEnd) { + return; + } + return tr.insert(endPosition, type.create()); + }, + state: { + init: (_, state) => { + const lastNode = state.tr.doc.lastChild; + return !nodeEqualsType({ node: lastNode, types: disabledNodes }); + }, + apply: (tr, value) => { + if (!tr.docChanged) { + return value; + } + if (tr.getMeta("__uniqueIDTransaction")) { + return value; + } + const lastNode = tr.doc.lastChild; + return !nodeEqualsType({ node: lastNode, types: disabledNodes }); + } + } + }) + ]; + } +}); +var UndoRedo = Extension.create({ + name: "undoRedo", + addOptions() { + return { + depth: 100, + newGroupDelay: 500 + }; + }, + addCommands() { + return { + undo: () => ({ state, dispatch }) => { + return undo(state, dispatch); + }, + redo: () => ({ state, dispatch }) => { + return redo(state, dispatch); + } + }; + }, + addProseMirrorPlugins() { + return [history(this.options)]; + }, + addKeyboardShortcuts() { + return { + "Mod-z": () => this.editor.commands.undo(), + "Shift-Mod-z": () => this.editor.commands.redo(), + "Mod-y": () => this.editor.commands.redo(), + // Russian keyboard layouts + "Mod-я": () => this.editor.commands.undo(), + "Shift-Mod-я": () => this.editor.commands.redo() + }; + } +}); + +// node_modules/@tiptap/starter-kit/dist/index.js +var StarterKit = Extension.create({ + name: "starterKit", + addExtensions() { + var _a, _b, _c, _d; + const extensions = []; + if (this.options.bold !== false) { + extensions.push(Bold.configure(this.options.bold)); + } + if (this.options.blockquote !== false) { + extensions.push(Blockquote.configure(this.options.blockquote)); + } + if (this.options.bulletList !== false) { + extensions.push(BulletList.configure(this.options.bulletList)); + } + if (this.options.code !== false) { + extensions.push(Code.configure(this.options.code)); + } + if (this.options.codeBlock !== false) { + extensions.push(CodeBlock.configure(this.options.codeBlock)); + } + if (this.options.document !== false) { + extensions.push(Document.configure(this.options.document)); + } + if (this.options.dropcursor !== false) { + extensions.push(Dropcursor.configure(this.options.dropcursor)); + } + if (this.options.gapcursor !== false) { + extensions.push(Gapcursor.configure(this.options.gapcursor)); + } + if (this.options.hardBreak !== false) { + extensions.push(HardBreak.configure(this.options.hardBreak)); + } + if (this.options.heading !== false) { + extensions.push(Heading.configure(this.options.heading)); + } + if (this.options.undoRedo !== false) { + extensions.push(UndoRedo.configure(this.options.undoRedo)); + } + if (this.options.horizontalRule !== false) { + extensions.push(HorizontalRule.configure(this.options.horizontalRule)); + } + if (this.options.italic !== false) { + extensions.push(Italic.configure(this.options.italic)); + } + if (this.options.listItem !== false) { + extensions.push(ListItem.configure(this.options.listItem)); + } + if (this.options.listKeymap !== false) { + extensions.push(ListKeymap.configure((_a = this.options) == null ? void 0 : _a.listKeymap)); + } + if (this.options.link !== false) { + extensions.push(Link.configure((_b = this.options) == null ? void 0 : _b.link)); + } + if (this.options.orderedList !== false) { + extensions.push(OrderedList.configure(this.options.orderedList)); + } + if (this.options.paragraph !== false) { + extensions.push(Paragraph.configure(this.options.paragraph)); + } + if (this.options.strike !== false) { + extensions.push(Strike.configure(this.options.strike)); + } + if (this.options.text !== false) { + extensions.push(Text.configure(this.options.text)); + } + if (this.options.underline !== false) { + extensions.push(Underline.configure((_c = this.options) == null ? void 0 : _c.underline)); + } + if (this.options.trailingNode !== false) { + extensions.push(TrailingNode.configure((_d = this.options) == null ? void 0 : _d.trailingNode)); + } + return extensions; + } +}); +var index_default = StarterKit; +export { + StarterKit, + index_default as default +}; +//# sourceMappingURL=@tiptap_starter-kit.js.map diff --git a/frontend/node_modules/.vite/deps/@tiptap_starter-kit.js.map b/frontend/node_modules/.vite/deps/@tiptap_starter-kit.js.map new file mode 100644 index 00000000..d6bafd1a --- /dev/null +++ b/frontend/node_modules/.vite/deps/@tiptap_starter-kit.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../@tiptap/core/src/jsx-runtime.ts", "../../@tiptap/extension-blockquote/src/blockquote.tsx", "../../@tiptap/extension-blockquote/src/index.ts", "../../@tiptap/extension-bold/src/bold.tsx", "../../@tiptap/extension-bold/src/index.ts", "../../@tiptap/extension-code/src/code.ts", "../../@tiptap/extension-code/src/index.ts", "../../@tiptap/extension-code-block/src/code-block.ts", "../../@tiptap/extension-code-block/src/index.ts", "../../@tiptap/extension-document/src/document.ts", "../../@tiptap/extension-document/src/index.ts", "../../@tiptap/extension-hard-break/src/hard-break.ts", "../../@tiptap/extension-hard-break/src/index.ts", "../../@tiptap/extension-heading/src/heading.ts", "../../@tiptap/extension-heading/src/index.ts", "../../@tiptap/extension-horizontal-rule/src/horizontal-rule.ts", "../../@tiptap/extension-horizontal-rule/src/index.ts", "../../@tiptap/extension-italic/src/italic.ts", "../../@tiptap/extension-italic/src/index.ts", "../../@tiptap/extension-list/src/bullet-list/bullet-list.ts", "../../@tiptap/extension-list/src/item/list-item.ts", "../../@tiptap/extension-list/src/keymap/list-keymap.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/index.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/findListItemPos.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/getNextListDepth.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/handleBackspace.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/hasListBefore.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/hasListItemBefore.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/listItemHasSubList.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/handleDelete.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/nextListIsDeeper.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/nextListIsHigher.ts", "../../@tiptap/extension-list/src/keymap/listHelpers/hasListItemAfter.ts", "../../@tiptap/extension-list/src/kit/index.ts", "../../@tiptap/extension-list/src/ordered-list/ordered-list.ts", "../../@tiptap/extension-list/src/ordered-list/utils.ts", "../../@tiptap/extension-list/src/task-item/task-item.ts", "../../@tiptap/extension-list/src/task-list/task-list.ts", "../../@tiptap/extension-paragraph/src/paragraph.ts", "../../@tiptap/extension-paragraph/src/index.ts", "../../@tiptap/extension-strike/src/strike.ts", "../../@tiptap/extension-strike/src/index.ts", "../../@tiptap/extension-text/src/text.ts", "../../@tiptap/extension-text/src/index.ts", "../../@tiptap/extension-underline/src/underline.ts", "../../@tiptap/extension-underline/src/index.ts", "../../prosemirror-dropcursor/dist/index.js", "../../prosemirror-gapcursor/dist/index.js", "../../rope-sequence/dist/index.js", "../../prosemirror-history/dist/index.js", "../../@tiptap/extensions/src/character-count/character-count.ts", "../../@tiptap/extensions/src/drop-cursor/drop-cursor.ts", "../../@tiptap/extensions/src/focus/focus.ts", "../../@tiptap/extensions/src/gap-cursor/gap-cursor.ts", "../../@tiptap/extensions/src/placeholder/placeholder.ts", "../../@tiptap/extensions/src/selection/selection.ts", "../../@tiptap/extensions/src/trailing-node/trailing-node.ts", "../../@tiptap/extensions/src/undo-redo/undo-redo.ts", "../../@tiptap/starter-kit/src/starter-kit.ts", "../../@tiptap/starter-kit/src/index.ts"], + "sourcesContent": ["export type Attributes = Record\n\nexport type DOMOutputSpecElement = 0 | Attributes | DOMOutputSpecArray\n/**\n * Better describes the output of a `renderHTML` function in prosemirror\n * @see https://prosemirror.net/docs/ref/#model.DOMOutputSpec\n */\nexport type DOMOutputSpecArray =\n | [string]\n | [string, Attributes]\n | [string, 0]\n | [string, Attributes, 0]\n | [string, Attributes, DOMOutputSpecArray | 0]\n | [string, DOMOutputSpecArray]\n\n// JSX types for Tiptap's JSX runtime\n// These types only apply when using @jsxImportSource @tiptap/core\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace JSX {\n export type Element = DOMOutputSpecArray\n export interface IntrinsicElements {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n }\n export interface ElementChildrenAttribute {\n children: unknown\n }\n}\n\nexport type JSXRenderer = (\n tag: 'slot' | string | ((props?: Attributes) => DOMOutputSpecArray | DOMOutputSpecElement),\n props?: Attributes,\n ...children: JSXRenderer[]\n) => DOMOutputSpecArray | DOMOutputSpecElement\n\nexport function Fragment(props: { children: JSXRenderer[] }) {\n return props.children\n}\n\nexport const h: JSXRenderer = (tag, attributes) => {\n // Treat the slot tag as the Prosemirror hole to render content into\n if (tag === 'slot') {\n return 0\n }\n\n // If the tag is a function, call it with the props\n if (tag instanceof Function) {\n return tag(attributes)\n }\n\n const { children, ...rest } = attributes ?? {}\n\n if (tag === 'svg') {\n throw new Error('SVG elements are not supported in the JSX syntax, use the array syntax instead')\n }\n\n // Otherwise, return the tag, attributes, and children\n return [tag, rest, children]\n}\n\n// See\n// https://esbuild.github.io/api/#jsx-import-source\n// https://www.typescriptlang.org/tsconfig/#jsxImportSource\n\nexport { h as createElement, h as jsx, h as jsxDEV, h as jsxs }\n", "/** @jsxImportSource @tiptap/core */\nimport { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nexport interface BlockquoteOptions {\n /**\n * HTML attributes to add to the blockquote element\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n blockQuote: {\n /**\n * Set a blockquote node\n */\n setBlockquote: () => ReturnType\n /**\n * Toggle a blockquote node\n */\n toggleBlockquote: () => ReturnType\n /**\n * Unset a blockquote node\n */\n unsetBlockquote: () => ReturnType\n }\n }\n}\n\n/**\n * Matches a blockquote to a `>` as input.\n */\nexport const inputRegex = /^\\s*>\\s$/\n\n/**\n * This extension allows you to create blockquotes.\n * @see https://tiptap.dev/api/nodes/blockquote\n */\nexport const Blockquote = Node.create({\n name: 'blockquote',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n content: 'block+',\n\n group: 'block',\n\n defining: true,\n\n parseHTML() {\n return [{ tag: 'blockquote' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return (\n

\n \n
\n )\n },\n\n parseMarkdown: (token, helpers) => {\n return helpers.createNode('blockquote', undefined, helpers.parseChildren(token.tokens || []))\n },\n\n renderMarkdown: (node, h) => {\n if (!node.content) {\n return ''\n }\n\n // Use a single '>' prefix regardless of nesting level\n // Nested blockquotes will add their own '>' prefix recursively\n const prefix = '>'\n const result: string[] = []\n\n node.content.forEach(child => {\n // Render each child node as an array so it gets processed properly\n const childContent = h.renderChildren([child])\n const lines = childContent.split('\\n')\n\n const linesWithPrefix = lines.map(line => {\n // Don't add prefix to empty lines\n if (line.trim() === '') {\n return prefix\n }\n\n // Nested blockquotes will already have their own prefixes\n // We just need to add our own prefix at the start\n return `${prefix} ${line}`\n })\n\n result.push(linesWithPrefix.join('\\n'))\n })\n\n // Add separator lines between children\n return result.join(`\\n${prefix}\\n`)\n },\n\n addCommands() {\n return {\n setBlockquote:\n () =>\n ({ commands }) => {\n return commands.wrapIn(this.name)\n },\n toggleBlockquote:\n () =>\n ({ commands }) => {\n return commands.toggleWrap(this.name)\n },\n unsetBlockquote:\n () =>\n ({ commands }) => {\n return commands.lift(this.name)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-b': () => this.editor.commands.toggleBlockquote(),\n }\n },\n\n addInputRules() {\n return [\n wrappingInputRule({\n find: inputRegex,\n type: this.type,\n }),\n ]\n },\n})\n", "import { Blockquote } from './blockquote.jsx'\n\nexport * from './blockquote.jsx'\n\nexport default Blockquote\n", "/** @jsxImportSource @tiptap/core */\nimport { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface BoldOptions {\n /**\n * HTML attributes to add to the bold element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n bold: {\n /**\n * Set a bold mark\n */\n setBold: () => ReturnType\n /**\n * Toggle a bold mark\n */\n toggleBold: () => ReturnType\n /**\n * Unset a bold mark\n */\n unsetBold: () => ReturnType\n }\n }\n}\n\n/**\n * Matches bold text via `**` as input.\n */\nexport const starInputRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))$/\n\n/**\n * Matches bold text via `**` while pasting.\n */\nexport const starPasteRegex = /(?:^|\\s)(\\*\\*(?!\\s+\\*\\*)((?:[^*]+))\\*\\*(?!\\s+\\*\\*))/g\n\n/**\n * Matches bold text via `__` as input.\n */\nexport const underscoreInputRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))$/\n\n/**\n * Matches bold text via `__` while pasting.\n */\nexport const underscorePasteRegex = /(?:^|\\s)(__(?!\\s+__)((?:[^_]+))__(?!\\s+__))/g\n\n/**\n * This extension allows you to mark text as bold.\n * @see https://tiptap.dev/api/marks/bold\n */\nexport const Bold = Mark.create({\n name: 'bold',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 'strong',\n },\n {\n tag: 'b',\n getAttrs: node => (node as HTMLElement).style.fontWeight !== 'normal' && null,\n },\n {\n style: 'font-weight=400',\n clearMark: mark => mark.type.name === this.name,\n },\n {\n style: 'font-weight',\n getAttrs: value => /^(bold(er)?|[5-9]\\d{2,})$/.test(value as string) && null,\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n return (\n \n \n \n )\n },\n\n markdownTokenName: 'strong',\n\n parseMarkdown: (token, helpers) => {\n // Convert 'strong' token to bold mark\n return helpers.applyMark('bold', helpers.parseInline(token.tokens || []))\n },\n\n renderMarkdown: (node, h) => {\n return `**${h.renderChildren(node)}**`\n },\n\n addCommands() {\n return {\n setBold:\n () =>\n ({ commands }) => {\n return commands.setMark(this.name)\n },\n toggleBold:\n () =>\n ({ commands }) => {\n return commands.toggleMark(this.name)\n },\n unsetBold:\n () =>\n ({ commands }) => {\n return commands.unsetMark(this.name)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-b': () => this.editor.commands.toggleBold(),\n 'Mod-B': () => this.editor.commands.toggleBold(),\n }\n },\n\n addInputRules() {\n return [\n markInputRule({\n find: starInputRegex,\n type: this.type,\n }),\n markInputRule({\n find: underscoreInputRegex,\n type: this.type,\n }),\n ]\n },\n\n addPasteRules() {\n return [\n markPasteRule({\n find: starPasteRegex,\n type: this.type,\n }),\n markPasteRule({\n find: underscorePasteRegex,\n type: this.type,\n }),\n ]\n },\n})\n", "import { Bold } from './bold.jsx'\n\nexport * from './bold.jsx'\n\nexport default Bold\n", "import { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface CodeOptions {\n /**\n * The HTML attributes applied to the code element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n code: {\n /**\n * Set a code mark\n */\n setCode: () => ReturnType\n /**\n * Toggle inline code\n */\n toggleCode: () => ReturnType\n /**\n * Unset a code mark\n */\n unsetCode: () => ReturnType\n }\n }\n}\n\n/**\n * Regular expressions to match inline code blocks enclosed in backticks.\n * It matches:\n * - An opening backtick, followed by\n * - Any text that doesn't include a backtick (captured for marking), followed by\n * - A closing backtick as the final character.\n * This ensures that any text between backticks is formatted as code,\n * regardless of the surrounding characters (exception being another backtick).\n */\nexport const inputRegex = /(^|[^`])`([^`]+)`(?!`)$/\n\n/**\n * Matches inline code while pasting.\n */\nexport const pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g\n\n/**\n * This extension allows you to mark text as inline code.\n * @see https://tiptap.dev/api/marks/code\n */\nexport const Code = Mark.create({\n name: 'code',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n excludes: '_',\n\n code: true,\n\n exitable: true,\n\n parseHTML() {\n return [{ tag: 'code' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['code', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n markdownTokenName: 'codespan',\n\n parseMarkdown: (token, helpers) => {\n // Convert 'codespan' token to code mark\n // For codespan tokens, we use the raw text content, not tokens\n return helpers.applyMark('code', [{ type: 'text', text: token.text || '' }])\n },\n\n renderMarkdown: (node, h) => {\n if (!node.content) {\n return ''\n }\n\n return `\\`${h.renderChildren(node.content)}\\``\n },\n\n addCommands() {\n return {\n setCode:\n () =>\n ({ commands }) => {\n return commands.setMark(this.name)\n },\n toggleCode:\n () =>\n ({ commands }) => {\n return commands.toggleMark(this.name)\n },\n unsetCode:\n () =>\n ({ commands }) => {\n return commands.unsetMark(this.name)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-e': () => this.editor.commands.toggleCode(),\n }\n },\n\n addInputRules() {\n return [\n markInputRule({\n find: inputRegex,\n type: this.type,\n }),\n ]\n },\n\n addPasteRules() {\n return [\n markPasteRule({\n find: pasteRegex,\n type: this.type,\n }),\n ]\n },\n})\n", "import { Code } from './code.js'\n\nexport * from './code.js'\n\nexport default Code\n", "import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'\nimport { Plugin, PluginKey, Selection, TextSelection } from '@tiptap/pm/state'\n\nconst DEFAULT_TAB_SIZE = 4\n\nexport interface CodeBlockOptions {\n /**\n * Adds a prefix to language classes that are applied to code tags.\n * @default 'language-'\n */\n languageClassPrefix: string | null | undefined\n /**\n * Define whether the node should be exited on triple enter.\n * @default true\n */\n exitOnTripleEnter: boolean | null | undefined\n /**\n * Define whether the node should be exited on arrow down if there is no node after it.\n * @default true\n */\n exitOnArrowDown: boolean | null | undefined\n /**\n * The default language.\n * @default null\n * @example 'js'\n */\n defaultLanguage: string | null | undefined\n /**\n * Enable tab key for indentation in code blocks.\n * @default false\n */\n enableTabIndentation: boolean | null | undefined\n /**\n * The number of spaces to use for tab indentation.\n * @default 4\n */\n tabSize: number | null | undefined\n /**\n * Custom HTML attributes that should be added to the rendered HTML tag.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n codeBlock: {\n /**\n * Set a code block\n * @param attributes Code block attributes\n * @example editor.commands.setCodeBlock({ language: 'javascript' })\n */\n setCodeBlock: (attributes?: { language: string }) => ReturnType\n /**\n * Toggle a code block\n * @param attributes Code block attributes\n * @example editor.commands.toggleCodeBlock({ language: 'javascript' })\n */\n toggleCodeBlock: (attributes?: { language: string }) => ReturnType\n }\n }\n}\n\n/**\n * Matches a code block with backticks.\n */\nexport const backtickInputRegex = /^```([a-z]+)?[\\s\\n]$/\n\n/**\n * Matches a code block with tildes.\n */\nexport const tildeInputRegex = /^~~~([a-z]+)?[\\s\\n]$/\n\n/**\n * This extension allows you to create code blocks.\n * @see https://tiptap.dev/api/nodes/code-block\n */\nexport const CodeBlock = Node.create({\n name: 'codeBlock',\n\n addOptions() {\n return {\n languageClassPrefix: 'language-',\n exitOnTripleEnter: true,\n exitOnArrowDown: true,\n defaultLanguage: null,\n enableTabIndentation: false,\n tabSize: DEFAULT_TAB_SIZE,\n HTMLAttributes: {},\n }\n },\n\n content: 'text*',\n\n marks: '',\n\n group: 'block',\n\n code: true,\n\n defining: true,\n\n addAttributes() {\n return {\n language: {\n default: this.options.defaultLanguage,\n parseHTML: element => {\n const { languageClassPrefix } = this.options\n\n if (!languageClassPrefix) {\n return null\n }\n\n const classNames = [...(element.firstElementChild?.classList || [])]\n const languages = classNames\n .filter(className => className.startsWith(languageClassPrefix))\n .map(className => className.replace(languageClassPrefix, ''))\n const language = languages[0]\n\n if (!language) {\n return null\n }\n\n return language\n },\n rendered: false,\n },\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 'pre',\n preserveWhitespace: 'full',\n },\n ]\n },\n\n renderHTML({ node, HTMLAttributes }) {\n return [\n 'pre',\n mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),\n [\n 'code',\n {\n class: node.attrs.language ? this.options.languageClassPrefix + node.attrs.language : null,\n },\n 0,\n ],\n ]\n },\n\n markdownTokenName: 'code',\n\n parseMarkdown: (token, helpers) => {\n if (token.raw?.startsWith('```') === false && token.codeBlockStyle !== 'indented') {\n return []\n }\n\n return helpers.createNode(\n 'codeBlock',\n { language: token.lang || null },\n token.text ? [helpers.createTextNode(token.text)] : [],\n )\n },\n\n renderMarkdown: (node, h) => {\n let output = ''\n const language = node.attrs?.language || ''\n\n if (!node.content) {\n output = `\\`\\`\\`${language}\\n\\n\\`\\`\\``\n } else {\n const lines = [`\\`\\`\\`${language}`, h.renderChildren(node.content), '```']\n output = lines.join('\\n')\n }\n\n return output\n },\n\n addCommands() {\n return {\n setCodeBlock:\n attributes =>\n ({ commands }) => {\n return commands.setNode(this.name, attributes)\n },\n toggleCodeBlock:\n attributes =>\n ({ commands }) => {\n return commands.toggleNode(this.name, 'paragraph', attributes)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Alt-c': () => this.editor.commands.toggleCodeBlock(),\n\n // remove code block when at start of document or code block is empty\n Backspace: () => {\n const { empty, $anchor } = this.editor.state.selection\n const isAtStart = $anchor.pos === 1\n\n if (!empty || $anchor.parent.type.name !== this.name) {\n return false\n }\n\n if (isAtStart || !$anchor.parent.textContent.length) {\n return this.editor.commands.clearNodes()\n }\n\n return false\n },\n\n // handle tab indentation\n Tab: ({ editor }) => {\n if (!this.options.enableTabIndentation) {\n return false\n }\n\n const tabSize = this.options.tabSize ?? DEFAULT_TAB_SIZE\n const { state } = editor\n const { selection } = state\n const { $from, empty } = selection\n\n if ($from.parent.type !== this.type) {\n return false\n }\n\n const indent = ' '.repeat(tabSize)\n\n if (empty) {\n return editor.commands.insertContent(indent)\n }\n\n return editor.commands.command(({ tr }) => {\n const { from, to } = selection\n const text = state.doc.textBetween(from, to, '\\n', '\\n')\n const lines = text.split('\\n')\n const indentedText = lines.map(line => indent + line).join('\\n')\n\n tr.replaceWith(from, to, state.schema.text(indentedText))\n return true\n })\n },\n\n // handle shift+tab reverse indentation\n 'Shift-Tab': ({ editor }) => {\n if (!this.options.enableTabIndentation) {\n return false\n }\n\n const tabSize = this.options.tabSize ?? DEFAULT_TAB_SIZE\n const { state } = editor\n const { selection } = state\n const { $from, empty } = selection\n\n if ($from.parent.type !== this.type) {\n return false\n }\n\n if (empty) {\n return editor.commands.command(({ tr }) => {\n const { pos } = $from\n const codeBlockStart = $from.start()\n const codeBlockEnd = $from.end()\n\n const allText = state.doc.textBetween(codeBlockStart, codeBlockEnd, '\\n', '\\n')\n const lines = allText.split('\\n')\n\n let currentLineIndex = 0\n let charCount = 0\n const relativeCursorPos = pos - codeBlockStart\n\n for (let i = 0; i < lines.length; i += 1) {\n if (charCount + lines[i].length >= relativeCursorPos) {\n currentLineIndex = i\n break\n }\n charCount += lines[i].length + 1\n }\n\n const currentLine = lines[currentLineIndex]\n const leadingSpaces = currentLine.match(/^ */)?.[0] || ''\n const spacesToRemove = Math.min(leadingSpaces.length, tabSize)\n\n if (spacesToRemove === 0) {\n return true\n }\n\n let lineStartPos = codeBlockStart\n for (let i = 0; i < currentLineIndex; i += 1) {\n lineStartPos += lines[i].length + 1\n }\n\n tr.delete(lineStartPos, lineStartPos + spacesToRemove)\n\n const cursorPosInLine = pos - lineStartPos\n if (cursorPosInLine <= spacesToRemove) {\n tr.setSelection(TextSelection.create(tr.doc, lineStartPos))\n }\n\n return true\n })\n }\n\n return editor.commands.command(({ tr }) => {\n const { from, to } = selection\n const text = state.doc.textBetween(from, to, '\\n', '\\n')\n const lines = text.split('\\n')\n const reverseIndentText = lines\n .map(line => {\n const leadingSpaces = line.match(/^ */)?.[0] || ''\n const spacesToRemove = Math.min(leadingSpaces.length, tabSize)\n return line.slice(spacesToRemove)\n })\n .join('\\n')\n\n tr.replaceWith(from, to, state.schema.text(reverseIndentText))\n return true\n })\n },\n\n // exit node on triple enter\n Enter: ({ editor }) => {\n if (!this.options.exitOnTripleEnter) {\n return false\n }\n\n const { state } = editor\n const { selection } = state\n const { $from, empty } = selection\n\n if (!empty || $from.parent.type !== this.type) {\n return false\n }\n\n const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n const endsWithDoubleNewline = $from.parent.textContent.endsWith('\\n\\n')\n\n if (!isAtEnd || !endsWithDoubleNewline) {\n return false\n }\n\n return editor\n .chain()\n .command(({ tr }) => {\n tr.delete($from.pos - 2, $from.pos)\n\n return true\n })\n .exitCode()\n .run()\n },\n\n // exit node on arrow down\n ArrowDown: ({ editor }) => {\n if (!this.options.exitOnArrowDown) {\n return false\n }\n\n const { state } = editor\n const { selection, doc } = state\n const { $from, empty } = selection\n\n if (!empty || $from.parent.type !== this.type) {\n return false\n }\n\n const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n\n if (!isAtEnd) {\n return false\n }\n\n const after = $from.after()\n\n if (after === undefined) {\n return false\n }\n\n const nodeAfter = doc.nodeAt(after)\n\n if (nodeAfter) {\n return editor.commands.command(({ tr }) => {\n tr.setSelection(Selection.near(doc.resolve(after)))\n return true\n })\n }\n\n return editor.commands.exitCode()\n },\n }\n },\n\n addInputRules() {\n return [\n textblockTypeInputRule({\n find: backtickInputRegex,\n type: this.type,\n getAttributes: match => ({\n language: match[1],\n }),\n }),\n textblockTypeInputRule({\n find: tildeInputRegex,\n type: this.type,\n getAttributes: match => ({\n language: match[1],\n }),\n }),\n ]\n },\n\n addProseMirrorPlugins() {\n return [\n // this plugin creates a code block for pasted content from VS Code\n // we can also detect the copied code language\n new Plugin({\n key: new PluginKey('codeBlockVSCodeHandler'),\n props: {\n handlePaste: (view, event) => {\n if (!event.clipboardData) {\n return false\n }\n\n // don’t create a new code block within code blocks\n if (this.editor.isActive(this.type.name)) {\n return false\n }\n\n const text = event.clipboardData.getData('text/plain')\n const vscode = event.clipboardData.getData('vscode-editor-data')\n const vscodeData = vscode ? JSON.parse(vscode) : undefined\n const language = vscodeData?.mode\n\n if (!text || !language) {\n return false\n }\n\n const { tr, schema } = view.state\n\n // prepare a text node\n // strip carriage return chars from text pasted as code\n // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd\n const textNode = schema.text(text.replace(/\\r\\n?/g, '\\n'))\n\n // create a code block with the text node\n // replace selection with the code block\n tr.replaceSelectionWith(this.type.create({ language }, textNode))\n\n if (tr.selection.$from.parent.type !== this.type) {\n // put cursor inside the newly created code block\n tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))))\n }\n\n // store meta information\n // this is useful for other plugins that depends on the paste event\n // like the paste rule plugin\n tr.setMeta('paste', true)\n\n view.dispatch(tr)\n\n return true\n },\n },\n }),\n ]\n },\n})\n", "import { CodeBlock } from './code-block.js'\n\nexport * from './code-block.js'\n\nexport default CodeBlock\n", "import { Node } from '@tiptap/core'\n\n/**\n * The default document node which represents the top level node of the editor.\n * @see https://tiptap.dev/api/nodes/document\n */\nexport const Document = Node.create({\n name: 'doc',\n topNode: true,\n content: 'block+',\n\n renderMarkdown: (node, h) => {\n if (!node.content) {\n return ''\n }\n\n return h.renderChildren(node.content, '\\n\\n')\n },\n})\n", "import { Document } from './document.js'\n\nexport * from './document.js'\n\nexport default Document\n", "import { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface HardBreakOptions {\n /**\n * Controls if marks should be kept after being split by a hard break.\n * @default true\n * @example false\n */\n keepMarks: boolean\n\n /**\n * HTML attributes to add to the hard break element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n hardBreak: {\n /**\n * Add a hard break\n * @example editor.commands.setHardBreak()\n */\n setHardBreak: () => ReturnType\n }\n }\n}\n\n/**\n * This extension allows you to insert hard breaks.\n * @see https://www.tiptap.dev/api/nodes/hard-break\n */\nexport const HardBreak = Node.create({\n name: 'hardBreak',\n\n markdownTokenName: 'br',\n\n addOptions() {\n return {\n keepMarks: true,\n HTMLAttributes: {},\n }\n },\n\n inline: true,\n\n group: 'inline',\n\n selectable: false,\n\n linebreakReplacement: true,\n\n parseHTML() {\n return [{ tag: 'br' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['br', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]\n },\n\n renderText() {\n return '\\n'\n },\n\n renderMarkdown: () => ` \\n`,\n\n parseMarkdown: () => {\n return {\n type: 'hardBreak',\n }\n },\n\n addCommands() {\n return {\n setHardBreak:\n () =>\n ({ commands, chain, state, editor }) => {\n return commands.first([\n () => commands.exitCode(),\n () =>\n commands.command(() => {\n const { selection, storedMarks } = state\n\n if (selection.$from.parent.type.spec.isolating) {\n return false\n }\n\n const { keepMarks } = this.options\n const { splittableMarks } = editor.extensionManager\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n return chain()\n .insertContent({ type: this.name })\n .command(({ tr, dispatch }) => {\n if (dispatch && marks && keepMarks) {\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n }\n\n return true\n })\n .run()\n }),\n ])\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Enter': () => this.editor.commands.setHardBreak(),\n 'Shift-Enter': () => this.editor.commands.setHardBreak(),\n }\n },\n})\n", "import { HardBreak } from './hard-break.js'\n\nexport * from './hard-break.js'\n\nexport default HardBreak\n", "import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'\n\n/**\n * The heading level options.\n */\nexport type Level = 1 | 2 | 3 | 4 | 5 | 6\n\nexport interface HeadingOptions {\n /**\n * The available heading levels.\n * @default [1, 2, 3, 4, 5, 6]\n * @example [1, 2, 3]\n */\n levels: Level[]\n\n /**\n * The HTML attributes for a heading node.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n heading: {\n /**\n * Set a heading node\n * @param attributes The heading attributes\n * @example editor.commands.setHeading({ level: 1 })\n */\n setHeading: (attributes: { level: Level }) => ReturnType\n /**\n * Toggle a heading node\n * @param attributes The heading attributes\n * @example editor.commands.toggleHeading({ level: 1 })\n */\n toggleHeading: (attributes: { level: Level }) => ReturnType\n }\n }\n}\n\n/**\n * This extension allows you to create headings.\n * @see https://www.tiptap.dev/api/nodes/heading\n */\nexport const Heading = Node.create({\n name: 'heading',\n\n addOptions() {\n return {\n levels: [1, 2, 3, 4, 5, 6],\n HTMLAttributes: {},\n }\n },\n\n content: 'inline*',\n\n group: 'block',\n\n defining: true,\n\n addAttributes() {\n return {\n level: {\n default: 1,\n rendered: false,\n },\n }\n },\n\n parseHTML() {\n return this.options.levels.map((level: Level) => ({\n tag: `h${level}`,\n attrs: { level },\n }))\n },\n\n renderHTML({ node, HTMLAttributes }) {\n const hasLevel = this.options.levels.includes(node.attrs.level)\n const level = hasLevel ? node.attrs.level : this.options.levels[0]\n\n return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n parseMarkdown: (token, helpers) => {\n // Convert 'heading' token to heading node\n // marked provides 'depth' property (1-6) for heading level\n return helpers.createNode('heading', { level: token.depth || 1 }, helpers.parseInline(token.tokens || []))\n },\n\n renderMarkdown: (node, h) => {\n const level = node.attrs?.level ? parseInt(node.attrs.level as string, 10) : 1\n const headingChars = '#'.repeat(level)\n\n if (!node.content) {\n return ''\n }\n\n // Use current context for proper joining/spacing\n return `${headingChars} ${h.renderChildren(node.content)}`\n },\n\n addCommands() {\n return {\n setHeading:\n attributes =>\n ({ commands }) => {\n if (!this.options.levels.includes(attributes.level)) {\n return false\n }\n\n return commands.setNode(this.name, attributes)\n },\n toggleHeading:\n attributes =>\n ({ commands }) => {\n if (!this.options.levels.includes(attributes.level)) {\n return false\n }\n\n return commands.toggleNode(this.name, 'paragraph', attributes)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return this.options.levels.reduce(\n (items, level) => ({\n ...items,\n ...{\n [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }),\n },\n }),\n {},\n )\n },\n\n addInputRules() {\n return this.options.levels.map(level => {\n return textblockTypeInputRule({\n find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\\\s$`),\n type: this.type,\n getAttributes: {\n level,\n },\n })\n })\n },\n})\n", "import { Heading } from './heading.js'\n\nexport * from './heading.js'\n\nexport default Heading\n", "import { canInsertNode, isNodeSelection, mergeAttributes, Node, nodeInputRule } from '@tiptap/core'\nimport { NodeSelection, TextSelection } from '@tiptap/pm/state'\n\nexport interface HorizontalRuleOptions {\n /**\n * The HTML attributes for a horizontal rule node.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n /**\n * The default type to insert after the horizontal rule.\n * @default \"paragraph\"\n * @example \"heading\"\n */\n nextNodeType: string\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n horizontalRule: {\n /**\n * Add a horizontal rule\n * @example editor.commands.setHorizontalRule()\n */\n setHorizontalRule: () => ReturnType\n }\n }\n}\n\n/**\n * This extension allows you to insert horizontal rules.\n * @see https://www.tiptap.dev/api/nodes/horizontal-rule\n */\nexport const HorizontalRule = Node.create({\n name: 'horizontalRule',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n nextNodeType: 'paragraph',\n }\n },\n\n group: 'block',\n\n parseHTML() {\n return [{ tag: 'hr' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['hr', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]\n },\n\n markdownTokenName: 'hr',\n\n parseMarkdown: (token, helpers) => {\n return helpers.createNode('horizontalRule')\n },\n\n renderMarkdown: () => {\n return '---'\n },\n\n addCommands() {\n return {\n setHorizontalRule:\n () =>\n ({ chain, state }) => {\n // Check if we can insert the node at the current selection\n if (!canInsertNode(state, state.schema.nodes[this.name])) {\n return false\n }\n\n const { selection } = state\n const { $to: $originTo } = selection\n\n const currentChain = chain()\n\n if (isNodeSelection(selection)) {\n currentChain.insertContentAt($originTo.pos, {\n type: this.name,\n })\n } else {\n currentChain.insertContent({ type: this.name })\n }\n\n return (\n currentChain\n // set cursor after horizontal rule\n .command(({ state: chainState, tr, dispatch }) => {\n if (dispatch) {\n const { $to } = tr.selection\n const posAfter = $to.end()\n\n if ($to.nodeAfter) {\n if ($to.nodeAfter.isTextblock) {\n tr.setSelection(TextSelection.create(tr.doc, $to.pos + 1))\n } else if ($to.nodeAfter.isBlock) {\n tr.setSelection(NodeSelection.create(tr.doc, $to.pos))\n } else {\n tr.setSelection(TextSelection.create(tr.doc, $to.pos))\n }\n } else {\n // add node after horizontal rule if it’s the end of the document\n const nodeType =\n chainState.schema.nodes[this.options.nextNodeType] || $to.parent.type.contentMatch.defaultType\n const node = nodeType?.create()\n\n if (node) {\n tr.insert(posAfter, node)\n tr.setSelection(TextSelection.create(tr.doc, posAfter + 1))\n }\n }\n\n tr.scrollIntoView()\n }\n\n return true\n })\n .run()\n )\n },\n }\n },\n\n addInputRules() {\n return [\n nodeInputRule({\n find: /^(?:---|—-|___\\s|\\*\\*\\*\\s)$/,\n type: this.type,\n }),\n ]\n },\n})\n", "import { HorizontalRule } from './horizontal-rule.js'\n\nexport * from './horizontal-rule.js'\n\nexport default HorizontalRule\n", "import { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface ItalicOptions {\n /**\n * HTML attributes to add to the italic element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n italic: {\n /**\n * Set an italic mark\n * @example editor.commands.setItalic()\n */\n setItalic: () => ReturnType\n /**\n * Toggle an italic mark\n * @example editor.commands.toggleItalic()\n */\n toggleItalic: () => ReturnType\n /**\n * Unset an italic mark\n * @example editor.commands.unsetItalic()\n */\n unsetItalic: () => ReturnType\n }\n }\n}\n\n/**\n * Matches an italic to a *italic* on input.\n */\nexport const starInputRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))$/\n\n/**\n * Matches an italic to a *italic* on paste.\n */\nexport const starPasteRegex = /(?:^|\\s)(\\*(?!\\s+\\*)((?:[^*]+))\\*(?!\\s+\\*))/g\n\n/**\n * Matches an italic to a _italic_ on input.\n */\nexport const underscoreInputRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))$/\n\n/**\n * Matches an italic to a _italic_ on paste.\n */\nexport const underscorePasteRegex = /(?:^|\\s)(_(?!\\s+_)((?:[^_]+))_(?!\\s+_))/g\n\n/**\n * This extension allows you to create italic text.\n * @see https://www.tiptap.dev/api/marks/italic\n */\nexport const Italic = Mark.create({\n name: 'italic',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 'em',\n },\n {\n tag: 'i',\n getAttrs: node => (node as HTMLElement).style.fontStyle !== 'normal' && null,\n },\n {\n style: 'font-style=normal',\n clearMark: mark => mark.type.name === this.name,\n },\n {\n style: 'font-style=italic',\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['em', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n addCommands() {\n return {\n setItalic:\n () =>\n ({ commands }) => {\n return commands.setMark(this.name)\n },\n toggleItalic:\n () =>\n ({ commands }) => {\n return commands.toggleMark(this.name)\n },\n unsetItalic:\n () =>\n ({ commands }) => {\n return commands.unsetMark(this.name)\n },\n }\n },\n\n markdownTokenName: 'em',\n\n parseMarkdown: (token, helpers) => {\n // Convert 'em' token to italic mark\n return helpers.applyMark('italic', helpers.parseInline(token.tokens || []))\n },\n\n renderMarkdown: (node, h) => {\n return `*${h.renderChildren(node)}*`\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-i': () => this.editor.commands.toggleItalic(),\n 'Mod-I': () => this.editor.commands.toggleItalic(),\n }\n },\n\n addInputRules() {\n return [\n markInputRule({\n find: starInputRegex,\n type: this.type,\n }),\n markInputRule({\n find: underscoreInputRegex,\n type: this.type,\n }),\n ]\n },\n\n addPasteRules() {\n return [\n markPasteRule({\n find: starPasteRegex,\n type: this.type,\n }),\n markPasteRule({\n find: underscorePasteRegex,\n type: this.type,\n }),\n ]\n },\n})\n", "import { Italic } from './italic.js'\n\nexport * from './italic.js'\n\nexport default Italic\n", "import { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nconst ListItemName = 'listItem'\nconst TextStyleName = 'textStyle'\n\nexport interface BulletListOptions {\n /**\n * The node name for the list items\n * @default 'listItem'\n * @example 'paragraph'\n */\n itemTypeName: string\n\n /**\n * HTML attributes to add to the bullet list element\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n\n /**\n * Keep the marks when splitting the list\n * @default false\n * @example true\n */\n keepMarks: boolean\n\n /**\n * Keep the attributes when splitting the list\n * @default false\n * @example true\n */\n keepAttributes: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n bulletList: {\n /**\n * Toggle a bullet list\n */\n toggleBulletList: () => ReturnType\n }\n }\n}\n\n/**\n * Matches a bullet list to a dash or asterisk.\n */\nexport const bulletListInputRegex = /^\\s*([-+*])\\s$/\n\n/**\n * This extension allows you to create bullet lists.\n * This requires the ListItem extension\n * @see https://tiptap.dev/api/nodes/bullet-list\n * @see https://tiptap.dev/api/nodes/list-item.\n */\nexport const BulletList = Node.create({\n name: 'bulletList',\n\n addOptions() {\n return {\n itemTypeName: 'listItem',\n HTMLAttributes: {},\n keepMarks: false,\n keepAttributes: false,\n }\n },\n\n group: 'block list',\n\n content() {\n return `${this.options.itemTypeName}+`\n },\n\n parseHTML() {\n return [{ tag: 'ul' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['ul', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n markdownTokenName: 'list',\n\n parseMarkdown: (token, helpers) => {\n if (token.type !== 'list' || (token as any).ordered) {\n return []\n }\n\n return {\n type: 'bulletList',\n content: token.items ? helpers.parseChildren(token.items) : [],\n }\n },\n\n renderMarkdown: (node, h) => {\n if (!node.content) {\n return ''\n }\n\n return h.renderChildren(node.content, '\\n')\n },\n\n markdownOptions: {\n indentsContent: true,\n },\n\n addCommands() {\n return {\n toggleBulletList:\n () =>\n ({ commands, chain }) => {\n if (this.options.keepAttributes) {\n return chain()\n .toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n .updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName))\n .run()\n }\n return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-8': () => this.editor.commands.toggleBulletList(),\n }\n },\n\n addInputRules() {\n let inputRule = wrappingInputRule({\n find: bulletListInputRegex,\n type: this.type,\n })\n\n if (this.options.keepMarks || this.options.keepAttributes) {\n inputRule = wrappingInputRule({\n find: bulletListInputRegex,\n type: this.type,\n keepMarks: this.options.keepMarks,\n keepAttributes: this.options.keepAttributes,\n getAttributes: () => {\n return this.editor.getAttributes(TextStyleName)\n },\n editor: this.editor,\n })\n }\n return [inputRule]\n },\n})\n", "import { mergeAttributes, Node, renderNestedMarkdownContent } from '@tiptap/core'\n\nexport interface ListItemOptions {\n /**\n * The HTML attributes for a list item node.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n\n /**\n * The node type for bulletList nodes\n * @default 'bulletList'\n * @example 'myCustomBulletList'\n */\n bulletListTypeName: string\n\n /**\n * The node type for orderedList nodes\n * @default 'orderedList'\n * @example 'myCustomOrderedList'\n */\n orderedListTypeName: string\n}\n\n/**\n * This extension allows you to create list items.\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nexport const ListItem = Node.create({\n name: 'listItem',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n bulletListTypeName: 'bulletList',\n orderedListTypeName: 'orderedList',\n }\n },\n\n content: 'paragraph block*',\n\n defining: true,\n\n parseHTML() {\n return [\n {\n tag: 'li',\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['li', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n markdownTokenName: 'list_item',\n\n parseMarkdown: (token, helpers) => {\n if (token.type !== 'list_item') {\n return []\n }\n\n let content: any[] = []\n\n if (token.tokens && token.tokens.length > 0) {\n // Check if we have paragraph tokens (complex list items)\n const hasParagraphTokens = token.tokens.some(t => t.type === 'paragraph')\n\n if (hasParagraphTokens) {\n // If we have paragraph tokens, parse them as block elements\n content = helpers.parseChildren(token.tokens)\n } else {\n // Check if the first token is a text token with nested inline tokens\n const firstToken = token.tokens[0]\n\n if (firstToken && firstToken.type === 'text' && firstToken.tokens && firstToken.tokens.length > 0) {\n // Parse the inline content from the text token\n const inlineContent = helpers.parseInline(firstToken.tokens)\n\n // Start with the paragraph containing the inline content\n content = [\n {\n type: 'paragraph',\n content: inlineContent,\n },\n ]\n\n // If there are additional tokens after the first text token (like nested lists),\n // parse them as block elements and add them\n if (token.tokens.length > 1) {\n const remainingTokens = token.tokens.slice(1)\n const additionalContent = helpers.parseChildren(remainingTokens)\n content.push(...additionalContent)\n }\n } else {\n // Fallback: parse all tokens as block elements\n content = helpers.parseChildren(token.tokens)\n }\n }\n }\n\n // Ensure we always have at least an empty paragraph\n if (content.length === 0) {\n content = [\n {\n type: 'paragraph',\n content: [],\n },\n ]\n }\n\n return {\n type: 'listItem',\n content,\n }\n },\n\n renderMarkdown: (node, h, ctx) => {\n return renderNestedMarkdownContent(\n node,\n h,\n (context: any) => {\n if (context.parentType === 'bulletList') {\n return '- '\n }\n if (context.parentType === 'orderedList') {\n const start = context.meta?.parentAttrs?.start || 1\n return `${start + context.index}. `\n }\n // Fallback to bullet list for unknown parent types\n return '- '\n },\n ctx,\n )\n },\n\n addKeyboardShortcuts() {\n return {\n Enter: () => this.editor.commands.splitListItem(this.name),\n Tab: () => this.editor.commands.sinkListItem(this.name),\n 'Shift-Tab': () => this.editor.commands.liftListItem(this.name),\n }\n },\n})\n", "import { Extension } from '@tiptap/core'\n\nimport { handleBackspace, handleDelete } from './listHelpers/index.js'\n\nexport type ListKeymapOptions = {\n /**\n * An array of list types. This is used for item and wrapper list matching.\n * @default []\n * @example [{ itemName: 'listItem', wrapperNames: ['bulletList', 'orderedList'] }]\n */\n listTypes: Array<{\n itemName: string\n wrapperNames: string[]\n }>\n}\n\n/**\n * This extension registers custom keymaps to change the behaviour of the backspace and delete keys.\n * By default Prosemirror keyhandling will always lift or sink items so paragraphs are joined into\n * the adjacent or previous list item. This extension will prevent this behaviour and instead will\n * try to join paragraphs from two list items into a single list item.\n * @see https://www.tiptap.dev/api/extensions/list-keymap\n */\nexport const ListKeymap = Extension.create({\n name: 'listKeymap',\n\n addOptions() {\n return {\n listTypes: [\n {\n itemName: 'listItem',\n wrapperNames: ['bulletList', 'orderedList'],\n },\n {\n itemName: 'taskItem',\n wrapperNames: ['taskList'],\n },\n ],\n }\n },\n\n addKeyboardShortcuts() {\n return {\n Delete: ({ editor }) => {\n let handled = false\n\n this.options.listTypes.forEach(({ itemName }) => {\n if (editor.state.schema.nodes[itemName] === undefined) {\n return\n }\n\n if (handleDelete(editor, itemName)) {\n handled = true\n }\n })\n\n return handled\n },\n 'Mod-Delete': ({ editor }) => {\n let handled = false\n\n this.options.listTypes.forEach(({ itemName }) => {\n if (editor.state.schema.nodes[itemName] === undefined) {\n return\n }\n\n if (handleDelete(editor, itemName)) {\n handled = true\n }\n })\n\n return handled\n },\n Backspace: ({ editor }) => {\n let handled = false\n\n this.options.listTypes.forEach(({ itemName, wrapperNames }) => {\n if (editor.state.schema.nodes[itemName] === undefined) {\n return\n }\n\n if (handleBackspace(editor, itemName, wrapperNames)) {\n handled = true\n }\n })\n\n return handled\n },\n 'Mod-Backspace': ({ editor }) => {\n let handled = false\n\n this.options.listTypes.forEach(({ itemName, wrapperNames }) => {\n if (editor.state.schema.nodes[itemName] === undefined) {\n return\n }\n\n if (handleBackspace(editor, itemName, wrapperNames)) {\n handled = true\n }\n })\n\n return handled\n },\n }\n },\n})\n", "export * from './findListItemPos.js'\nexport * from './getNextListDepth.js'\nexport * from './handleBackspace.js'\nexport * from './handleDelete.js'\nexport * from './hasListBefore.js'\nexport * from './hasListItemAfter.js'\nexport * from './hasListItemBefore.js'\nexport * from './listItemHasSubList.js'\nexport * from './nextListIsDeeper.js'\nexport * from './nextListIsHigher.js'\n", "import { getNodeType } from '@tiptap/core'\nimport type { NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nexport const findListItemPos = (typeOrName: string | NodeType, state: EditorState) => {\n const { $from } = state.selection\n const nodeType = getNodeType(typeOrName, state.schema)\n\n let currentNode = null\n let currentDepth = $from.depth\n let currentPos = $from.pos\n let targetDepth: number | null = null\n\n while (currentDepth > 0 && targetDepth === null) {\n currentNode = $from.node(currentDepth)\n\n if (currentNode.type === nodeType) {\n targetDepth = currentDepth\n } else {\n currentDepth -= 1\n currentPos -= 1\n }\n }\n\n if (targetDepth === null) {\n return null\n }\n\n return { $pos: state.doc.resolve(currentPos), depth: targetDepth }\n}\n", "import { getNodeAtPosition } from '@tiptap/core'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { findListItemPos } from './findListItemPos.js'\n\nexport const getNextListDepth = (typeOrName: string, state: EditorState) => {\n const listItemPos = findListItemPos(typeOrName, state)\n\n if (!listItemPos) {\n return false\n }\n\n const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4)\n\n return depth\n}\n", "import type { Editor } from '@tiptap/core'\nimport { isAtStartOfNode, isNodeActive } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\n\nimport { findListItemPos } from './findListItemPos.js'\nimport { hasListBefore } from './hasListBefore.js'\nimport { hasListItemBefore } from './hasListItemBefore.js'\nimport { listItemHasSubList } from './listItemHasSubList.js'\n\nexport const handleBackspace = (editor: Editor, name: string, parentListTypes: string[]) => {\n // this is required to still handle the undo handling\n if (editor.commands.undoInputRule()) {\n return true\n }\n\n // if the selection is not collapsed\n // we can rely on the default backspace behavior\n if (editor.state.selection.from !== editor.state.selection.to) {\n return false\n }\n\n // if the current item is NOT inside a list item &\n // the previous item is a list (orderedList or bulletList)\n // move the cursor into the list and delete the current item\n if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) {\n const { $anchor } = editor.state.selection\n\n const $listPos = editor.state.doc.resolve($anchor.before() - 1)\n\n const listDescendants: Array<{ node: Node; pos: number }> = []\n\n $listPos.node().descendants((node, pos) => {\n if (node.type.name === name) {\n listDescendants.push({ node, pos })\n }\n })\n\n const lastItem = listDescendants.at(-1)\n\n if (!lastItem) {\n return false\n }\n\n const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1)\n\n return editor\n .chain()\n .cut({ from: $anchor.start() - 1, to: $anchor.end() + 1 }, $lastItemPos.end())\n .joinForward()\n .run()\n }\n\n // if the cursor is not inside the current node type\n // do nothing and proceed\n if (!isNodeActive(editor.state, name)) {\n return false\n }\n\n // if the cursor is not at the start of a node\n // do nothing and proceed\n if (!isAtStartOfNode(editor.state)) {\n return false\n }\n\n const listItemPos = findListItemPos(name, editor.state)\n\n if (!listItemPos) {\n return false\n }\n\n const $prev = editor.state.doc.resolve(listItemPos.$pos.pos - 2)\n const prevNode = $prev.node(listItemPos.depth)\n\n const previousListItemHasSubList = listItemHasSubList(name, editor.state, prevNode)\n\n // if the previous item is a list item and doesn't have a sublist, join the list items\n if (hasListItemBefore(name, editor.state) && !previousListItemHasSubList) {\n return editor.commands.joinItemBackward()\n }\n\n // otherwise in the end, a backspace should\n // always just lift the list item if\n // joining / merging is not possible\n return editor.chain().liftListItem(name).run()\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const hasListBefore = (editorState: EditorState, name: string, parentListTypes: string[]) => {\n const { $anchor } = editorState.selection\n\n const previousNodePos = Math.max(0, $anchor.pos - 2)\n\n const previousNode = editorState.doc.resolve(previousNodePos).node()\n\n if (!previousNode || !parentListTypes.includes(previousNode.type.name)) {\n return false\n }\n\n return true\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const hasListItemBefore = (typeOrName: string, state: EditorState): boolean => {\n const { $anchor } = state.selection\n\n const $targetPos = state.doc.resolve($anchor.pos - 2)\n\n if ($targetPos.index() === 0) {\n return false\n }\n\n if ($targetPos.nodeBefore?.type.name !== typeOrName) {\n return false\n }\n\n return true\n}\n", "import { getNodeType } from '@tiptap/core'\nimport type { Node } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nexport const listItemHasSubList = (typeOrName: string, state: EditorState, node?: Node) => {\n if (!node) {\n return false\n }\n\n const nodeType = getNodeType(typeOrName, state.schema)\n\n let hasSubList = false\n\n node.descendants(child => {\n if (child.type === nodeType) {\n hasSubList = true\n }\n })\n\n return hasSubList\n}\n", "import type { Editor } from '@tiptap/core'\nimport { isAtEndOfNode, isNodeActive } from '@tiptap/core'\n\nimport { nextListIsDeeper } from './nextListIsDeeper.js'\nimport { nextListIsHigher } from './nextListIsHigher.js'\n\nexport const handleDelete = (editor: Editor, name: string) => {\n // if the cursor is not inside the current node type\n // do nothing and proceed\n if (!isNodeActive(editor.state, name)) {\n return false\n }\n\n // if the cursor is not at the end of a node\n // do nothing and proceed\n if (!isAtEndOfNode(editor.state, name)) {\n return false\n }\n\n // if the selection is not collapsed, or not within a single node\n // do nothing and proceed\n const { selection } = editor.state\n const { $from, $to } = selection\n\n if (!selection.empty && $from.sameParent($to)) {\n return false\n }\n\n // check if the next node is a list with a deeper depth\n if (nextListIsDeeper(name, editor.state)) {\n return editor\n .chain()\n .focus(editor.state.selection.from + 4)\n .lift(name)\n .joinBackward()\n .run()\n }\n\n if (nextListIsHigher(name, editor.state)) {\n return editor.chain().joinForward().joinBackward().run()\n }\n\n return editor.commands.joinItemForward()\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { findListItemPos } from './findListItemPos.js'\nimport { getNextListDepth } from './getNextListDepth.js'\n\nexport const nextListIsDeeper = (typeOrName: string, state: EditorState) => {\n const listDepth = getNextListDepth(typeOrName, state)\n const listItemPos = findListItemPos(typeOrName, state)\n\n if (!listItemPos || !listDepth) {\n return false\n }\n\n if (listDepth > listItemPos.depth) {\n return true\n }\n\n return false\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { findListItemPos } from './findListItemPos.js'\nimport { getNextListDepth } from './getNextListDepth.js'\n\nexport const nextListIsHigher = (typeOrName: string, state: EditorState) => {\n const listDepth = getNextListDepth(typeOrName, state)\n const listItemPos = findListItemPos(typeOrName, state)\n\n if (!listItemPos || !listDepth) {\n return false\n }\n\n if (listDepth < listItemPos.depth) {\n return true\n }\n\n return false\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const hasListItemAfter = (typeOrName: string, state: EditorState): boolean => {\n const { $anchor } = state.selection\n\n const $targetPos = state.doc.resolve($anchor.pos - $anchor.parentOffset - 2)\n\n if ($targetPos.index() === $targetPos.parent.childCount - 1) {\n return false\n }\n\n if ($targetPos.nodeAfter?.type.name !== typeOrName) {\n return false\n }\n\n return true\n}\n", "import { Extension } from '@tiptap/core'\n\nimport type { BulletListOptions } from '../bullet-list/index.js'\nimport { BulletList } from '../bullet-list/index.js'\nimport type { ListItemOptions } from '../item/index.js'\nimport { ListItem } from '../item/index.js'\nimport type { ListKeymapOptions } from '../keymap/index.js'\nimport { ListKeymap } from '../keymap/index.js'\nimport type { OrderedListOptions } from '../ordered-list/index.js'\nimport { OrderedList } from '../ordered-list/index.js'\nimport type { TaskItemOptions } from '../task-item/index.js'\nimport { TaskItem } from '../task-item/index.js'\nimport type { TaskListOptions } from '../task-list/index.js'\nimport { TaskList } from '../task-list/index.js'\n\nexport interface ListKitOptions {\n /**\n * If set to false, the bulletList extension will not be registered\n * @example table: false\n */\n bulletList: Partial | false\n /**\n * If set to false, the listItem extension will not be registered\n */\n listItem: Partial | false\n /**\n * If set to false, the listKeymap extension will not be registered\n */\n listKeymap: Partial | false\n /**\n * If set to false, the orderedList extension will not be registered\n */\n orderedList: Partial | false\n /**\n * If set to false, the taskItem extension will not be registered\n */\n taskItem: Partial | false\n /**\n * If set to false, the taskList extension will not be registered\n */\n taskList: Partial | false\n}\n\n/**\n * The table kit is a collection of table editor extensions.\n *\n * It’s a good starting point for building your own table in Tiptap.\n */\nexport const ListKit = Extension.create({\n name: 'listKit',\n\n addExtensions() {\n const extensions = []\n\n if (this.options.bulletList !== false) {\n extensions.push(BulletList.configure(this.options.bulletList))\n }\n\n if (this.options.listItem !== false) {\n extensions.push(ListItem.configure(this.options.listItem))\n }\n\n if (this.options.listKeymap !== false) {\n extensions.push(ListKeymap.configure(this.options.listKeymap))\n }\n\n if (this.options.orderedList !== false) {\n extensions.push(OrderedList.configure(this.options.orderedList))\n }\n\n if (this.options.taskItem !== false) {\n extensions.push(TaskItem.configure(this.options.taskItem))\n }\n\n if (this.options.taskList !== false) {\n extensions.push(TaskList.configure(this.options.taskList))\n }\n\n return extensions\n },\n})\n", "import { mergeAttributes, Node, wrappingInputRule } from '@tiptap/core'\n\nimport { buildNestedStructure, collectOrderedListItems, parseListItems } from './utils.js'\n\nconst ListItemName = 'listItem'\nconst TextStyleName = 'textStyle'\n\nexport interface OrderedListOptions {\n /**\n * The node type name for list items.\n * @default 'listItem'\n * @example 'myListItem'\n */\n itemTypeName: string\n\n /**\n * The HTML attributes for an ordered list node.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n\n /**\n * Keep the marks when splitting a list item.\n * @default false\n * @example true\n */\n keepMarks: boolean\n\n /**\n * Keep the attributes when splitting a list item.\n * @default false\n * @example true\n */\n keepAttributes: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n orderedList: {\n /**\n * Toggle an ordered list\n * @example editor.commands.toggleOrderedList()\n */\n toggleOrderedList: () => ReturnType\n }\n }\n}\n\n/**\n * Matches an ordered list to a 1. on input (or any number followed by a dot).\n */\nexport const orderedListInputRegex = /^(\\d+)\\.\\s$/\n\n/**\n * This extension allows you to create ordered lists.\n * This requires the ListItem extension\n * @see https://www.tiptap.dev/api/nodes/ordered-list\n * @see https://www.tiptap.dev/api/nodes/list-item\n */\nexport const OrderedList = Node.create({\n name: 'orderedList',\n\n addOptions() {\n return {\n itemTypeName: 'listItem',\n HTMLAttributes: {},\n keepMarks: false,\n keepAttributes: false,\n }\n },\n\n group: 'block list',\n\n content() {\n return `${this.options.itemTypeName}+`\n },\n\n addAttributes() {\n return {\n start: {\n default: 1,\n parseHTML: element => {\n return element.hasAttribute('start') ? parseInt(element.getAttribute('start') || '', 10) : 1\n },\n },\n type: {\n default: null,\n parseHTML: element => element.getAttribute('type'),\n },\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 'ol',\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n const { start, ...attributesWithoutStart } = HTMLAttributes\n\n return start === 1\n ? ['ol', mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0]\n : ['ol', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n markdownTokenName: 'list',\n\n parseMarkdown: (token, helpers) => {\n if (token.type !== 'list' || !token.ordered) {\n return []\n }\n\n const startValue = token.start || 1\n const content = token.items ? parseListItems(token.items, helpers) : []\n\n if (startValue !== 1) {\n return {\n type: 'orderedList',\n attrs: { start: startValue },\n content,\n }\n }\n\n return {\n type: 'orderedList',\n content,\n }\n },\n\n renderMarkdown: (node, h) => {\n if (!node.content) {\n return ''\n }\n\n return h.renderChildren(node.content, '\\n')\n },\n\n markdownTokenizer: {\n name: 'orderedList',\n level: 'block',\n start: (src: string) => {\n const match = src.match(/^(\\s*)(\\d+)\\.\\s+/)\n const index = match?.index\n return index !== undefined ? index : -1\n },\n tokenize: (src: string, _tokens, lexer) => {\n const lines = src.split('\\n')\n const [listItems, consumed] = collectOrderedListItems(lines)\n\n if (listItems.length === 0) {\n return undefined\n }\n\n const items = buildNestedStructure(listItems, 0, lexer)\n\n if (items.length === 0) {\n return undefined\n }\n\n const startValue = listItems[0]?.number || 1\n\n return {\n type: 'list',\n ordered: true,\n start: startValue,\n items,\n raw: lines.slice(0, consumed).join('\\n'),\n } as unknown as object\n },\n },\n\n markdownOptions: {\n indentsContent: true,\n },\n\n addCommands() {\n return {\n toggleOrderedList:\n () =>\n ({ commands, chain }) => {\n if (this.options.keepAttributes) {\n return chain()\n .toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n .updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName))\n .run()\n }\n return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-7': () => this.editor.commands.toggleOrderedList(),\n }\n },\n\n addInputRules() {\n let inputRule = wrappingInputRule({\n find: orderedListInputRegex,\n type: this.type,\n getAttributes: match => ({ start: +match[1] }),\n joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1],\n })\n\n if (this.options.keepMarks || this.options.keepAttributes) {\n inputRule = wrappingInputRule({\n find: orderedListInputRegex,\n type: this.type,\n keepMarks: this.options.keepMarks,\n keepAttributes: this.options.keepAttributes,\n getAttributes: match => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName) }),\n joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1],\n editor: this.editor,\n })\n }\n return [inputRule]\n },\n})\n", "import type { JSONContent, MarkdownLexerConfiguration, MarkdownParseHelpers, MarkdownToken } from '@tiptap/core'\n\n/**\n * Matches an ordered list item line with optional leading whitespace.\n * Captures: (1) indentation spaces, (2) item number, (3) content after marker\n * Example matches: \"1. Item\", \" 2. Nested item\", \" 3. Deeply nested\"\n */\nconst ORDERED_LIST_ITEM_REGEX = /^(\\s*)(\\d+)\\.\\s+(.*)$/\n\n/**\n * Matches any line that starts with whitespace (indented content).\n * Used to identify continuation content that belongs to a list item.\n */\nconst INDENTED_LINE_REGEX = /^\\s/\n\n/**\n * Represents a parsed ordered list item with indentation information\n */\nexport interface OrderedListItem {\n indent: number\n number: number\n content: string\n raw: string\n}\n\n/**\n * Collects all ordered list items from lines, parsing them into a flat array\n * with indentation information. Stops collecting continuation content when\n * encountering nested list items, allowing them to be processed separately.\n *\n * @param lines - Array of source lines to parse\n * @returns Tuple of [listItems array, number of lines consumed]\n */\nexport function collectOrderedListItems(lines: string[]): [OrderedListItem[], number] {\n const listItems: OrderedListItem[] = []\n let currentLineIndex = 0\n let consumed = 0\n\n while (currentLineIndex < lines.length) {\n const line = lines[currentLineIndex]\n const match = line.match(ORDERED_LIST_ITEM_REGEX)\n\n if (!match) {\n break\n }\n\n const [, indent, number, content] = match\n const indentLevel = indent.length\n let itemContent = content\n let nextLineIndex = currentLineIndex + 1\n const itemLines = [line]\n\n // Collect continuation lines for this item (but NOT nested list items)\n while (nextLineIndex < lines.length) {\n const nextLine = lines[nextLineIndex]\n const nextMatch = nextLine.match(ORDERED_LIST_ITEM_REGEX)\n\n // If it's another list item (nested or not), stop collecting\n if (nextMatch) {\n break\n }\n\n // Check for continuation content (non-list content)\n if (nextLine.trim() === '') {\n // Empty line\n itemLines.push(nextLine)\n itemContent += '\\n'\n nextLineIndex += 1\n } else if (nextLine.match(INDENTED_LINE_REGEX)) {\n // Indented content - part of this item (but not a list item)\n itemLines.push(nextLine)\n itemContent += `\\n${nextLine.slice(indentLevel + 2)}` // Remove list marker indent\n nextLineIndex += 1\n } else {\n // Non-indented line means end of list\n break\n }\n }\n\n listItems.push({\n indent: indentLevel,\n number: parseInt(number, 10),\n content: itemContent.trim(),\n raw: itemLines.join('\\n'),\n })\n\n consumed = nextLineIndex\n currentLineIndex = nextLineIndex\n }\n\n return [listItems, consumed]\n}\n\n/**\n * Recursively builds a nested structure from a flat array of list items\n * based on their indentation levels. Creates proper markdown tokens with\n * nested lists where appropriate.\n *\n * @param items - Flat array of list items with indentation info\n * @param baseIndent - The indentation level to process at this recursion level\n * @param lexer - Markdown lexer for parsing inline and block content\n * @returns Array of list_item tokens with proper nesting\n */\nexport function buildNestedStructure(\n items: OrderedListItem[],\n baseIndent: number,\n lexer: MarkdownLexerConfiguration,\n): unknown[] {\n const result: unknown[] = []\n let currentIndex = 0\n\n while (currentIndex < items.length) {\n const item = items[currentIndex]\n\n if (item.indent === baseIndent) {\n // This item belongs at the current level\n const contentLines = item.content.split('\\n')\n const mainText = contentLines[0]?.trim() || ''\n\n const tokens = []\n\n // Always wrap the main text in a paragraph token\n if (mainText) {\n tokens.push({\n type: 'paragraph',\n raw: mainText,\n tokens: lexer.inlineTokens(mainText),\n })\n }\n\n // Handle additional content after the main text\n const additionalContent = contentLines.slice(1).join('\\n').trim()\n if (additionalContent) {\n // Parse as block tokens (handles mixed unordered lists, etc.)\n const blockTokens = lexer.blockTokens(additionalContent)\n tokens.push(...blockTokens)\n }\n\n // Look ahead to find nested items at deeper indent levels\n let lookAheadIndex = currentIndex + 1\n const nestedItems = []\n\n while (lookAheadIndex < items.length && items[lookAheadIndex].indent > baseIndent) {\n nestedItems.push(items[lookAheadIndex])\n lookAheadIndex += 1\n }\n\n // If we have nested items, recursively build their structure\n if (nestedItems.length > 0) {\n // Find the next indent level (immediate children)\n const nextIndent = Math.min(...nestedItems.map(nestedItem => nestedItem.indent))\n\n // Build the nested list recursively with all nested items\n // The recursive call will handle further nesting\n const nestedListItems = buildNestedStructure(nestedItems, nextIndent, lexer)\n\n // Create a nested list token\n tokens.push({\n type: 'list',\n ordered: true,\n start: nestedItems[0].number,\n items: nestedListItems,\n raw: nestedItems.map(nestedItem => nestedItem.raw).join('\\n'),\n })\n }\n\n result.push({\n type: 'list_item',\n raw: item.raw,\n tokens,\n })\n\n // Skip the nested items we just processed\n currentIndex = lookAheadIndex\n } else {\n // This item has deeper indent than we're currently processing\n // It should be handled by a recursive call\n currentIndex += 1\n }\n }\n\n return result\n}\n\n/**\n * Parses markdown list item tokens into Tiptap JSONContent structure,\n * ensuring text content is properly wrapped in paragraph nodes.\n *\n * @param items - Array of markdown tokens representing list items\n * @param helpers - Markdown parse helpers for recursive parsing\n * @returns Array of listItem JSONContent nodes\n */\nexport function parseListItems(items: MarkdownToken[], helpers: MarkdownParseHelpers): JSONContent[] {\n return items.map(item => {\n if (item.type !== 'list_item') {\n return helpers.parseChildren([item])[0]\n }\n\n // Parse the tokens within the list item\n const content: JSONContent[] = []\n\n if (item.tokens && item.tokens.length > 0) {\n item.tokens.forEach(itemToken => {\n // If it's already a proper block node (paragraph, list, etc.), parse it directly\n if (\n itemToken.type === 'paragraph' ||\n itemToken.type === 'list' ||\n itemToken.type === 'blockquote' ||\n itemToken.type === 'code'\n ) {\n content.push(...helpers.parseChildren([itemToken]))\n } else if (itemToken.type === 'text' && itemToken.tokens) {\n // If it's inline text tokens, wrap them in a paragraph\n const inlineContent = helpers.parseChildren([itemToken])\n content.push({\n type: 'paragraph',\n content: inlineContent,\n })\n } else {\n // For any other content, try to parse it\n const parsed = helpers.parseChildren([itemToken])\n if (parsed.length > 0) {\n content.push(...parsed)\n }\n }\n })\n }\n\n return {\n type: 'listItem',\n content,\n }\n })\n}\n", "import type { KeyboardShortcutCommand } from '@tiptap/core'\nimport {\n getRenderedAttributes,\n mergeAttributes,\n Node,\n renderNestedMarkdownContent,\n wrappingInputRule,\n} from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nexport interface TaskItemOptions {\n /**\n * A callback function that is called when the checkbox is clicked while the editor is in readonly mode.\n * @param node The prosemirror node of the task item\n * @param checked The new checked state\n * @returns boolean\n */\n onReadOnlyChecked?: (node: ProseMirrorNode, checked: boolean) => boolean\n\n /**\n * Controls whether the task items can be nested or not.\n * @default false\n * @example true\n */\n nested: boolean\n\n /**\n * HTML attributes to add to the task item element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n\n /**\n * The node type for taskList nodes\n * @default 'taskList'\n * @example 'myCustomTaskList'\n */\n taskListTypeName: string\n\n /**\n * Accessibility options for the task item.\n * @default {}\n * @example\n * ```js\n * {\n * checkboxLabel: (node) => `Task item: ${node.textContent || 'empty task item'}`\n * }\n */\n a11y?: {\n checkboxLabel?: (node: ProseMirrorNode, checked: boolean) => string\n }\n}\n\n/**\n * Matches a task item to a - [ ] on input.\n */\nexport const inputRegex = /^\\s*(\\[([( |x])?\\])\\s$/\n\n/**\n * This extension allows you to create task items.\n * @see https://www.tiptap.dev/api/nodes/task-item\n */\nexport const TaskItem = Node.create({\n name: 'taskItem',\n\n addOptions() {\n return {\n nested: false,\n HTMLAttributes: {},\n taskListTypeName: 'taskList',\n a11y: undefined,\n }\n },\n\n content() {\n return this.options.nested ? 'paragraph block*' : 'paragraph+'\n },\n\n defining: true,\n\n addAttributes() {\n return {\n checked: {\n default: false,\n keepOnSplit: false,\n parseHTML: element => {\n const dataChecked = element.getAttribute('data-checked')\n\n return dataChecked === '' || dataChecked === 'true'\n },\n renderHTML: attributes => ({\n 'data-checked': attributes.checked,\n }),\n },\n }\n },\n\n parseHTML() {\n return [\n {\n tag: `li[data-type=\"${this.name}\"]`,\n priority: 51,\n },\n ]\n },\n\n renderHTML({ node, HTMLAttributes }) {\n return [\n 'li',\n mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {\n 'data-type': this.name,\n }),\n [\n 'label',\n [\n 'input',\n {\n type: 'checkbox',\n checked: node.attrs.checked ? 'checked' : null,\n },\n ],\n ['span'],\n ],\n ['div', 0],\n ]\n },\n\n parseMarkdown: (token, h) => {\n // Parse the task item's text content into paragraph content\n const content = []\n\n // First, add the main paragraph content\n if (token.tokens && token.tokens.length > 0) {\n // If we have tokens, create a paragraph with the inline content\n content.push(h.createNode('paragraph', {}, h.parseInline(token.tokens)))\n } else if (token.text) {\n // If we have raw text, create a paragraph with text node\n content.push(h.createNode('paragraph', {}, [h.createNode('text', { text: token.text })]))\n } else {\n // Fallback: empty paragraph\n content.push(h.createNode('paragraph', {}, []))\n }\n\n // Then, add any nested content (like nested task lists)\n if (token.nestedTokens && token.nestedTokens.length > 0) {\n const nestedContent = h.parseChildren(token.nestedTokens)\n content.push(...nestedContent)\n }\n\n return h.createNode('taskItem', { checked: token.checked || false }, content)\n },\n\n renderMarkdown: (node, h) => {\n const checkedChar = node.attrs?.checked ? 'x' : ' '\n const prefix = `- [${checkedChar}] `\n\n return renderNestedMarkdownContent(node, h, prefix)\n },\n\n addKeyboardShortcuts() {\n const shortcuts: {\n [key: string]: KeyboardShortcutCommand\n } = {\n Enter: () => this.editor.commands.splitListItem(this.name),\n 'Shift-Tab': () => this.editor.commands.liftListItem(this.name),\n }\n\n if (!this.options.nested) {\n return shortcuts\n }\n\n return {\n ...shortcuts,\n Tab: () => this.editor.commands.sinkListItem(this.name),\n }\n },\n\n addNodeView() {\n return ({ node, HTMLAttributes, getPos, editor }) => {\n const listItem = document.createElement('li')\n const checkboxWrapper = document.createElement('label')\n const checkboxStyler = document.createElement('span')\n const checkbox = document.createElement('input')\n const content = document.createElement('div')\n\n const updateA11Y = (currentNode: ProseMirrorNode) => {\n checkbox.ariaLabel =\n this.options.a11y?.checkboxLabel?.(currentNode, checkbox.checked) ||\n `Task item checkbox for ${currentNode.textContent || 'empty task item'}`\n }\n\n updateA11Y(node)\n\n checkboxWrapper.contentEditable = 'false'\n checkbox.type = 'checkbox'\n checkbox.addEventListener('mousedown', event => event.preventDefault())\n checkbox.addEventListener('change', event => {\n // if the editor isn’t editable and we don't have a handler for\n // readonly checks we have to undo the latest change\n if (!editor.isEditable && !this.options.onReadOnlyChecked) {\n checkbox.checked = !checkbox.checked\n\n return\n }\n\n const { checked } = event.target as any\n\n if (editor.isEditable && typeof getPos === 'function') {\n editor\n .chain()\n .focus(undefined, { scrollIntoView: false })\n .command(({ tr }) => {\n const position = getPos()\n\n if (typeof position !== 'number') {\n return false\n }\n const currentNode = tr.doc.nodeAt(position)\n\n tr.setNodeMarkup(position, undefined, {\n ...currentNode?.attrs,\n checked,\n })\n\n return true\n })\n .run()\n }\n if (!editor.isEditable && this.options.onReadOnlyChecked) {\n // Reset state if onReadOnlyChecked returns false\n if (!this.options.onReadOnlyChecked(node, checked)) {\n checkbox.checked = !checkbox.checked\n }\n }\n })\n\n Object.entries(this.options.HTMLAttributes).forEach(([key, value]) => {\n listItem.setAttribute(key, value)\n })\n\n listItem.dataset.checked = node.attrs.checked\n checkbox.checked = node.attrs.checked\n\n checkboxWrapper.append(checkbox, checkboxStyler)\n listItem.append(checkboxWrapper, content)\n\n Object.entries(HTMLAttributes).forEach(([key, value]) => {\n listItem.setAttribute(key, value)\n })\n\n // Track the keys of previously rendered HTML attributes for proper removal\n let prevRenderedAttributeKeys = new Set(Object.keys(HTMLAttributes))\n\n return {\n dom: listItem,\n contentDOM: content,\n update: updatedNode => {\n if (updatedNode.type !== this.type) {\n return false\n }\n\n listItem.dataset.checked = updatedNode.attrs.checked\n checkbox.checked = updatedNode.attrs.checked\n updateA11Y(updatedNode)\n\n // Sync all HTML attributes from the updated node\n const extensionAttributes = editor.extensionManager.attributes\n const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes)\n const newKeys = new Set(Object.keys(newHTMLAttributes))\n\n // Remove attributes that were previously rendered but are no longer present\n // If the attribute exists in static options, restore it instead of removing\n const staticAttrs = this.options.HTMLAttributes\n\n prevRenderedAttributeKeys.forEach(key => {\n if (!newKeys.has(key)) {\n if (key in staticAttrs) {\n listItem.setAttribute(key, staticAttrs[key])\n } else {\n listItem.removeAttribute(key)\n }\n }\n })\n\n // Update or add new attributes\n Object.entries(newHTMLAttributes).forEach(([key, value]) => {\n if (value === null || value === undefined) {\n // If the attribute exists in static options, restore it instead of removing\n if (key in staticAttrs) {\n listItem.setAttribute(key, staticAttrs[key])\n } else {\n listItem.removeAttribute(key)\n }\n } else {\n listItem.setAttribute(key, value)\n }\n })\n\n // Update the tracked keys for next update\n prevRenderedAttributeKeys = newKeys\n\n return true\n },\n }\n }\n },\n\n addInputRules() {\n return [\n wrappingInputRule({\n find: inputRegex,\n type: this.type,\n getAttributes: match => ({\n checked: match[match.length - 1] === 'x',\n }),\n }),\n ]\n },\n})\n", "import { mergeAttributes, Node, parseIndentedBlocks } from '@tiptap/core'\n\nexport interface TaskListOptions {\n /**\n * The node type name for a task item.\n * @default 'taskItem'\n * @example 'myCustomTaskItem'\n */\n itemTypeName: string\n\n /**\n * The HTML attributes for a task list node.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n taskList: {\n /**\n * Toggle a task list\n * @example editor.commands.toggleTaskList()\n */\n toggleTaskList: () => ReturnType\n }\n }\n}\n\n/**\n * This extension allows you to create task lists.\n * @see https://www.tiptap.dev/api/nodes/task-list\n */\nexport const TaskList = Node.create({\n name: 'taskList',\n\n addOptions() {\n return {\n itemTypeName: 'taskItem',\n HTMLAttributes: {},\n }\n },\n\n group: 'block list',\n\n content() {\n return `${this.options.itemTypeName}+`\n },\n\n parseHTML() {\n return [\n {\n tag: `ul[data-type=\"${this.name}\"]`,\n priority: 51,\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['ul', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { 'data-type': this.name }), 0]\n },\n\n parseMarkdown: (token, h) => {\n return h.createNode('taskList', {}, h.parseChildren(token.items || []))\n },\n\n renderMarkdown: (node, h) => {\n if (!node.content) {\n return ''\n }\n\n return h.renderChildren(node.content, '\\n')\n },\n\n markdownTokenizer: {\n name: 'taskList',\n level: 'block',\n start(src) {\n // Look for the start of a task list item\n const index = src.match(/^\\s*[-+*]\\s+\\[([ xX])\\]\\s+/)?.index\n return index !== undefined ? index : -1\n },\n tokenize(src, tokens, lexer) {\n // Helper function to recursively parse task lists\n const parseTaskListContent = (content: string): any[] | undefined => {\n const nestedResult = parseIndentedBlocks(\n content,\n {\n itemPattern: /^(\\s*)([-+*])\\s+\\[([ xX])\\]\\s+(.*)$/,\n extractItemData: match => ({\n indentLevel: match[1].length,\n mainContent: match[4],\n checked: match[3].toLowerCase() === 'x',\n }),\n createToken: (data, nestedTokens) => ({\n type: 'taskItem',\n raw: '',\n mainContent: data.mainContent,\n indentLevel: data.indentLevel,\n checked: data.checked,\n text: data.mainContent,\n tokens: lexer.inlineTokens(data.mainContent),\n nestedTokens,\n }),\n // Allow recursive nesting\n customNestedParser: parseTaskListContent,\n },\n lexer,\n )\n\n if (nestedResult) {\n // Return as task list token\n return [\n {\n type: 'taskList',\n raw: nestedResult.raw,\n items: nestedResult.items,\n },\n ]\n }\n\n // Fall back to regular markdown parsing if not a task list\n return lexer.blockTokens(content)\n }\n\n const result = parseIndentedBlocks(\n src,\n {\n itemPattern: /^(\\s*)([-+*])\\s+\\[([ xX])\\]\\s+(.*)$/,\n extractItemData: match => ({\n indentLevel: match[1].length,\n mainContent: match[4],\n checked: match[3].toLowerCase() === 'x',\n }),\n createToken: (data, nestedTokens) => ({\n type: 'taskItem',\n raw: '',\n mainContent: data.mainContent,\n indentLevel: data.indentLevel,\n checked: data.checked,\n text: data.mainContent,\n tokens: lexer.inlineTokens(data.mainContent),\n nestedTokens,\n }),\n // Use the recursive parser for nested content\n customNestedParser: parseTaskListContent,\n },\n lexer,\n )\n\n if (!result) {\n return undefined\n }\n\n return {\n type: 'taskList',\n raw: result.raw,\n items: result.items,\n }\n },\n },\n\n markdownOptions: {\n indentsContent: true,\n },\n\n addCommands() {\n return {\n toggleTaskList:\n () =>\n ({ commands }) => {\n return commands.toggleList(this.name, this.options.itemTypeName)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-9': () => this.editor.commands.toggleTaskList(),\n }\n },\n})\n", "import { mergeAttributes, Node } from '@tiptap/core'\n\nexport interface ParagraphOptions {\n /**\n * The HTML attributes for a paragraph node.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n paragraph: {\n /**\n * Toggle a paragraph\n * @example editor.commands.toggleParagraph()\n */\n setParagraph: () => ReturnType\n }\n }\n}\n\n/**\n * Markdown marker for empty paragraphs to preserve blank lines.\n * Using   (non-breaking space HTML entity) ensures the paragraph\n * is not collapsed by markdown parsers while remaining human-readable.\n */\nconst EMPTY_PARAGRAPH_MARKDOWN = ' '\n\n/**\n * Unicode character for non-breaking space (U+00A0).\n * Some markdown parsers may convert   entities to this literal character.\n */\nconst NBSP_CHAR = '\\u00A0'\n\n/**\n * This extension allows you to create paragraphs.\n * @see https://www.tiptap.dev/api/nodes/paragraph\n */\nexport const Paragraph = Node.create({\n name: 'paragraph',\n\n priority: 1000,\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n group: 'block',\n\n content: 'inline*',\n\n parseHTML() {\n return [{ tag: 'p' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['p', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n parseMarkdown: (token, helpers) => {\n const tokens = token.tokens || []\n\n // Special case: if paragraph contains only a single image token,\n // unwrap it to avoid nesting block elements incorrectly\n if (tokens.length === 1 && tokens[0].type === 'image') {\n // Parse the image token directly as a block element\n return helpers.parseChildren([tokens[0]])\n }\n\n // Parse the inline tokens\n const content = helpers.parseInline(tokens)\n\n // Special case: if paragraph contains only   (non-breaking space),\n // treat it as an empty paragraph to preserve blank lines\n if (\n content.length === 1 &&\n content[0].type === 'text' &&\n (content[0].text === EMPTY_PARAGRAPH_MARKDOWN || content[0].text === NBSP_CHAR)\n ) {\n return helpers.createNode('paragraph', undefined, [])\n }\n\n // Convert 'paragraph' token to paragraph node\n return helpers.createNode('paragraph', undefined, content)\n },\n\n renderMarkdown: (node, h) => {\n if (!node) {\n return ''\n }\n\n // Normalize content: treat undefined/null as empty array\n const content = Array.isArray(node.content) ? node.content : []\n\n // If the paragraph is empty, render a non-breaking space to preserve blank lines\n if (content.length === 0) {\n return EMPTY_PARAGRAPH_MARKDOWN\n }\n\n return h.renderChildren(content)\n },\n\n addCommands() {\n return {\n setParagraph:\n () =>\n ({ commands }) => {\n return commands.setNode(this.name)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Alt-0': () => this.editor.commands.setParagraph(),\n }\n },\n})\n", "import { Paragraph } from './paragraph.js'\n\nexport * from './paragraph.js'\n\nexport default Paragraph\n", "import { Mark, markInputRule, markPasteRule, mergeAttributes } from '@tiptap/core'\n\nexport interface StrikeOptions {\n /**\n * HTML attributes to add to the strike element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n strike: {\n /**\n * Set a strike mark\n * @example editor.commands.setStrike()\n */\n setStrike: () => ReturnType\n /**\n * Toggle a strike mark\n * @example editor.commands.toggleStrike()\n */\n toggleStrike: () => ReturnType\n /**\n * Unset a strike mark\n * @example editor.commands.unsetStrike()\n */\n unsetStrike: () => ReturnType\n }\n }\n}\n\n/**\n * Matches a strike to a ~~strike~~ on input.\n */\nexport const inputRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))$/\n\n/**\n * Matches a strike to a ~~strike~~ on paste.\n */\nexport const pasteRegex = /(?:^|\\s)(~~(?!\\s+~~)((?:[^~]+))~~(?!\\s+~~))/g\n\n/**\n * This extension allows you to create strike text.\n * @see https://www.tiptap.dev/api/marks/strike\n */\nexport const Strike = Mark.create({\n name: 'strike',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 's',\n },\n {\n tag: 'del',\n },\n {\n tag: 'strike',\n },\n {\n style: 'text-decoration',\n consuming: false,\n getAttrs: style => ((style as string).includes('line-through') ? {} : false),\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['s', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n markdownTokenName: 'del',\n\n parseMarkdown: (token, helpers) => {\n // Convert 'del' token to strike mark\n return helpers.applyMark('strike', helpers.parseInline(token.tokens || []))\n },\n\n renderMarkdown: (node, h) => {\n return `~~${h.renderChildren(node)}~~`\n },\n\n addCommands() {\n return {\n setStrike:\n () =>\n ({ commands }) => {\n return commands.setMark(this.name)\n },\n toggleStrike:\n () =>\n ({ commands }) => {\n return commands.toggleMark(this.name)\n },\n unsetStrike:\n () =>\n ({ commands }) => {\n return commands.unsetMark(this.name)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Shift-s': () => this.editor.commands.toggleStrike(),\n }\n },\n\n addInputRules() {\n return [\n markInputRule({\n find: inputRegex,\n type: this.type,\n }),\n ]\n },\n\n addPasteRules() {\n return [\n markPasteRule({\n find: pasteRegex,\n type: this.type,\n }),\n ]\n },\n})\n", "import { Strike } from './strike.js'\n\nexport * from './strike.js'\n\nexport default Strike\n", "import { Node } from '@tiptap/core'\n\n/**\n * This extension allows you to create text nodes.\n * @see https://www.tiptap.dev/api/nodes/text\n */\nexport const Text = Node.create({\n name: 'text',\n group: 'inline',\n\n parseMarkdown: token => {\n // Convert 'text' token to text node - text nodes are special as they store text directly\n return {\n type: 'text',\n text: token.text || '',\n }\n },\n\n renderMarkdown: node => node.text || '',\n})\n", "import { Text } from './text.js'\n\nexport * from './text.js'\n\nexport default Text\n", "import { Mark, mergeAttributes } from '@tiptap/core'\n\nexport interface UnderlineOptions {\n /**\n * HTML attributes to add to the underline element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n underline: {\n /**\n * Set an underline mark\n * @example editor.commands.setUnderline()\n */\n setUnderline: () => ReturnType\n /**\n * Toggle an underline mark\n * @example editor.commands.toggleUnderline()\n */\n toggleUnderline: () => ReturnType\n /**\n * Unset an underline mark\n * @example editor.commands.unsetUnderline()\n */\n unsetUnderline: () => ReturnType\n }\n }\n}\n\n/**\n * This extension allows you to create underline text.\n * @see https://www.tiptap.dev/api/marks/underline\n */\nexport const Underline = Mark.create({\n name: 'underline',\n\n addOptions() {\n return {\n HTMLAttributes: {},\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 'u',\n },\n {\n style: 'text-decoration',\n consuming: false,\n getAttrs: style => ((style as string).includes('underline') ? {} : false),\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['u', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n parseMarkdown(token, helpers) {\n return helpers.applyMark(this.name || 'underline', helpers.parseInline(token.tokens || []))\n },\n\n renderMarkdown(node, helpers) {\n return `++${helpers.renderChildren(node)}++`\n },\n\n markdownTokenizer: {\n name: 'underline',\n level: 'inline',\n start(src) {\n return src.indexOf('++')\n },\n tokenize(src, _tokens, lexer) {\n const rule = /^(\\+\\+)([\\s\\S]+?)(\\+\\+)/\n const match = rule.exec(src)\n\n if (!match) {\n return undefined\n }\n\n const innerContent = match[2].trim()\n\n return {\n type: 'underline',\n raw: match[0],\n text: innerContent,\n tokens: lexer.inlineTokens(innerContent),\n }\n },\n },\n\n addCommands() {\n return {\n setUnderline:\n () =>\n ({ commands }) => {\n return commands.setMark(this.name)\n },\n toggleUnderline:\n () =>\n ({ commands }) => {\n return commands.toggleMark(this.name)\n },\n unsetUnderline:\n () =>\n ({ commands }) => {\n return commands.unsetMark(this.name)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-u': () => this.editor.commands.toggleUnderline(),\n 'Mod-U': () => this.editor.commands.toggleUnderline(),\n }\n },\n})\n", "import { Underline } from './underline.js'\n\nexport * from './underline.js'\n\nexport default Underline\n", "import { Plugin } from 'prosemirror-state';\nimport { dropPoint } from 'prosemirror-transform';\n\n/**\nCreate a plugin that, when added to a ProseMirror instance,\ncauses a decoration to show up at the drop position when something\nis dragged over the editor.\n\nNodes may add a `disableDropCursor` property to their spec to\ncontrol the showing of a drop cursor inside them. This may be a\nboolean or a function, which will be called with a view and a\nposition, and should return a boolean.\n*/\nfunction dropCursor(options = {}) {\n return new Plugin({\n view(editorView) { return new DropCursorView(editorView, options); }\n });\n}\nclass DropCursorView {\n constructor(editorView, options) {\n var _a;\n this.editorView = editorView;\n this.cursorPos = null;\n this.element = null;\n this.timeout = -1;\n this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1;\n this.color = options.color === false ? undefined : (options.color || \"black\");\n this.class = options.class;\n this.handlers = [\"dragover\", \"dragend\", \"drop\", \"dragleave\"].map(name => {\n let handler = (e) => { this[name](e); };\n editorView.dom.addEventListener(name, handler);\n return { name, handler };\n });\n }\n destroy() {\n this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));\n }\n update(editorView, prevState) {\n if (this.cursorPos != null && prevState.doc != editorView.state.doc) {\n if (this.cursorPos > editorView.state.doc.content.size)\n this.setCursor(null);\n else\n this.updateOverlay();\n }\n }\n setCursor(pos) {\n if (pos == this.cursorPos)\n return;\n this.cursorPos = pos;\n if (pos == null) {\n this.element.parentNode.removeChild(this.element);\n this.element = null;\n }\n else {\n this.updateOverlay();\n }\n }\n updateOverlay() {\n let $pos = this.editorView.state.doc.resolve(this.cursorPos);\n let isBlock = !$pos.parent.inlineContent, rect;\n let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect();\n let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight;\n if (isBlock) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter;\n if (before || after) {\n let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));\n if (node) {\n let nodeRect = node.getBoundingClientRect();\n let top = before ? nodeRect.bottom : nodeRect.top;\n if (before && after)\n top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;\n let halfWidth = (this.width / 2) * scaleY;\n rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth };\n }\n }\n }\n if (!rect) {\n let coords = this.editorView.coordsAtPos(this.cursorPos);\n let halfWidth = (this.width / 2) * scaleX;\n rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom };\n }\n let parent = this.editorView.dom.offsetParent;\n if (!this.element) {\n this.element = parent.appendChild(document.createElement(\"div\"));\n if (this.class)\n this.element.className = this.class;\n this.element.style.cssText = \"position: absolute; z-index: 50; pointer-events: none;\";\n if (this.color) {\n this.element.style.backgroundColor = this.color;\n }\n }\n this.element.classList.toggle(\"prosemirror-dropcursor-block\", isBlock);\n this.element.classList.toggle(\"prosemirror-dropcursor-inline\", !isBlock);\n let parentLeft, parentTop;\n if (!parent || parent == document.body && getComputedStyle(parent).position == \"static\") {\n parentLeft = -pageXOffset;\n parentTop = -pageYOffset;\n }\n else {\n let rect = parent.getBoundingClientRect();\n let parentScaleX = rect.width / parent.offsetWidth, parentScaleY = rect.height / parent.offsetHeight;\n parentLeft = rect.left - parent.scrollLeft * parentScaleX;\n parentTop = rect.top - parent.scrollTop * parentScaleY;\n }\n this.element.style.left = (rect.left - parentLeft) / scaleX + \"px\";\n this.element.style.top = (rect.top - parentTop) / scaleY + \"px\";\n this.element.style.width = (rect.right - rect.left) / scaleX + \"px\";\n this.element.style.height = (rect.bottom - rect.top) / scaleY + \"px\";\n }\n scheduleRemoval(timeout) {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(() => this.setCursor(null), timeout);\n }\n dragover(event) {\n if (!this.editorView.editable)\n return;\n let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });\n let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);\n let disableDropCursor = node && node.type.spec.disableDropCursor;\n let disabled = typeof disableDropCursor == \"function\"\n ? disableDropCursor(this.editorView, pos, event)\n : disableDropCursor;\n if (pos && !disabled) {\n let target = pos.pos;\n if (this.editorView.dragging && this.editorView.dragging.slice) {\n let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);\n if (point != null)\n target = point;\n }\n this.setCursor(target);\n this.scheduleRemoval(5000);\n }\n }\n dragend() {\n this.scheduleRemoval(20);\n }\n drop() {\n this.scheduleRemoval(20);\n }\n dragleave(event) {\n if (!this.editorView.dom.contains(event.relatedTarget))\n this.setCursor(null);\n }\n}\n\nexport { dropCursor };\n", "import { keydownHandler } from 'prosemirror-keymap';\nimport { Selection, NodeSelection, TextSelection, Plugin } from 'prosemirror-state';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { DecorationSet, Decoration } from 'prosemirror-view';\n\n/**\nGap cursor selections are represented using this class. Its\n`$anchor` and `$head` properties both point at the cursor position.\n*/\nclass GapCursor extends Selection {\n /**\n Create a gap cursor.\n */\n constructor($pos) {\n super($pos, $pos);\n }\n map(doc, mapping) {\n let $pos = doc.resolve(mapping.map(this.head));\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n }\n content() { return Slice.empty; }\n eq(other) {\n return other instanceof GapCursor && other.head == this.head;\n }\n toJSON() {\n return { type: \"gapcursor\", pos: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for GapCursor.fromJSON\");\n return new GapCursor(doc.resolve(json.pos));\n }\n /**\n @internal\n */\n getBookmark() { return new GapBookmark(this.anchor); }\n /**\n @internal\n */\n static valid($pos) {\n let parent = $pos.parent;\n if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos))\n return false;\n let override = parent.type.spec.allowGapCursor;\n if (override != null)\n return override;\n let deflt = parent.contentMatchAt($pos.index()).defaultType;\n return deflt && deflt.isTextblock;\n }\n /**\n @internal\n */\n static findGapCursorFrom($pos, dir, mustMove = false) {\n search: for (;;) {\n if (!mustMove && GapCursor.valid($pos))\n return $pos;\n let pos = $pos.pos, next = null;\n // Scan up from this position\n for (let d = $pos.depth;; d--) {\n let parent = $pos.node(d);\n if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {\n next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);\n break;\n }\n else if (d == 0) {\n return null;\n }\n pos += dir;\n let $cur = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur))\n return $cur;\n }\n // And then down into the next node\n for (;;) {\n let inside = dir > 0 ? next.firstChild : next.lastChild;\n if (!inside) {\n if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {\n $pos = $pos.doc.resolve(pos + next.nodeSize * dir);\n mustMove = false;\n continue search;\n }\n break;\n }\n next = inside;\n pos += dir;\n let $cur = $pos.doc.resolve(pos);\n if (GapCursor.valid($cur))\n return $cur;\n }\n return null;\n }\n }\n}\nGapCursor.prototype.visible = false;\nGapCursor.findFrom = GapCursor.findGapCursorFrom;\nSelection.jsonID(\"gapcursor\", GapCursor);\nclass GapBookmark {\n constructor(pos) {\n this.pos = pos;\n }\n map(mapping) {\n return new GapBookmark(mapping.map(this.pos));\n }\n resolve(doc) {\n let $pos = doc.resolve(this.pos);\n return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);\n }\n}\nfunction needsGap(type) {\n return type.isAtom || type.spec.isolating || type.spec.createGapCursor;\n}\nfunction closedBefore($pos) {\n for (let d = $pos.depth; d >= 0; d--) {\n let index = $pos.index(d), parent = $pos.node(d);\n // At the start of this parent, look at next one\n if (index == 0) {\n if (parent.type.spec.isolating)\n return true;\n continue;\n }\n // See if the node before (or its first ancestor) is closed\n for (let before = parent.child(index - 1);; before = before.lastChild) {\n if ((before.childCount == 0 && !before.inlineContent) || needsGap(before.type))\n return true;\n if (before.inlineContent)\n return false;\n }\n }\n // Hit start of document\n return true;\n}\nfunction closedAfter($pos) {\n for (let d = $pos.depth; d >= 0; d--) {\n let index = $pos.indexAfter(d), parent = $pos.node(d);\n if (index == parent.childCount) {\n if (parent.type.spec.isolating)\n return true;\n continue;\n }\n for (let after = parent.child(index);; after = after.firstChild) {\n if ((after.childCount == 0 && !after.inlineContent) || needsGap(after.type))\n return true;\n if (after.inlineContent)\n return false;\n }\n }\n return true;\n}\n\n/**\nCreate a gap cursor plugin. When enabled, this will capture clicks\nnear and arrow-key-motion past places that don't have a normally\nselectable position nearby, and create a gap cursor selection for\nthem. The cursor is drawn as an element with class\n`ProseMirror-gapcursor`. You can either include\n`style/gapcursor.css` from the package's directory or add your own\nstyles to make it visible.\n*/\nfunction gapCursor() {\n return new Plugin({\n props: {\n decorations: drawGapCursor,\n createSelectionBetween(_view, $anchor, $head) {\n return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;\n },\n handleClick,\n handleKeyDown,\n handleDOMEvents: { beforeinput: beforeinput }\n }\n });\n}\nconst handleKeyDown = keydownHandler({\n \"ArrowLeft\": arrow(\"horiz\", -1),\n \"ArrowRight\": arrow(\"horiz\", 1),\n \"ArrowUp\": arrow(\"vert\", -1),\n \"ArrowDown\": arrow(\"vert\", 1)\n});\nfunction arrow(axis, dir) {\n const dirStr = axis == \"vert\" ? (dir > 0 ? \"down\" : \"up\") : (dir > 0 ? \"right\" : \"left\");\n return function (state, dispatch, view) {\n let sel = state.selection;\n let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;\n if (sel instanceof TextSelection) {\n if (!view.endOfTextblock(dirStr) || $start.depth == 0)\n return false;\n mustMove = false;\n $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());\n }\n let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);\n if (!$found)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(new GapCursor($found)));\n return true;\n };\n}\nfunction handleClick(view, pos, event) {\n if (!view || !view.editable)\n return false;\n let $pos = view.state.doc.resolve(pos);\n if (!GapCursor.valid($pos))\n return false;\n let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });\n if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))\n return false;\n view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));\n return true;\n}\n// This is a hack that, when a composition starts while a gap cursor\n// is active, quickly creates an inline context for the composition to\n// happen in, to avoid it being aborted by the DOM selection being\n// moved into a valid position.\nfunction beforeinput(view, event) {\n if (event.inputType != \"insertCompositionText\" || !(view.state.selection instanceof GapCursor))\n return false;\n let { $from } = view.state.selection;\n let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);\n if (!insert)\n return false;\n let frag = Fragment.empty;\n for (let i = insert.length - 1; i >= 0; i--)\n frag = Fragment.from(insert[i].createAndFill(null, frag));\n let tr = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));\n tr.setSelection(TextSelection.near(tr.doc.resolve($from.pos + 1)));\n view.dispatch(tr);\n return false;\n}\nfunction drawGapCursor(state) {\n if (!(state.selection instanceof GapCursor))\n return null;\n let node = document.createElement(\"div\");\n node.className = \"ProseMirror-gapcursor\";\n return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: \"gapcursor\" })]);\n}\n\nexport { GapCursor, gapCursor };\n", "var GOOD_LEAF_SIZE = 200;\n\n// :: class A rope sequence is a persistent sequence data structure\n// that supports appending, prepending, and slicing without doing a\n// full copy. It is represented as a mostly-balanced tree.\nvar RopeSequence = function RopeSequence () {};\n\nRopeSequence.prototype.append = function append (other) {\n if (!other.length) { return this }\n other = RopeSequence.from(other);\n\n return (!this.length && other) ||\n (other.length < GOOD_LEAF_SIZE && this.leafAppend(other)) ||\n (this.length < GOOD_LEAF_SIZE && other.leafPrepend(this)) ||\n this.appendInner(other)\n};\n\n// :: (union<[T], RopeSequence>) → RopeSequence\n// Prepend an array or other rope to this one, returning a new rope.\nRopeSequence.prototype.prepend = function prepend (other) {\n if (!other.length) { return this }\n return RopeSequence.from(other).append(this)\n};\n\nRopeSequence.prototype.appendInner = function appendInner (other) {\n return new Append(this, other)\n};\n\n// :: (?number, ?number) → RopeSequence\n// Create a rope repesenting a sub-sequence of this rope.\nRopeSequence.prototype.slice = function slice (from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from >= to) { return RopeSequence.empty }\n return this.sliceInner(Math.max(0, from), Math.min(this.length, to))\n};\n\n// :: (number) → T\n// Retrieve the element at the given position from this rope.\nRopeSequence.prototype.get = function get (i) {\n if (i < 0 || i >= this.length) { return undefined }\n return this.getInner(i)\n};\n\n// :: ((element: T, index: number) → ?bool, ?number, ?number)\n// Call the given function for each element between the given\n// indices. This tends to be more efficient than looping over the\n// indices and calling `get`, because it doesn't have to descend the\n// tree for every element.\nRopeSequence.prototype.forEach = function forEach (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n if (from <= to)\n { this.forEachInner(f, from, to, 0); }\n else\n { this.forEachInvertedInner(f, from, to, 0); }\n};\n\n// :: ((element: T, index: number) → U, ?number, ?number) → [U]\n// Map the given functions over the elements of the rope, producing\n// a flat array.\nRopeSequence.prototype.map = function map (f, from, to) {\n if ( from === void 0 ) from = 0;\n if ( to === void 0 ) to = this.length;\n\n var result = [];\n this.forEach(function (elt, i) { return result.push(f(elt, i)); }, from, to);\n return result\n};\n\n// :: (?union<[T], RopeSequence>) → RopeSequence\n// Create a rope representing the given array, or return the rope\n// itself if a rope was given.\nRopeSequence.from = function from (values) {\n if (values instanceof RopeSequence) { return values }\n return values && values.length ? new Leaf(values) : RopeSequence.empty\n};\n\nvar Leaf = /*@__PURE__*/(function (RopeSequence) {\n function Leaf(values) {\n RopeSequence.call(this);\n this.values = values;\n }\n\n if ( RopeSequence ) Leaf.__proto__ = RopeSequence;\n Leaf.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Leaf.prototype.constructor = Leaf;\n\n var prototypeAccessors = { length: { configurable: true },depth: { configurable: true } };\n\n Leaf.prototype.flatten = function flatten () {\n return this.values\n };\n\n Leaf.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n return new Leaf(this.values.slice(from, to))\n };\n\n Leaf.prototype.getInner = function getInner (i) {\n return this.values[i]\n };\n\n Leaf.prototype.forEachInner = function forEachInner (f, from, to, start) {\n for (var i = from; i < to; i++)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n for (var i = from - 1; i >= to; i--)\n { if (f(this.values[i], start + i) === false) { return false } }\n };\n\n Leaf.prototype.leafAppend = function leafAppend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(this.values.concat(other.flatten())) }\n };\n\n Leaf.prototype.leafPrepend = function leafPrepend (other) {\n if (this.length + other.length <= GOOD_LEAF_SIZE)\n { return new Leaf(other.flatten().concat(this.values)) }\n };\n\n prototypeAccessors.length.get = function () { return this.values.length };\n\n prototypeAccessors.depth.get = function () { return 0 };\n\n Object.defineProperties( Leaf.prototype, prototypeAccessors );\n\n return Leaf;\n}(RopeSequence));\n\n// :: RopeSequence\n// The empty rope sequence.\nRopeSequence.empty = new Leaf([]);\n\nvar Append = /*@__PURE__*/(function (RopeSequence) {\n function Append(left, right) {\n RopeSequence.call(this);\n this.left = left;\n this.right = right;\n this.length = left.length + right.length;\n this.depth = Math.max(left.depth, right.depth) + 1;\n }\n\n if ( RopeSequence ) Append.__proto__ = RopeSequence;\n Append.prototype = Object.create( RopeSequence && RopeSequence.prototype );\n Append.prototype.constructor = Append;\n\n Append.prototype.flatten = function flatten () {\n return this.left.flatten().concat(this.right.flatten())\n };\n\n Append.prototype.getInner = function getInner (i) {\n return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length)\n };\n\n Append.prototype.forEachInner = function forEachInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from < leftLen &&\n this.left.forEachInner(f, from, Math.min(to, leftLen), start) === false)\n { return false }\n if (to > leftLen &&\n this.right.forEachInner(f, Math.max(from - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false)\n { return false }\n };\n\n Append.prototype.forEachInvertedInner = function forEachInvertedInner (f, from, to, start) {\n var leftLen = this.left.length;\n if (from > leftLen &&\n this.right.forEachInvertedInner(f, from - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false)\n { return false }\n if (to < leftLen &&\n this.left.forEachInvertedInner(f, Math.min(from, leftLen), to, start) === false)\n { return false }\n };\n\n Append.prototype.sliceInner = function sliceInner (from, to) {\n if (from == 0 && to == this.length) { return this }\n var leftLen = this.left.length;\n if (to <= leftLen) { return this.left.slice(from, to) }\n if (from >= leftLen) { return this.right.slice(from - leftLen, to - leftLen) }\n return this.left.slice(from, leftLen).append(this.right.slice(0, to - leftLen))\n };\n\n Append.prototype.leafAppend = function leafAppend (other) {\n var inner = this.right.leafAppend(other);\n if (inner) { return new Append(this.left, inner) }\n };\n\n Append.prototype.leafPrepend = function leafPrepend (other) {\n var inner = this.left.leafPrepend(other);\n if (inner) { return new Append(inner, this.right) }\n };\n\n Append.prototype.appendInner = function appendInner (other) {\n if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1)\n { return new Append(this.left, new Append(this.right, other)) }\n return new Append(this, other)\n };\n\n return Append;\n}(RopeSequence));\n\nexport default RopeSequence;\n", "import RopeSequence from 'rope-sequence';\nimport { Mapping } from 'prosemirror-transform';\nimport { PluginKey, Plugin } from 'prosemirror-state';\n\n// ProseMirror's history isn't simply a way to roll back to a previous\n// state, because ProseMirror supports applying changes without adding\n// them to the history (for example during collaboration).\n//\n// To this end, each 'Branch' (one for the undo history and one for\n// the redo history) keeps an array of 'Items', which can optionally\n// hold a step (an actual undoable change), and always hold a position\n// map (which is needed to move changes below them to apply to the\n// current document).\n//\n// An item that has both a step and a selection bookmark is the start\n// of an 'event' — a group of changes that will be undone or redone at\n// once. (It stores only the bookmark, since that way we don't have to\n// provide a document until the selection is actually applied, which\n// is useful when compressing.)\n// Used to schedule history compression\nconst max_empty_items = 500;\nclass Branch {\n constructor(items, eventCount) {\n this.items = items;\n this.eventCount = eventCount;\n }\n // Pop the latest event off the branch's history and apply it\n // to a document transform.\n popEvent(state, preserveItems) {\n if (this.eventCount == 0)\n return null;\n let end = this.items.length;\n for (;; end--) {\n let next = this.items.get(end - 1);\n if (next.selection) {\n --end;\n break;\n }\n }\n let remap, mapFrom;\n if (preserveItems) {\n remap = this.remapping(end, this.items.length);\n mapFrom = remap.maps.length;\n }\n let transform = state.tr;\n let selection, remaining;\n let addAfter = [], addBefore = [];\n this.items.forEach((item, i) => {\n if (!item.step) {\n if (!remap) {\n remap = this.remapping(end, i + 1);\n mapFrom = remap.maps.length;\n }\n mapFrom--;\n addBefore.push(item);\n return;\n }\n if (remap) {\n addBefore.push(new Item(item.map));\n let step = item.step.map(remap.slice(mapFrom)), map;\n if (step && transform.maybeStep(step).doc) {\n map = transform.mapping.maps[transform.mapping.maps.length - 1];\n addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length));\n }\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n }\n else {\n transform.maybeStep(item.step);\n }\n if (item.selection) {\n selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;\n remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);\n return false;\n }\n }, this.items.length, 0);\n return { remaining: remaining, transform, selection: selection };\n }\n // Create a new branch with the given transform added.\n addTransform(transform, selection, histOptions, preserveItems) {\n let newItems = [], eventCount = this.eventCount;\n let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;\n for (let i = 0; i < transform.steps.length; i++) {\n let step = transform.steps[i].invert(transform.docs[i]);\n let item = new Item(transform.mapping.maps[i], step, selection), merged;\n if (merged = lastItem && lastItem.merge(item)) {\n item = merged;\n if (i)\n newItems.pop();\n else\n oldItems = oldItems.slice(0, oldItems.length - 1);\n }\n newItems.push(item);\n if (selection) {\n eventCount++;\n selection = undefined;\n }\n if (!preserveItems)\n lastItem = item;\n }\n let overflow = eventCount - histOptions.depth;\n if (overflow > DEPTH_OVERFLOW) {\n oldItems = cutOffEvents(oldItems, overflow);\n eventCount -= overflow;\n }\n return new Branch(oldItems.append(newItems), eventCount);\n }\n remapping(from, to) {\n let maps = new Mapping;\n this.items.forEach((item, i) => {\n let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from\n ? maps.maps.length - item.mirrorOffset : undefined;\n maps.appendMap(item.map, mirrorPos);\n }, from, to);\n return maps;\n }\n addMaps(array) {\n if (this.eventCount == 0)\n return this;\n return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount);\n }\n // When the collab module receives remote changes, the history has\n // to know about those, so that it can adjust the steps that were\n // rebased on top of the remote changes, and include the position\n // maps for the remote changes in its array of items.\n rebased(rebasedTransform, rebasedCount) {\n if (!this.eventCount)\n return this;\n let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);\n let mapping = rebasedTransform.mapping;\n let newUntil = rebasedTransform.steps.length;\n let eventCount = this.eventCount;\n this.items.forEach(item => { if (item.selection)\n eventCount--; }, start);\n let iRebased = rebasedCount;\n this.items.forEach(item => {\n let pos = mapping.getMirror(--iRebased);\n if (pos == null)\n return;\n newUntil = Math.min(newUntil, pos);\n let map = mapping.maps[pos];\n if (item.step) {\n let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);\n let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));\n if (selection)\n eventCount++;\n rebasedItems.push(new Item(map, step, selection));\n }\n else {\n rebasedItems.push(new Item(map));\n }\n }, start);\n let newMaps = [];\n for (let i = rebasedCount; i < newUntil; i++)\n newMaps.push(new Item(mapping.maps[i]));\n let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);\n let branch = new Branch(items, eventCount);\n if (branch.emptyItemCount() > max_empty_items)\n branch = branch.compress(this.items.length - rebasedItems.length);\n return branch;\n }\n emptyItemCount() {\n let count = 0;\n this.items.forEach(item => { if (!item.step)\n count++; });\n return count;\n }\n // Compressing a branch means rewriting it to push the air (map-only\n // items) out. During collaboration, these naturally accumulate\n // because each remote change adds one. The `upto` argument is used\n // to ensure that only the items below a given level are compressed,\n // because `rebased` relies on a clean, untouched set of items in\n // order to associate old items with rebased steps.\n compress(upto = this.items.length) {\n let remap = this.remapping(0, upto), mapFrom = remap.maps.length;\n let items = [], events = 0;\n this.items.forEach((item, i) => {\n if (i >= upto) {\n items.push(item);\n if (item.selection)\n events++;\n }\n else if (item.step) {\n let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap();\n mapFrom--;\n if (map)\n remap.appendMap(map, mapFrom);\n if (step) {\n let selection = item.selection && item.selection.map(remap.slice(mapFrom));\n if (selection)\n events++;\n let newItem = new Item(map.invert(), step, selection), merged, last = items.length - 1;\n if (merged = items.length && items[last].merge(newItem))\n items[last] = merged;\n else\n items.push(newItem);\n }\n }\n else if (item.map) {\n mapFrom--;\n }\n }, this.items.length, 0);\n return new Branch(RopeSequence.from(items.reverse()), events);\n }\n}\nBranch.empty = new Branch(RopeSequence.empty, 0);\nfunction cutOffEvents(items, n) {\n let cutPoint;\n items.forEach((item, i) => {\n if (item.selection && (n-- == 0)) {\n cutPoint = i;\n return false;\n }\n });\n return items.slice(cutPoint);\n}\nclass Item {\n constructor(\n // The (forward) step map for this item.\n map, \n // The inverted step\n step, \n // If this is non-null, this item is the start of a group, and\n // this selection is the starting selection for the group (the one\n // that was active before the first step was applied)\n selection, \n // If this item is the inverse of a previous mapping on the stack,\n // this points at the inverse's offset\n mirrorOffset) {\n this.map = map;\n this.step = step;\n this.selection = selection;\n this.mirrorOffset = mirrorOffset;\n }\n merge(other) {\n if (this.step && other.step && !other.selection) {\n let step = other.step.merge(this.step);\n if (step)\n return new Item(step.getMap().invert(), step, this.selection);\n }\n }\n}\n// The value of the state field that tracks undo/redo history for that\n// state. Will be stored in the plugin state when the history plugin\n// is active.\nclass HistoryState {\n constructor(done, undone, prevRanges, prevTime, prevComposition) {\n this.done = done;\n this.undone = undone;\n this.prevRanges = prevRanges;\n this.prevTime = prevTime;\n this.prevComposition = prevComposition;\n }\n}\nconst DEPTH_OVERFLOW = 20;\n// Record a transformation in undo history.\nfunction applyTransaction(history, state, tr, options) {\n let historyTr = tr.getMeta(historyKey), rebased;\n if (historyTr)\n return historyTr.historyState;\n if (tr.getMeta(closeHistoryKey))\n history = new HistoryState(history.done, history.undone, null, 0, -1);\n let appended = tr.getMeta(\"appendedTransaction\");\n if (tr.steps.length == 0) {\n return history;\n }\n else if (appended && appended.getMeta(historyKey)) {\n if (appended.getMeta(historyKey).redo)\n return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition);\n else\n return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition);\n }\n else if (tr.getMeta(\"addToHistory\") !== false && !(appended && appended.getMeta(\"addToHistory\") === false)) {\n // Group transforms that occur in quick succession into one event.\n let composition = tr.getMeta(\"composition\");\n let newGroup = history.prevTime == 0 ||\n (!appended && history.prevComposition != composition &&\n (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges)));\n let prevRanges = appended ? mapRanges(history.prevRanges, tr.mapping) : rangesFor(tr.mapping.maps);\n return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition);\n }\n else if (rebased = tr.getMeta(\"rebased\")) {\n // Used by the collab module to tell the history that some of its\n // content has been rebased.\n return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n else {\n return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges, tr.mapping), history.prevTime, history.prevComposition);\n }\n}\nfunction isAdjacentTo(transform, prevRanges) {\n if (!prevRanges)\n return false;\n if (!transform.docChanged)\n return true;\n let adjacent = false;\n transform.mapping.maps[0].forEach((start, end) => {\n for (let i = 0; i < prevRanges.length; i += 2)\n if (start <= prevRanges[i + 1] && end >= prevRanges[i])\n adjacent = true;\n });\n return adjacent;\n}\nfunction rangesFor(maps) {\n let result = [];\n for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)\n maps[i].forEach((_from, _to, from, to) => result.push(from, to));\n return result;\n}\nfunction mapRanges(ranges, mapping) {\n if (!ranges)\n return null;\n let result = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);\n if (from <= to)\n result.push(from, to);\n }\n return result;\n}\n// Apply the latest event from one branch to the document and shift the event\n// onto the other branch.\nfunction histTransaction(history, state, redo) {\n let preserveItems = mustPreserveItems(state);\n let histOptions = historyKey.get(state).spec.config;\n let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n if (!pop)\n return null;\n let selection = pop.selection.resolve(pop.transform.doc);\n let added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);\n let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1);\n return pop.transform.setSelection(selection).setMeta(historyKey, { redo, historyState: newHist });\n}\nlet cachedPreserveItems = false, cachedPreserveItemsPlugins = null;\n// Check whether any plugin in the given state has a\n// `historyPreserveItems` property in its spec, in which case we must\n// preserve steps exactly as they came in, so that they can be\n// rebased.\nfunction mustPreserveItems(state) {\n let plugins = state.plugins;\n if (cachedPreserveItemsPlugins != plugins) {\n cachedPreserveItems = false;\n cachedPreserveItemsPlugins = plugins;\n for (let i = 0; i < plugins.length; i++)\n if (plugins[i].spec.historyPreserveItems) {\n cachedPreserveItems = true;\n break;\n }\n }\n return cachedPreserveItems;\n}\n/**\nSet a flag on the given transaction that will prevent further steps\nfrom being appended to an existing history event (so that they\nrequire a separate undo command to undo).\n*/\nfunction closeHistory(tr) {\n return tr.setMeta(closeHistoryKey, true);\n}\nconst historyKey = new PluginKey(\"history\");\nconst closeHistoryKey = new PluginKey(\"closeHistory\");\n/**\nReturns a plugin that enables the undo history for an editor. The\nplugin will track undo and redo stacks, which can be used with the\n[`undo`](https://prosemirror.net/docs/ref/#history.undo) and [`redo`](https://prosemirror.net/docs/ref/#history.redo) commands.\n\nYou can set an `\"addToHistory\"` [metadata\nproperty](https://prosemirror.net/docs/ref/#state.Transaction.setMeta) of `false` on a transaction\nto prevent it from being rolled back by undo.\n*/\nfunction history(config = {}) {\n config = { depth: config.depth || 100,\n newGroupDelay: config.newGroupDelay || 500 };\n return new Plugin({\n key: historyKey,\n state: {\n init() {\n return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);\n },\n apply(tr, hist, state) {\n return applyTransaction(hist, state, tr, config);\n }\n },\n config,\n props: {\n handleDOMEvents: {\n beforeinput(view, e) {\n let inputType = e.inputType;\n let command = inputType == \"historyUndo\" ? undo : inputType == \"historyRedo\" ? redo : null;\n if (!command || !view.editable)\n return false;\n e.preventDefault();\n return command(view.state, view.dispatch);\n }\n }\n }\n });\n}\nfunction buildCommand(redo, scroll) {\n return (state, dispatch) => {\n let hist = historyKey.getState(state);\n if (!hist || (redo ? hist.undone : hist.done).eventCount == 0)\n return false;\n if (dispatch) {\n let tr = histTransaction(hist, state, redo);\n if (tr)\n dispatch(scroll ? tr.scrollIntoView() : tr);\n }\n return true;\n };\n}\n/**\nA command function that undoes the last change, if any.\n*/\nconst undo = buildCommand(false, true);\n/**\nA command function that redoes the last undone change, if any.\n*/\nconst redo = buildCommand(true, true);\n/**\nA command function that undoes the last change. Don't scroll the\nselection into view.\n*/\nconst undoNoScroll = buildCommand(false, false);\n/**\nA command function that redoes the last undone change. Don't\nscroll the selection into view.\n*/\nconst redoNoScroll = buildCommand(true, false);\n/**\nThe amount of undoable events available in a given state.\n*/\nfunction undoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.done.eventCount : 0;\n}\n/**\nThe amount of redoable events available in a given editor state.\n*/\nfunction redoDepth(state) {\n let hist = historyKey.getState(state);\n return hist ? hist.undone.eventCount : 0;\n}\n/**\nReturns true if the given transaction was generated by the history\nplugin.\n*/\nfunction isHistoryTransaction(tr) {\n return tr.getMeta(historyKey) != null;\n}\n\nexport { closeHistory, history, isHistoryTransaction, redo, redoDepth, redoNoScroll, undo, undoDepth, undoNoScroll };\n", "import { Extension } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\nexport interface CharacterCountOptions {\n /**\n * The maximum number of characters that should be allowed. Defaults to `0`.\n * @default null\n * @example 180\n */\n limit: number | null | undefined\n /**\n * The mode by which the size is calculated. If set to `textSize`, the textContent of the document is used.\n * If set to `nodeSize`, the nodeSize of the document is used.\n * @default 'textSize'\n * @example 'textSize'\n */\n mode: 'textSize' | 'nodeSize'\n /**\n * The text counter function to use. Defaults to a simple character count.\n * @default (text) => text.length\n * @example (text) => [...new Intl.Segmenter().segment(text)].length\n */\n textCounter: (text: string) => number\n /**\n * The word counter function to use. Defaults to a simple word count.\n * @default (text) => text.split(' ').filter(word => word !== '').length\n * @example (text) => text.split(/\\s+/).filter(word => word !== '').length\n */\n wordCounter: (text: string) => number\n}\n\nexport interface CharacterCountStorage {\n /**\n * Get the number of characters for the current document.\n * @param options The options for the character count. (optional)\n * @param options.node The node to get the characters from. Defaults to the current document.\n * @param options.mode The mode by which the size is calculated. If set to `textSize`, the textContent of the document is used.\n */\n characters: (options?: { node?: ProseMirrorNode; mode?: 'textSize' | 'nodeSize' }) => number\n\n /**\n * Get the number of words for the current document.\n * @param options The options for the character count. (optional)\n * @param options.node The node to get the words from. Defaults to the current document.\n */\n words: (options?: { node?: ProseMirrorNode }) => number\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n characterCount: CharacterCountStorage\n }\n}\n\n/**\n * This extension allows you to count the characters and words of your document.\n * @see https://tiptap.dev/api/extensions/character-count\n */\nexport const CharacterCount = Extension.create({\n name: 'characterCount',\n\n addOptions() {\n return {\n limit: null,\n mode: 'textSize',\n textCounter: text => text.length,\n wordCounter: text => text.split(' ').filter(word => word !== '').length,\n }\n },\n\n addStorage() {\n return {\n characters: () => 0,\n words: () => 0,\n }\n },\n\n onBeforeCreate() {\n this.storage.characters = options => {\n const node = options?.node || this.editor.state.doc\n const mode = options?.mode || this.options.mode\n\n if (mode === 'textSize') {\n const text = node.textBetween(0, node.content.size, undefined, ' ')\n\n return this.options.textCounter(text)\n }\n\n return node.nodeSize\n }\n\n this.storage.words = options => {\n const node = options?.node || this.editor.state.doc\n const text = node.textBetween(0, node.content.size, ' ', ' ')\n\n return this.options.wordCounter(text)\n }\n },\n\n addProseMirrorPlugins() {\n let initialEvaluationDone = false\n\n return [\n new Plugin({\n key: new PluginKey('characterCount'),\n appendTransaction: (transactions, oldState, newState) => {\n if (initialEvaluationDone) {\n return\n }\n\n const limit = this.options.limit\n\n if (limit === null || limit === undefined || limit === 0) {\n initialEvaluationDone = true\n return\n }\n\n const initialContentSize = this.storage.characters({ node: newState.doc })\n\n if (initialContentSize > limit) {\n const over = initialContentSize - limit\n const from = 0\n const to = over\n\n console.warn(\n `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`,\n )\n const tr = newState.tr.deleteRange(from, to)\n\n initialEvaluationDone = true\n return tr\n }\n\n initialEvaluationDone = true\n },\n filterTransaction: (transaction, state) => {\n const limit = this.options.limit\n\n // Nothing has changed or no limit is defined. Ignore it.\n if (!transaction.docChanged || limit === 0 || limit === null || limit === undefined) {\n return true\n }\n\n const oldSize = this.storage.characters({ node: state.doc })\n const newSize = this.storage.characters({ node: transaction.doc })\n\n // Everything is in the limit. Good.\n if (newSize <= limit) {\n return true\n }\n\n // The limit has already been exceeded but will be reduced.\n if (oldSize > limit && newSize > limit && newSize <= oldSize) {\n return true\n }\n\n // The limit has already been exceeded and will be increased further.\n if (oldSize > limit && newSize > limit && newSize > oldSize) {\n return false\n }\n\n const isPaste = transaction.getMeta('paste')\n\n // Block all exceeding transactions that were not pasted.\n if (!isPaste) {\n return false\n }\n\n // For pasted content, we try to remove the exceeding content.\n const pos = transaction.selection.$head.pos\n const over = newSize - limit\n const from = pos - over\n const to = pos\n\n // It’s probably a bad idea to mutate transactions within `filterTransaction`\n // but for now this is working fine.\n transaction.deleteRange(from, to)\n\n // In some situations, the limit will continue to be exceeded after trimming.\n // This happens e.g. when truncating within a complex node (e.g. table)\n // and ProseMirror has to close this node again.\n // If this is the case, we prevent the transaction completely.\n const updatedSize = this.storage.characters({ node: transaction.doc })\n\n if (updatedSize > limit) {\n return false\n }\n\n return true\n },\n }),\n ]\n },\n})\n", "import { Extension } from '@tiptap/core'\nimport { dropCursor } from '@tiptap/pm/dropcursor'\n\nexport interface DropcursorOptions {\n /**\n * The color of the drop cursor. Use `false` to apply no color and rely only on class.\n * @default 'currentColor'\n * @example 'red'\n */\n color?: string | false\n\n /**\n * The width of the drop cursor\n * @default 1\n * @example 2\n */\n width: number | undefined\n\n /**\n * The class of the drop cursor\n * @default undefined\n * @example 'drop-cursor'\n */\n class: string | undefined\n}\n\n/**\n * This extension allows you to add a drop cursor to your editor.\n * A drop cursor is a line that appears when you drag and drop content\n * in-between nodes.\n * @see https://tiptap.dev/api/extensions/dropcursor\n */\nexport const Dropcursor = Extension.create({\n name: 'dropCursor',\n\n addOptions() {\n return {\n color: 'currentColor',\n width: 1,\n class: undefined,\n }\n },\n\n addProseMirrorPlugins() {\n return [dropCursor(this.options)]\n },\n})\n", "import { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\nexport interface FocusOptions {\n /**\n * The class name that should be added to the focused node.\n * @default 'has-focus'\n * @example 'is-focused'\n */\n className: string\n\n /**\n * The mode by which the focused node is determined.\n * - All: All nodes are marked as focused.\n * - Deepest: Only the deepest node is marked as focused.\n * - Shallowest: Only the shallowest node is marked as focused.\n *\n * @default 'all'\n * @example 'deepest'\n * @example 'shallowest'\n */\n mode: 'all' | 'deepest' | 'shallowest'\n}\n\n/**\n * This extension allows you to add a class to the focused node.\n * @see https://www.tiptap.dev/api/extensions/focus\n */\nexport const Focus = Extension.create({\n name: 'focus',\n\n addOptions() {\n return {\n className: 'has-focus',\n mode: 'all',\n }\n },\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('focus'),\n props: {\n decorations: ({ doc, selection }) => {\n const { isEditable, isFocused } = this.editor\n const { anchor } = selection\n const decorations: Decoration[] = []\n\n if (!isEditable || !isFocused) {\n return DecorationSet.create(doc, [])\n }\n\n // Maximum Levels\n let maxLevels = 0\n\n if (this.options.mode === 'deepest') {\n doc.descendants((node, pos) => {\n if (node.isText) {\n return\n }\n\n const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1\n\n if (!isCurrent) {\n return false\n }\n\n maxLevels += 1\n })\n }\n\n // Loop through current\n let currentLevel = 0\n\n doc.descendants((node, pos) => {\n if (node.isText) {\n return false\n }\n\n const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1\n\n if (!isCurrent) {\n return false\n }\n\n currentLevel += 1\n\n const outOfScope =\n (this.options.mode === 'deepest' && maxLevels - currentLevel > 0) ||\n (this.options.mode === 'shallowest' && currentLevel > 1)\n\n if (outOfScope) {\n return this.options.mode === 'deepest'\n }\n\n decorations.push(\n Decoration.node(pos, pos + node.nodeSize, {\n class: this.options.className,\n }),\n )\n })\n\n return DecorationSet.create(doc, decorations)\n },\n },\n }),\n ]\n },\n})\n", "import type { ParentConfig } from '@tiptap/core'\nimport { callOrReturn, Extension, getExtensionField } from '@tiptap/core'\nimport { gapCursor } from '@tiptap/pm/gapcursor'\n\ndeclare module '@tiptap/core' {\n interface NodeConfig {\n /**\n * A function to determine whether the gap cursor is allowed at the current position. Must return `true` or `false`.\n * @default null\n */\n allowGapCursor?:\n | boolean\n | null\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['allowGapCursor']\n }) => boolean | null)\n }\n}\n\n/**\n * This extension allows you to add a gap cursor to your editor.\n * A gap cursor is a cursor that appears when you click on a place\n * where no content is present, for example inbetween nodes.\n * @see https://tiptap.dev/api/extensions/gapcursor\n */\nexport const Gapcursor = Extension.create({\n name: 'gapCursor',\n\n addProseMirrorPlugins() {\n return [gapCursor()]\n },\n\n extendNodeSchema(extension) {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n\n return {\n allowGapCursor: callOrReturn(getExtensionField(extension, 'allowGapCursor', context)) ?? null,\n }\n },\n})\n", "import type { Editor } from '@tiptap/core'\nimport { Extension, isNodeEmpty } from '@tiptap/core'\nimport type { Node as ProsemirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\n/**\n * The default data attribute label\n */\nconst DEFAULT_DATA_ATTRIBUTE = 'placeholder'\n\n/**\n * Prepares the placeholder attribute by ensuring it is properly formatted.\n * @param attr - The placeholder attribute string.\n * @returns The prepared placeholder attribute string.\n */\nexport function preparePlaceholderAttribute(attr: string): string {\n return (\n attr\n // replace whitespace with dashes\n .replace(/\\s+/g, '-')\n // replace non-alphanumeric characters\n // or special chars like $, %, &, etc.\n // but not dashes\n .replace(/[^a-zA-Z0-9-]/g, '')\n // and replace any numeric character at the start\n .replace(/^[0-9-]+/, '')\n // and finally replace any stray, leading dashes\n .replace(/^-+/, '')\n .toLowerCase()\n )\n}\n\nexport interface PlaceholderOptions {\n /**\n * **The class name for the empty editor**\n * @default 'is-editor-empty'\n */\n emptyEditorClass: string\n\n /**\n * **The class name for empty nodes**\n * @default 'is-empty'\n */\n emptyNodeClass: string\n\n /**\n * **The data-attribute used for the placeholder label**\n * Will be prepended with `data-` and converted to kebab-case and cleaned of special characters.\n * @default 'placeholder'\n */\n dataAttribute: string\n\n /**\n * **The placeholder content**\n *\n * You can use a function to return a dynamic placeholder or a string.\n * @default 'Write something …'\n */\n placeholder:\n | ((PlaceholderProps: { editor: Editor; node: ProsemirrorNode; pos: number; hasAnchor: boolean }) => string)\n | string\n\n /**\n * **Checks if the placeholder should be only shown when the editor is editable.**\n *\n * If true, the placeholder will only be shown when the editor is editable.\n * If false, the placeholder will always be shown.\n * @default true\n */\n showOnlyWhenEditable: boolean\n\n /**\n * **Checks if the placeholder should be only shown when the current node is empty.**\n *\n * If true, the placeholder will only be shown when the current node is empty.\n * If false, the placeholder will be shown when any node is empty.\n * @default true\n */\n showOnlyCurrent: boolean\n\n /**\n * **Controls if the placeholder should be shown for all descendents.**\n *\n * If true, the placeholder will be shown for all descendents.\n * If false, the placeholder will only be shown for the current node.\n * @default false\n */\n includeChildren: boolean\n}\n\n/**\n * This extension allows you to add a placeholder to your editor.\n * A placeholder is a text that appears when the editor or a node is empty.\n * @see https://www.tiptap.dev/api/extensions/placeholder\n */\nexport const Placeholder = Extension.create({\n name: 'placeholder',\n\n addOptions() {\n return {\n emptyEditorClass: 'is-editor-empty',\n emptyNodeClass: 'is-empty',\n dataAttribute: DEFAULT_DATA_ATTRIBUTE,\n placeholder: 'Write something …',\n showOnlyWhenEditable: true,\n showOnlyCurrent: true,\n includeChildren: false,\n }\n },\n\n addProseMirrorPlugins() {\n const dataAttribute = this.options.dataAttribute\n ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}`\n : `data-${DEFAULT_DATA_ATTRIBUTE}`\n\n return [\n new Plugin({\n key: new PluginKey('placeholder'),\n props: {\n decorations: ({ doc, selection }) => {\n const active = this.editor.isEditable || !this.options.showOnlyWhenEditable\n const { anchor } = selection\n const decorations: Decoration[] = []\n\n if (!active) {\n return null\n }\n\n const isEmptyDoc = this.editor.isEmpty\n\n doc.descendants((node, pos) => {\n const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize\n const isEmpty = !node.isLeaf && isNodeEmpty(node)\n\n if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {\n const classes = [this.options.emptyNodeClass]\n\n if (isEmptyDoc) {\n classes.push(this.options.emptyEditorClass)\n }\n\n const decoration = Decoration.node(pos, pos + node.nodeSize, {\n class: classes.join(' '),\n [dataAttribute]:\n typeof this.options.placeholder === 'function'\n ? this.options.placeholder({\n editor: this.editor,\n node,\n pos,\n hasAnchor,\n })\n : this.options.placeholder,\n })\n\n decorations.push(decoration)\n }\n\n return this.options.includeChildren\n })\n\n return DecorationSet.create(doc, decorations)\n },\n },\n }),\n ]\n },\n})\n", "import { Extension, isNodeSelection } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\nexport type SelectionOptions = {\n /**\n * The class name that should be added to the selected text.\n * @default 'selection'\n * @example 'is-selected'\n */\n className: string\n}\n\n/**\n * This extension allows you to add a class to the selected text.\n * @see https://www.tiptap.dev/api/extensions/selection\n */\nexport const Selection = Extension.create({\n name: 'selection',\n\n addOptions() {\n return {\n className: 'selection',\n }\n },\n\n addProseMirrorPlugins() {\n const { editor, options } = this\n\n return [\n new Plugin({\n key: new PluginKey('selection'),\n props: {\n decorations(state) {\n if (\n state.selection.empty ||\n editor.isFocused ||\n !editor.isEditable ||\n isNodeSelection(state.selection) ||\n editor.view.dragging\n ) {\n return null\n }\n\n return DecorationSet.create(state.doc, [\n Decoration.inline(state.selection.from, state.selection.to, {\n class: options.className,\n }),\n ])\n },\n },\n }),\n ]\n },\n})\n\nexport default Selection\n", "import { Extension } from '@tiptap/core'\nimport type { Node, NodeType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\nfunction nodeEqualsType({ types, node }: { types: NodeType | NodeType[]; node: Node | null | undefined }) {\n return (node && Array.isArray(types) && types.includes(node.type)) || node?.type === types\n}\n\n/**\n * Extension based on:\n * - https://github.com/ueberdosis/tiptap/blob/v1/packages/tiptap-extensions/src/extensions/TrailingNode.js\n * - https://github.com/remirror/remirror/blob/e0f1bec4a1e8073ce8f5500d62193e52321155b9/packages/prosemirror-trailing-node/src/trailing-node-plugin.ts\n */\n\nexport interface TrailingNodeOptions {\n /**\n * The node type that should be inserted at the end of the document.\n * @note the node will always be added to the `notAfter` lists to\n * prevent an infinite loop.\n * @default undefined\n */\n node?: string\n /**\n * The node types after which the trailing node should not be inserted.\n * @default ['paragraph']\n */\n notAfter?: string | string[]\n}\n\n/**\n * This extension allows you to add an extra node at the end of the document.\n * @see https://www.tiptap.dev/api/extensions/trailing-node\n */\nexport const TrailingNode = Extension.create({\n name: 'trailingNode',\n\n addOptions() {\n return {\n node: undefined,\n notAfter: [],\n }\n },\n\n addProseMirrorPlugins() {\n const plugin = new PluginKey(this.name)\n const defaultNode =\n this.options.node || this.editor.schema.topNodeType.contentMatch.defaultType?.name || 'paragraph'\n\n const disabledNodes = Object.entries(this.editor.schema.nodes)\n .map(([, value]) => value)\n .filter(node => (this.options.notAfter || []).concat(defaultNode).includes(node.name))\n\n return [\n new Plugin({\n key: plugin,\n appendTransaction: (_, __, state) => {\n const { doc, tr, schema } = state\n const shouldInsertNodeAtEnd = plugin.getState(state)\n const endPosition = doc.content.size\n const type = schema.nodes[defaultNode]\n\n if (!shouldInsertNodeAtEnd) {\n return\n }\n\n return tr.insert(endPosition, type.create())\n },\n state: {\n init: (_, state) => {\n const lastNode = state.tr.doc.lastChild\n\n return !nodeEqualsType({ node: lastNode, types: disabledNodes })\n },\n apply: (tr, value) => {\n if (!tr.docChanged) {\n return value\n }\n\n // Ignore transactions from UniqueID extension to prevent infinite loops\n // when UniqueID adds IDs to newly inserted trailing nodes\n if (tr.getMeta('__uniqueIDTransaction')) {\n return value\n }\n\n const lastNode = tr.doc.lastChild\n\n return !nodeEqualsType({ node: lastNode, types: disabledNodes })\n },\n },\n }),\n ]\n },\n})\n", "import { Extension } from '@tiptap/core'\nimport { history, redo, undo } from '@tiptap/pm/history'\n\nexport interface UndoRedoOptions {\n /**\n * The amount of history events that are collected before the oldest events are discarded.\n * @default 100\n * @example 50\n */\n depth: number\n\n /**\n * The delay (in milliseconds) between changes after which a new group should be started.\n * @default 500\n * @example 1000\n */\n newGroupDelay: number\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n undoRedo: {\n /**\n * Undo recent changes\n * @example editor.commands.undo()\n */\n undo: () => ReturnType\n /**\n * Reapply reverted changes\n * @example editor.commands.redo()\n */\n redo: () => ReturnType\n }\n }\n}\n\n/**\n * This extension allows you to undo and redo recent changes.\n * @see https://www.tiptap.dev/api/extensions/undo-redo\n *\n * **Important**: If the `@tiptap/extension-collaboration` package is used, make sure to remove\n * the `undo-redo` extension, as it is not compatible with the `collaboration` extension.\n *\n * `@tiptap/extension-collaboration` uses its own history implementation.\n */\nexport const UndoRedo = Extension.create({\n name: 'undoRedo',\n\n addOptions() {\n return {\n depth: 100,\n newGroupDelay: 500,\n }\n },\n\n addCommands() {\n return {\n undo:\n () =>\n ({ state, dispatch }) => {\n return undo(state, dispatch)\n },\n redo:\n () =>\n ({ state, dispatch }) => {\n return redo(state, dispatch)\n },\n }\n },\n\n addProseMirrorPlugins() {\n return [history(this.options)]\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-z': () => this.editor.commands.undo(),\n 'Shift-Mod-z': () => this.editor.commands.redo(),\n 'Mod-y': () => this.editor.commands.redo(),\n\n // Russian keyboard layouts\n 'Mod-я': () => this.editor.commands.undo(),\n 'Shift-Mod-я': () => this.editor.commands.redo(),\n }\n },\n})\n", "import { Extension } from '@tiptap/core'\nimport type { BlockquoteOptions } from '@tiptap/extension-blockquote'\nimport { Blockquote } from '@tiptap/extension-blockquote'\nimport type { BoldOptions } from '@tiptap/extension-bold'\nimport { Bold } from '@tiptap/extension-bold'\nimport type { CodeOptions } from '@tiptap/extension-code'\nimport { Code } from '@tiptap/extension-code'\nimport type { CodeBlockOptions } from '@tiptap/extension-code-block'\nimport { CodeBlock } from '@tiptap/extension-code-block'\nimport { Document } from '@tiptap/extension-document'\nimport type { HardBreakOptions } from '@tiptap/extension-hard-break'\nimport { HardBreak } from '@tiptap/extension-hard-break'\nimport type { HeadingOptions } from '@tiptap/extension-heading'\nimport { Heading } from '@tiptap/extension-heading'\nimport type { HorizontalRuleOptions } from '@tiptap/extension-horizontal-rule'\nimport { HorizontalRule } from '@tiptap/extension-horizontal-rule'\nimport type { ItalicOptions } from '@tiptap/extension-italic'\nimport { Italic } from '@tiptap/extension-italic'\nimport type { LinkOptions } from '@tiptap/extension-link'\nimport { Link } from '@tiptap/extension-link'\nimport type { BulletListOptions, ListItemOptions, ListKeymapOptions, OrderedListOptions } from '@tiptap/extension-list'\nimport { BulletList, ListItem, ListKeymap, OrderedList } from '@tiptap/extension-list'\nimport type { ParagraphOptions } from '@tiptap/extension-paragraph'\nimport { Paragraph } from '@tiptap/extension-paragraph'\nimport type { StrikeOptions } from '@tiptap/extension-strike'\nimport { Strike } from '@tiptap/extension-strike'\nimport { Text } from '@tiptap/extension-text'\nimport type { UnderlineOptions } from '@tiptap/extension-underline'\nimport { Underline } from '@tiptap/extension-underline'\nimport type { DropcursorOptions, TrailingNodeOptions, UndoRedoOptions } from '@tiptap/extensions'\nimport { Dropcursor, Gapcursor, TrailingNode, UndoRedo } from '@tiptap/extensions'\n\nexport interface StarterKitOptions {\n /**\n * If set to false, the blockquote extension will not be registered\n * @example blockquote: false\n */\n blockquote: Partial | false\n\n /**\n * If set to false, the bold extension will not be registered\n * @example bold: false\n */\n bold: Partial | false\n\n /**\n * If set to false, the bulletList extension will not be registered\n * @example bulletList: false\n */\n bulletList: Partial | false\n\n /**\n * If set to false, the code extension will not be registered\n * @example code: false\n */\n code: Partial | false\n\n /**\n * If set to false, the codeBlock extension will not be registered\n * @example codeBlock: false\n */\n codeBlock: Partial | false\n\n /**\n * If set to false, the document extension will not be registered\n * @example document: false\n */\n document: false\n\n /**\n * If set to false, the dropcursor extension will not be registered\n * @example dropcursor: false\n */\n dropcursor: Partial | false\n\n /**\n * If set to false, the gapcursor extension will not be registered\n * @example gapcursor: false\n */\n gapcursor: false\n\n /**\n * If set to false, the hardBreak extension will not be registered\n * @example hardBreak: false\n */\n hardBreak: Partial | false\n\n /**\n * If set to false, the heading extension will not be registered\n * @example heading: false\n */\n heading: Partial | false\n\n /**\n * If set to false, the undo-redo extension will not be registered\n * @example undoRedo: false\n */\n undoRedo: Partial | false\n\n /**\n * If set to false, the horizontalRule extension will not be registered\n * @example horizontalRule: false\n */\n horizontalRule: Partial | false\n\n /**\n * If set to false, the italic extension will not be registered\n * @example italic: false\n */\n italic: Partial | false\n\n /**\n * If set to false, the listItem extension will not be registered\n * @example listItem: false\n */\n listItem: Partial | false\n\n /**\n * If set to false, the listItemKeymap extension will not be registered\n * @example listKeymap: false\n */\n listKeymap: Partial | false\n\n /**\n * If set to false, the link extension will not be registered\n * @example link: false\n */\n link: Partial | false\n\n /**\n * If set to false, the orderedList extension will not be registered\n * @example orderedList: false\n */\n orderedList: Partial | false\n\n /**\n * If set to false, the paragraph extension will not be registered\n * @example paragraph: false\n */\n paragraph: Partial | false\n\n /**\n * If set to false, the strike extension will not be registered\n * @example strike: false\n */\n strike: Partial | false\n\n /**\n * If set to false, the text extension will not be registered\n * @example text: false\n */\n text: false\n\n /**\n * If set to false, the underline extension will not be registered\n * @example underline: false\n */\n underline: Partial | false\n\n /**\n * If set to false, the trailingNode extension will not be registered\n * @example trailingNode: false\n */\n trailingNode: Partial | false\n}\n\n/**\n * The starter kit is a collection of essential editor extensions.\n *\n * It’s a good starting point for building your own editor.\n */\nexport const StarterKit = Extension.create({\n name: 'starterKit',\n\n addExtensions() {\n const extensions = []\n\n if (this.options.bold !== false) {\n extensions.push(Bold.configure(this.options.bold))\n }\n\n if (this.options.blockquote !== false) {\n extensions.push(Blockquote.configure(this.options.blockquote))\n }\n\n if (this.options.bulletList !== false) {\n extensions.push(BulletList.configure(this.options.bulletList))\n }\n\n if (this.options.code !== false) {\n extensions.push(Code.configure(this.options.code))\n }\n\n if (this.options.codeBlock !== false) {\n extensions.push(CodeBlock.configure(this.options.codeBlock))\n }\n\n if (this.options.document !== false) {\n extensions.push(Document.configure(this.options.document))\n }\n\n if (this.options.dropcursor !== false) {\n extensions.push(Dropcursor.configure(this.options.dropcursor))\n }\n\n if (this.options.gapcursor !== false) {\n extensions.push(Gapcursor.configure(this.options.gapcursor))\n }\n\n if (this.options.hardBreak !== false) {\n extensions.push(HardBreak.configure(this.options.hardBreak))\n }\n\n if (this.options.heading !== false) {\n extensions.push(Heading.configure(this.options.heading))\n }\n\n if (this.options.undoRedo !== false) {\n extensions.push(UndoRedo.configure(this.options.undoRedo))\n }\n\n if (this.options.horizontalRule !== false) {\n extensions.push(HorizontalRule.configure(this.options.horizontalRule))\n }\n\n if (this.options.italic !== false) {\n extensions.push(Italic.configure(this.options.italic))\n }\n\n if (this.options.listItem !== false) {\n extensions.push(ListItem.configure(this.options.listItem))\n }\n\n if (this.options.listKeymap !== false) {\n extensions.push(ListKeymap.configure(this.options?.listKeymap))\n }\n\n if (this.options.link !== false) {\n extensions.push(Link.configure(this.options?.link))\n }\n\n if (this.options.orderedList !== false) {\n extensions.push(OrderedList.configure(this.options.orderedList))\n }\n\n if (this.options.paragraph !== false) {\n extensions.push(Paragraph.configure(this.options.paragraph))\n }\n\n if (this.options.strike !== false) {\n extensions.push(Strike.configure(this.options.strike))\n }\n\n if (this.options.text !== false) {\n extensions.push(Text.configure(this.options.text))\n }\n\n if (this.options.underline !== false) {\n extensions.push(Underline.configure(this.options?.underline))\n }\n\n if (this.options.trailingNode !== false) {\n extensions.push(TrailingNode.configure(this.options?.trailingNode))\n }\n\n return extensions\n },\n})\n", "import { StarterKit } from './starter-kit.js'\n\nexport type { StarterKitOptions } from './starter-kit.js'\nexport * from './starter-kit.js'\n\nexport default StarterKit\n"], + "mappings": ";;;;;;;;;;;;;;;;;;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,SAAA,GAAc,UAAU,CAAC;IAChE;AAEA,QAAI,KAAK,QAAQ,SAAS,OAAO;AAC/B,iBAAW,KAAK,KAAK,WAAU,KAAA,KAAK,YAAL,OAAA,SAAA,GAAc,IAAI,CAAC;IACpD;AAEA,QAAI,KAAK,QAAQ,gBAAgB,OAAO;AACtC,iBAAW,KAAK,YAAY,UAAU,KAAK,QAAQ,WAAW,CAAC;IACjE;AAEA,QAAI,KAAK,QAAQ,cAAc,OAAO;AACpC,iBAAW,KAAK,UAAU,UAAU,KAAK,QAAQ,SAAS,CAAC;IAC7D;AAEA,QAAI,KAAK,QAAQ,WAAW,OAAO;AACjC,iBAAW,KAAK,OAAO,UAAU,KAAK,QAAQ,MAAM,CAAC;IACvD;AAEA,QAAI,KAAK,QAAQ,SAAS,OAAO;AAC/B,iBAAW,KAAK,KAAK,UAAU,KAAK,QAAQ,IAAI,CAAC;IACnD;AAEA,QAAI,KAAK,QAAQ,cAAc,OAAO;AACpC,iBAAW,KAAK,UAAU,WAAU,KAAA,KAAK,YAAL,OAAA,SAAA,GAAc,SAAS,CAAC;IAC9D;AAEA,QAAI,KAAK,QAAQ,iBAAiB,OAAO;AACvC,iBAAW,KAAK,aAAa,WAAU,KAAA,KAAK,YAAL,OAAA,SAAA,GAAc,YAAY,CAAC;IACpE;AAEA,WAAO;EACT;AACF,CAAC;ACtQD,IAAO,gBAAQ;", + "names": ["h", "h", "inputRegex", "h", "h", "from", "_a", "h", "h", "starInputRegex", "starPasteRegex", "underscoreInputRegex", "underscorePasteRegex", "h", "h", "Node", "mergeAttributes", "getNodeType", "isNodeActive", "ListItemName", "TextStyleName", "wrappingInputRule", "inputRegex", "renderNestedMarkdownContent", "Extension", "h", "inputRegex", "pasteRegex", "h", "rect", "RopeSequence", "from", "Leaf", "Append", "appendInner", "map", "from", "history", "redo", "redo", "from", "Extension", "Plugin", "PluginKey", "Decoration", "DecorationSet", "Selection"] +} diff --git a/frontend/node_modules/.vite/deps/_metadata.json b/frontend/node_modules/.vite/deps/_metadata.json index 28055e4f..59a6b463 100644 --- a/frontend/node_modules/.vite/deps/_metadata.json +++ b/frontend/node_modules/.vite/deps/_metadata.json @@ -1,83 +1,107 @@ { - "hash": "b8db82d9", + "hash": "3e94270a", "configHash": "c7be2068", - "lockfileHash": "ee9bf28c", - "browserHash": "deb47249", + "lockfileHash": "c53fe6cb", + "browserHash": "ee679691", "optimized": { "react": { "src": "../../react/index.js", "file": "react.js", - "fileHash": "304f33a9", + "fileHash": "c6967d06", "needsInterop": true }, "react-dom": { "src": "../../react-dom/index.js", "file": "react-dom.js", - "fileHash": "96d32bc1", + "fileHash": "86783379", "needsInterop": true }, "react/jsx-dev-runtime": { "src": "../../react/jsx-dev-runtime.js", "file": "react_jsx-dev-runtime.js", - "fileHash": "6424b7ea", + "fileHash": "d4bbc325", "needsInterop": true }, "react/jsx-runtime": { "src": "../../react/jsx-runtime.js", "file": "react_jsx-runtime.js", - "fileHash": "af95a7a1", + "fileHash": "c4c48fd2", "needsInterop": true }, "@tanstack/react-query": { "src": "../../@tanstack/react-query/build/modern/index.js", "file": "@tanstack_react-query.js", - "fileHash": "c9459c14", + "fileHash": "0ed0cd7e", "needsInterop": false }, "axios": { "src": "../../axios/index.js", "file": "axios.js", - "fileHash": "032e1913", + "fileHash": "b14adf3a", "needsInterop": false }, "lucide-react": { "src": "../../lucide-react/dist/esm/lucide-react.js", "file": "lucide-react.js", - "fileHash": "341675db", + "fileHash": "b370d795", "needsInterop": false }, "react-dom/client": { "src": "../../react-dom/client.js", "file": "react-dom_client.js", - "fileHash": "6520a32f", + "fileHash": "17cccb93", "needsInterop": true }, "react-hook-form": { "src": "../../react-hook-form/dist/index.esm.mjs", "file": "react-hook-form.js", - "fileHash": "29e58164", + "fileHash": "19a01ac0", "needsInterop": false }, "react-router-dom": { "src": "../../react-router-dom/dist/index.js", "file": "react-router-dom.js", - "fileHash": "4b5d4fdc", + "fileHash": "427019e1", "needsInterop": false }, "react-hot-toast": { "src": "../../react-hot-toast/dist/index.mjs", "file": "react-hot-toast.js", - "fileHash": "7423c32d", + "fileHash": "718bd15f", + "needsInterop": false + }, + "@tiptap/react": { + "src": "../../@tiptap/react/dist/index.js", + "file": "@tiptap_react.js", + "fileHash": "c3b8784a", + "needsInterop": false + }, + "@tiptap/starter-kit": { + "src": "../../@tiptap/starter-kit/dist/index.js", + "file": "@tiptap_starter-kit.js", + "fileHash": "99ec846a", + "needsInterop": false + }, + "@tiptap/extension-link": { + "src": "../../@tiptap/extension-link/dist/index.js", + "file": "@tiptap_extension-link.js", + "fileHash": "884cdfc7", "needsInterop": false } }, "chunks": { - "chunk-S77I6LSE": { - "file": "chunk-S77I6LSE.js" + "chunk-MX7X7RGK": { + "file": "chunk-MX7X7RGK.js" + }, + "chunk-YRIELJS7": { + "file": "chunk-YRIELJS7.js" }, "chunk-WERSD76P": { "file": "chunk-WERSD76P.js" }, + "chunk-S77I6LSE": { + "file": "chunk-S77I6LSE.js" + }, "chunk-3TFVT2CW": { "file": "chunk-3TFVT2CW.js" }, diff --git a/frontend/node_modules/.vite/deps/chunk-MX7X7RGK.js b/frontend/node_modules/.vite/deps/chunk-MX7X7RGK.js new file mode 100644 index 00000000..35500201 --- /dev/null +++ b/frontend/node_modules/.vite/deps/chunk-MX7X7RGK.js @@ -0,0 +1,1611 @@ +import { + Mark, + Plugin, + PluginKey, + combineTransactionSteps, + findChildrenInRange, + getAttributes, + getChangedRanges, + getMarksBetween, + markPasteRule, + mergeAttributes +} from "./chunk-YRIELJS7.js"; + +// node_modules/linkifyjs/dist/linkify.mjs +var encodedTlds = "aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2"; +var encodedUtlds = "ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2"; +var numeric = "numeric"; +var ascii = "ascii"; +var alpha = "alpha"; +var asciinumeric = "asciinumeric"; +var alphanumeric = "alphanumeric"; +var domain = "domain"; +var emoji = "emoji"; +var scheme = "scheme"; +var slashscheme = "slashscheme"; +var whitespace = "whitespace"; +function registerGroup(name, groups) { + if (!(name in groups)) { + groups[name] = []; + } + return groups[name]; +} +function addToGroups(t, flags, groups) { + if (flags[numeric]) { + flags[asciinumeric] = true; + flags[alphanumeric] = true; + } + if (flags[ascii]) { + flags[asciinumeric] = true; + flags[alpha] = true; + } + if (flags[asciinumeric]) { + flags[alphanumeric] = true; + } + if (flags[alpha]) { + flags[alphanumeric] = true; + } + if (flags[alphanumeric]) { + flags[domain] = true; + } + if (flags[emoji]) { + flags[domain] = true; + } + for (const k in flags) { + const group = registerGroup(k, groups); + if (group.indexOf(t) < 0) { + group.push(t); + } + } +} +function flagsForToken(t, groups) { + const result = {}; + for (const c in groups) { + if (groups[c].indexOf(t) >= 0) { + result[c] = true; + } + } + return result; +} +function State(token = null) { + this.j = {}; + this.jr = []; + this.jd = null; + this.t = token; +} +State.groups = {}; +State.prototype = { + accepts() { + return !!this.t; + }, + /** + * Follow an existing transition from the given input to the next state. + * Does not mutate. + * @param {string} input character or token type to transition on + * @returns {?State} the next state, if any + */ + go(input) { + const state = this; + const nextState = state.j[input]; + if (nextState) { + return nextState; + } + for (let i = 0; i < state.jr.length; i++) { + const regex = state.jr[i][0]; + const nextState2 = state.jr[i][1]; + if (nextState2 && regex.test(input)) { + return nextState2; + } + } + return state.jd; + }, + /** + * Whether the state has a transition for the given input. Set the second + * argument to true to only look for an exact match (and not a default or + * regular-expression-based transition) + * @param {string} input + * @param {boolean} exactOnly + */ + has(input, exactOnly = false) { + return exactOnly ? input in this.j : !!this.go(input); + }, + /** + * Short for "transition all"; create a transition from the array of items + * in the given list to the same final resulting state. + * @param {string | string[]} inputs Group of inputs to transition on + * @param {Transition | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of token groups + */ + ta(inputs, next, flags, groups) { + for (let i = 0; i < inputs.length; i++) { + this.tt(inputs[i], next, flags, groups); + } + }, + /** + * Short for "take regexp transition"; defines a transition for this state + * when it encounters a token which matches the given regular expression + * @param {RegExp} regexp Regular expression transition (populate first) + * @param {T | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of token groups + * @returns {State} taken after the given input + */ + tr(regexp2, next, flags, groups) { + groups = groups || State.groups; + let nextState; + if (next && next.j) { + nextState = next; + } else { + nextState = new State(next); + if (flags && groups) { + addToGroups(next, flags, groups); + } + } + this.jr.push([regexp2, nextState]); + return nextState; + }, + /** + * Short for "take transitions", will take as many sequential transitions as + * the length of the given input and returns the + * resulting final state. + * @param {string | string[]} input + * @param {T | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of token groups + * @returns {State} taken after the given input + */ + ts(input, next, flags, groups) { + let state = this; + const len = input.length; + if (!len) { + return state; + } + for (let i = 0; i < len - 1; i++) { + state = state.tt(input[i]); + } + return state.tt(input[len - 1], next, flags, groups); + }, + /** + * Short for "take transition", this is a method for building/working with + * state machines. + * + * If a state already exists for the given input, returns it. + * + * If a token is specified, that state will emit that token when reached by + * the linkify engine. + * + * If no state exists, it will be initialized with some default transitions + * that resemble existing default transitions. + * + * If a state is given for the second argument, that state will be + * transitioned to on the given input regardless of what that input + * previously did. + * + * Specify a token group flags to define groups that this token belongs to. + * The token will be added to corresponding entires in the given groups + * object. + * + * @param {string} input character, token type to transition on + * @param {T | State} [next] Transition options + * @param {Flags} [flags] Collections flags to add token to + * @param {Collections} [groups] Master list of groups + * @returns {State} taken after the given input + */ + tt(input, next, flags, groups) { + groups = groups || State.groups; + const state = this; + if (next && next.j) { + state.j[input] = next; + return next; + } + const t = next; + let nextState, templateState = state.go(input); + if (templateState) { + nextState = new State(); + Object.assign(nextState.j, templateState.j); + nextState.jr.push.apply(nextState.jr, templateState.jr); + nextState.jd = templateState.jd; + nextState.t = templateState.t; + } else { + nextState = new State(); + } + if (t) { + if (groups) { + if (nextState.t && typeof nextState.t === "string") { + const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags); + addToGroups(t, allFlags, groups); + } else if (flags) { + addToGroups(t, flags, groups); + } + } + nextState.t = t; + } + state.j[input] = nextState; + return nextState; + } +}; +var ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups); +var tr = (state, regexp2, next, flags, groups) => state.tr(regexp2, next, flags, groups); +var ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups); +var tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups); +var WORD = "WORD"; +var UWORD = "UWORD"; +var ASCIINUMERICAL = "ASCIINUMERICAL"; +var ALPHANUMERICAL = "ALPHANUMERICAL"; +var LOCALHOST = "LOCALHOST"; +var TLD = "TLD"; +var UTLD = "UTLD"; +var SCHEME = "SCHEME"; +var SLASH_SCHEME = "SLASH_SCHEME"; +var NUM = "NUM"; +var WS = "WS"; +var NL = "NL"; +var OPENBRACE = "OPENBRACE"; +var CLOSEBRACE = "CLOSEBRACE"; +var OPENBRACKET = "OPENBRACKET"; +var CLOSEBRACKET = "CLOSEBRACKET"; +var OPENPAREN = "OPENPAREN"; +var CLOSEPAREN = "CLOSEPAREN"; +var OPENANGLEBRACKET = "OPENANGLEBRACKET"; +var CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET"; +var FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN"; +var FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN"; +var LEFTCORNERBRACKET = "LEFTCORNERBRACKET"; +var RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET"; +var LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET"; +var RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET"; +var FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN"; +var FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN"; +var AMPERSAND = "AMPERSAND"; +var APOSTROPHE = "APOSTROPHE"; +var ASTERISK = "ASTERISK"; +var AT = "AT"; +var BACKSLASH = "BACKSLASH"; +var BACKTICK = "BACKTICK"; +var CARET = "CARET"; +var COLON = "COLON"; +var COMMA = "COMMA"; +var DOLLAR = "DOLLAR"; +var DOT = "DOT"; +var EQUALS = "EQUALS"; +var EXCLAMATION = "EXCLAMATION"; +var HYPHEN = "HYPHEN"; +var PERCENT = "PERCENT"; +var PIPE = "PIPE"; +var PLUS = "PLUS"; +var POUND = "POUND"; +var QUERY = "QUERY"; +var QUOTE = "QUOTE"; +var FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT"; +var SEMI = "SEMI"; +var SLASH = "SLASH"; +var TILDE = "TILDE"; +var UNDERSCORE = "UNDERSCORE"; +var EMOJI$1 = "EMOJI"; +var SYM = "SYM"; +var tk = Object.freeze({ + __proto__: null, + ALPHANUMERICAL, + AMPERSAND, + APOSTROPHE, + ASCIINUMERICAL, + ASTERISK, + AT, + BACKSLASH, + BACKTICK, + CARET, + CLOSEANGLEBRACKET, + CLOSEBRACE, + CLOSEBRACKET, + CLOSEPAREN, + COLON, + COMMA, + DOLLAR, + DOT, + EMOJI: EMOJI$1, + EQUALS, + EXCLAMATION, + FULLWIDTHGREATERTHAN, + FULLWIDTHLEFTPAREN, + FULLWIDTHLESSTHAN, + FULLWIDTHMIDDLEDOT, + FULLWIDTHRIGHTPAREN, + HYPHEN, + LEFTCORNERBRACKET, + LEFTWHITECORNERBRACKET, + LOCALHOST, + NL, + NUM, + OPENANGLEBRACKET, + OPENBRACE, + OPENBRACKET, + OPENPAREN, + PERCENT, + PIPE, + PLUS, + POUND, + QUERY, + QUOTE, + RIGHTCORNERBRACKET, + RIGHTWHITECORNERBRACKET, + SCHEME, + SEMI, + SLASH, + SLASH_SCHEME, + SYM, + TILDE, + TLD, + UNDERSCORE, + UTLD, + UWORD, + WORD, + WS +}); +var ASCII_LETTER = /[a-z]/; +var LETTER = new RegExp("\\p{L}", "u"); +var EMOJI = new RegExp("\\p{Emoji}", "u"); +var EMOJI_VARIATION$1 = /\ufe0f/; +var DIGIT = /\d/; +var SPACE = /\s/; +var regexp = Object.freeze({ + __proto__: null, + ASCII_LETTER, + DIGIT, + EMOJI, + EMOJI_VARIATION: EMOJI_VARIATION$1, + LETTER, + SPACE +}); +var CR = "\r"; +var LF = "\n"; +var EMOJI_VARIATION = "️"; +var EMOJI_JOINER = "‍"; +var OBJECT_REPLACEMENT = ""; +var tlds = null; +var utlds = null; +function init$2(customSchemes = []) { + const groups = {}; + State.groups = groups; + const Start = new State(); + if (tlds == null) { + tlds = decodeTlds(encodedTlds); + } + if (utlds == null) { + utlds = decodeTlds(encodedUtlds); + } + tt(Start, "'", APOSTROPHE); + tt(Start, "{", OPENBRACE); + tt(Start, "}", CLOSEBRACE); + tt(Start, "[", OPENBRACKET); + tt(Start, "]", CLOSEBRACKET); + tt(Start, "(", OPENPAREN); + tt(Start, ")", CLOSEPAREN); + tt(Start, "<", OPENANGLEBRACKET); + tt(Start, ">", CLOSEANGLEBRACKET); + tt(Start, "(", FULLWIDTHLEFTPAREN); + tt(Start, ")", FULLWIDTHRIGHTPAREN); + tt(Start, "「", LEFTCORNERBRACKET); + tt(Start, "」", RIGHTCORNERBRACKET); + tt(Start, "『", LEFTWHITECORNERBRACKET); + tt(Start, "』", RIGHTWHITECORNERBRACKET); + tt(Start, "<", FULLWIDTHLESSTHAN); + tt(Start, ">", FULLWIDTHGREATERTHAN); + tt(Start, "&", AMPERSAND); + tt(Start, "*", ASTERISK); + tt(Start, "@", AT); + tt(Start, "`", BACKTICK); + tt(Start, "^", CARET); + tt(Start, ":", COLON); + tt(Start, ",", COMMA); + tt(Start, "$", DOLLAR); + tt(Start, ".", DOT); + tt(Start, "=", EQUALS); + tt(Start, "!", EXCLAMATION); + tt(Start, "-", HYPHEN); + tt(Start, "%", PERCENT); + tt(Start, "|", PIPE); + tt(Start, "+", PLUS); + tt(Start, "#", POUND); + tt(Start, "?", QUERY); + tt(Start, '"', QUOTE); + tt(Start, "/", SLASH); + tt(Start, ";", SEMI); + tt(Start, "~", TILDE); + tt(Start, "_", UNDERSCORE); + tt(Start, "\\", BACKSLASH); + tt(Start, "・", FULLWIDTHMIDDLEDOT); + const Num = tr(Start, DIGIT, NUM, { + [numeric]: true + }); + tr(Num, DIGIT, Num); + const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, { + [asciinumeric]: true + }); + const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, { + [alphanumeric]: true + }); + const Word = tr(Start, ASCII_LETTER, WORD, { + [ascii]: true + }); + tr(Word, DIGIT, Asciinumeric); + tr(Word, ASCII_LETTER, Word); + tr(Asciinumeric, DIGIT, Asciinumeric); + tr(Asciinumeric, ASCII_LETTER, Asciinumeric); + const UWord = tr(Start, LETTER, UWORD, { + [alpha]: true + }); + tr(UWord, ASCII_LETTER); + tr(UWord, DIGIT, Alphanumeric); + tr(UWord, LETTER, UWord); + tr(Alphanumeric, DIGIT, Alphanumeric); + tr(Alphanumeric, ASCII_LETTER); + tr(Alphanumeric, LETTER, Alphanumeric); + const Nl2 = tt(Start, LF, NL, { + [whitespace]: true + }); + const Cr = tt(Start, CR, WS, { + [whitespace]: true + }); + const Ws = tr(Start, SPACE, WS, { + [whitespace]: true + }); + tt(Start, OBJECT_REPLACEMENT, Ws); + tt(Cr, LF, Nl2); + tt(Cr, OBJECT_REPLACEMENT, Ws); + tr(Cr, SPACE, Ws); + tt(Ws, CR); + tt(Ws, LF); + tr(Ws, SPACE, Ws); + tt(Ws, OBJECT_REPLACEMENT, Ws); + const Emoji = tr(Start, EMOJI, EMOJI$1, { + [emoji]: true + }); + tt(Emoji, "#"); + tr(Emoji, EMOJI, Emoji); + tt(Emoji, EMOJI_VARIATION, Emoji); + const EmojiJoiner = tt(Emoji, EMOJI_JOINER); + tt(EmojiJoiner, "#"); + tr(EmojiJoiner, EMOJI, Emoji); + const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]]; + const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]]; + for (let i = 0; i < tlds.length; i++) { + fastts(Start, tlds[i], TLD, WORD, wordjr); + } + for (let i = 0; i < utlds.length; i++) { + fastts(Start, utlds[i], UTLD, UWORD, uwordjr); + } + addToGroups(TLD, { + tld: true, + ascii: true + }, groups); + addToGroups(UTLD, { + utld: true, + alpha: true + }, groups); + fastts(Start, "file", SCHEME, WORD, wordjr); + fastts(Start, "mailto", SCHEME, WORD, wordjr); + fastts(Start, "http", SLASH_SCHEME, WORD, wordjr); + fastts(Start, "https", SLASH_SCHEME, WORD, wordjr); + fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr); + fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr); + addToGroups(SCHEME, { + scheme: true, + ascii: true + }, groups); + addToGroups(SLASH_SCHEME, { + slashscheme: true, + ascii: true + }, groups); + customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1); + for (let i = 0; i < customSchemes.length; i++) { + const sch = customSchemes[i][0]; + const optionalSlashSlash = customSchemes[i][1]; + const flags = optionalSlashSlash ? { + [scheme]: true + } : { + [slashscheme]: true + }; + if (sch.indexOf("-") >= 0) { + flags[domain] = true; + } else if (!ASCII_LETTER.test(sch)) { + flags[numeric] = true; + } else if (DIGIT.test(sch)) { + flags[asciinumeric] = true; + } else { + flags[ascii] = true; + } + ts(Start, sch, sch, flags); + } + ts(Start, "localhost", LOCALHOST, { + ascii: true + }); + Start.jd = new State(SYM); + return { + start: Start, + tokens: Object.assign({ + groups + }, tk) + }; +} +function run$1(start, str) { + const iterable = stringToArray(str.replace(/[A-Z]/g, (c) => c.toLowerCase())); + const charCount = iterable.length; + const tokens = []; + let cursor = 0; + let charCursor = 0; + while (charCursor < charCount) { + let state = start; + let nextState = null; + let tokenLength = 0; + let latestAccepting = null; + let sinceAccepts = -1; + let charsSinceAccepts = -1; + while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) { + state = nextState; + if (state.accepts()) { + sinceAccepts = 0; + charsSinceAccepts = 0; + latestAccepting = state; + } else if (sinceAccepts >= 0) { + sinceAccepts += iterable[charCursor].length; + charsSinceAccepts++; + } + tokenLength += iterable[charCursor].length; + cursor += iterable[charCursor].length; + charCursor++; + } + cursor -= sinceAccepts; + charCursor -= charsSinceAccepts; + tokenLength -= sinceAccepts; + tokens.push({ + t: latestAccepting.t, + // token type/name + v: str.slice(cursor - tokenLength, cursor), + // string value + s: cursor - tokenLength, + // start index + e: cursor + // end index (excluding) + }); + } + return tokens; +} +function stringToArray(str) { + const result = []; + const len = str.length; + let index = 0; + while (index < len) { + let first = str.charCodeAt(index); + let second; + let char = first < 55296 || first > 56319 || index + 1 === len || (second = str.charCodeAt(index + 1)) < 56320 || second > 57343 ? str[index] : str.slice(index, index + 2); + result.push(char); + index += char.length; + } + return result; +} +function fastts(state, input, t, defaultt, jr) { + let next; + const len = input.length; + for (let i = 0; i < len - 1; i++) { + const char = input[i]; + if (state.j[char]) { + next = state.j[char]; + } else { + next = new State(defaultt); + next.jr = jr.slice(); + state.j[char] = next; + } + state = next; + } + next = new State(t); + next.jr = jr.slice(); + state.j[input[len - 1]] = next; + return next; +} +function decodeTlds(encoded) { + const words = []; + const stack = []; + let i = 0; + let digits = "0123456789"; + while (i < encoded.length) { + let popDigitCount = 0; + while (digits.indexOf(encoded[i + popDigitCount]) >= 0) { + popDigitCount++; + } + if (popDigitCount > 0) { + words.push(stack.join("")); + for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) { + stack.pop(); + } + i += popDigitCount; + } else { + stack.push(encoded[i]); + i++; + } + } + return words; +} +var defaults = { + defaultProtocol: "http", + events: null, + format: noop, + formatHref: noop, + nl2br: false, + tagName: "a", + target: null, + rel: null, + validate: true, + truncate: Infinity, + className: null, + attributes: null, + ignoreTags: [], + render: null +}; +function Options(opts, defaultRender = null) { + let o = Object.assign({}, defaults); + if (opts) { + o = Object.assign(o, opts instanceof Options ? opts.o : opts); + } + const ignoredTags = o.ignoreTags; + const uppercaseIgnoredTags = []; + for (let i = 0; i < ignoredTags.length; i++) { + uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase()); + } + this.o = o; + if (defaultRender) { + this.defaultRender = defaultRender; + } + this.ignoreTags = uppercaseIgnoredTags; +} +Options.prototype = { + o: defaults, + /** + * @type string[] + */ + ignoreTags: [], + /** + * @param {IntermediateRepresentation} ir + * @returns {any} + */ + defaultRender(ir) { + return ir; + }, + /** + * Returns true or false based on whether a token should be displayed as a + * link based on the user options. + * @param {MultiToken} token + * @returns {boolean} + */ + check(token) { + return this.get("validate", token.toString(), token); + }, + // Private methods + /** + * Resolve an option's value based on the value of the option and the given + * params. If operator and token are specified and the target option is + * callable, automatically calls the function with the given argument. + * @template {keyof Opts} K + * @param {K} key Name of option to use + * @param {string} [operator] will be passed to the target option if it's a + * function. If not specified, RAW function value gets returned + * @param {MultiToken} [token] The token from linkify.tokenize + * @returns {Opts[K] | any} + */ + get(key, operator, token) { + const isCallable = operator != null; + let option = this.o[key]; + if (!option) { + return option; + } + if (typeof option === "object") { + option = token.t in option ? option[token.t] : defaults[key]; + if (typeof option === "function" && isCallable) { + option = option(operator, token); + } + } else if (typeof option === "function" && isCallable) { + option = option(operator, token.t, token); + } + return option; + }, + /** + * @template {keyof Opts} L + * @param {L} key Name of options object to use + * @param {string} [operator] + * @param {MultiToken} [token] + * @returns {Opts[L] | any} + */ + getObj(key, operator, token) { + let obj = this.o[key]; + if (typeof obj === "function" && operator != null) { + obj = obj(operator, token.t, token); + } + return obj; + }, + /** + * Convert the given token to a rendered element that may be added to the + * calling-interface's DOM + * @param {MultiToken} token Token to render to an HTML element + * @returns {any} Render result; e.g., HTML string, DOM element, React + * Component, etc. + */ + render(token) { + const ir = token.render(this); + const renderFn = this.get("render", null, token) || this.defaultRender; + return renderFn(ir, token.t, token); + } +}; +function noop(val) { + return val; +} +var options = Object.freeze({ + __proto__: null, + Options, + defaults +}); +function MultiToken(value, tokens) { + this.t = "token"; + this.v = value; + this.tk = tokens; +} +MultiToken.prototype = { + isLink: false, + /** + * Return the string this token represents. + * @return {string} + */ + toString() { + return this.v; + }, + /** + * What should the value for this token be in the `href` HTML attribute? + * Returns the `.toString` value by default. + * @param {string} [scheme] + * @return {string} + */ + toHref(scheme2) { + return this.toString(); + }, + /** + * @param {Options} options Formatting options + * @returns {string} + */ + toFormattedString(options2) { + const val = this.toString(); + const truncate = options2.get("truncate", val, this); + const formatted = options2.get("format", val, this); + return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + "…" : formatted; + }, + /** + * + * @param {Options} options + * @returns {string} + */ + toFormattedHref(options2) { + return options2.get("formatHref", this.toHref(options2.get("defaultProtocol")), this); + }, + /** + * The start index of this token in the original input string + * @returns {number} + */ + startIndex() { + return this.tk[0].s; + }, + /** + * The end index of this token in the original input string (up to this + * index but not including it) + * @returns {number} + */ + endIndex() { + return this.tk[this.tk.length - 1].e; + }, + /** + Returns an object of relevant values for this token, which includes keys + * type - Kind of token ('url', 'email', etc.) + * value - Original text + * href - The value that should be added to the anchor tag's href + attribute + @method toObject + @param {string} [protocol] `'http'` by default + */ + toObject(protocol = defaults.defaultProtocol) { + return { + type: this.t, + value: this.toString(), + isLink: this.isLink, + href: this.toHref(protocol), + start: this.startIndex(), + end: this.endIndex() + }; + }, + /** + * + * @param {Options} options Formatting option + */ + toFormattedObject(options2) { + return { + type: this.t, + value: this.toFormattedString(options2), + isLink: this.isLink, + href: this.toFormattedHref(options2), + start: this.startIndex(), + end: this.endIndex() + }; + }, + /** + * Whether this token should be rendered as a link according to the given options + * @param {Options} options + * @returns {boolean} + */ + validate(options2) { + return options2.get("validate", this.toString(), this); + }, + /** + * Return an object that represents how this link should be rendered. + * @param {Options} options Formattinng options + */ + render(options2) { + const token = this; + const href = this.toHref(options2.get("defaultProtocol")); + const formattedHref = options2.get("formatHref", href, this); + const tagName = options2.get("tagName", href, token); + const content = this.toFormattedString(options2); + const attributes = {}; + const className = options2.get("className", href, token); + const target = options2.get("target", href, token); + const rel = options2.get("rel", href, token); + const attrs = options2.getObj("attributes", href, token); + const eventListeners = options2.getObj("events", href, token); + attributes.href = formattedHref; + if (className) { + attributes.class = className; + } + if (target) { + attributes.target = target; + } + if (rel) { + attributes.rel = rel; + } + if (attrs) { + Object.assign(attributes, attrs); + } + return { + tagName, + attributes, + content, + eventListeners + }; + } +}; +function createTokenClass(type, props) { + class Token extends MultiToken { + constructor(value, tokens) { + super(value, tokens); + this.t = type; + } + } + for (const p in props) { + Token.prototype[p] = props[p]; + } + Token.t = type; + return Token; +} +var Email = createTokenClass("email", { + isLink: true, + toHref() { + return "mailto:" + this.toString(); + } +}); +var Text = createTokenClass("text"); +var Nl = createTokenClass("nl"); +var Url = createTokenClass("url", { + isLink: true, + /** + Lowercases relevant parts of the domain and adds the protocol if + required. Note that this will not escape unsafe HTML characters in the + URL. + @param {string} [scheme] default scheme (e.g., 'https') + @return {string} the full href + */ + toHref(scheme2 = defaults.defaultProtocol) { + return this.hasProtocol() ? this.v : `${scheme2}://${this.v}`; + }, + /** + * Check whether this URL token has a protocol + * @return {boolean} + */ + hasProtocol() { + const tokens = this.tk; + return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON; + } +}); +var multi = Object.freeze({ + __proto__: null, + Base: MultiToken, + Email, + MultiToken, + Nl, + Text, + Url, + createTokenClass +}); +var makeState = (arg) => new State(arg); +function init$1({ + groups +}) { + const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]); + const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN]; + const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE]; + const Start = makeState(); + const Localpart = tt(Start, TILDE); + ta(Localpart, localpartAccepting, Localpart); + ta(Localpart, groups.domain, Localpart); + const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState(); + ta(Start, groups.domain, Domain); + ta(Start, groups.scheme, Scheme); + ta(Start, groups.slashscheme, SlashScheme); + ta(Domain, localpartAccepting, Localpart); + ta(Domain, groups.domain, Domain); + const LocalpartAt = tt(Domain, AT); + tt(Localpart, AT, LocalpartAt); + tt(Scheme, AT, LocalpartAt); + tt(SlashScheme, AT, LocalpartAt); + const LocalpartDot = tt(Localpart, DOT); + ta(LocalpartDot, localpartAccepting, Localpart); + ta(LocalpartDot, groups.domain, Localpart); + const EmailDomain = makeState(); + ta(LocalpartAt, groups.domain, EmailDomain); + ta(EmailDomain, groups.domain, EmailDomain); + const EmailDomainDot = tt(EmailDomain, DOT); + ta(EmailDomainDot, groups.domain, EmailDomain); + const Email$1 = makeState(Email); + ta(EmailDomainDot, groups.tld, Email$1); + ta(EmailDomainDot, groups.utld, Email$1); + tt(LocalpartAt, LOCALHOST, Email$1); + const EmailDomainHyphen = tt(EmailDomain, HYPHEN); + tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen); + ta(EmailDomainHyphen, groups.domain, EmailDomain); + ta(Email$1, groups.domain, EmailDomain); + tt(Email$1, DOT, EmailDomainDot); + tt(Email$1, HYPHEN, EmailDomainHyphen); + const EmailColon = tt(Email$1, COLON); + ta(EmailColon, groups.numeric, Email); + const DomainHyphen = tt(Domain, HYPHEN); + const DomainDot = tt(Domain, DOT); + tt(DomainHyphen, HYPHEN, DomainHyphen); + ta(DomainHyphen, groups.domain, Domain); + ta(DomainDot, localpartAccepting, Localpart); + ta(DomainDot, groups.domain, Domain); + const DomainDotTld = makeState(Url); + ta(DomainDot, groups.tld, DomainDotTld); + ta(DomainDot, groups.utld, DomainDotTld); + ta(DomainDotTld, groups.domain, Domain); + ta(DomainDotTld, localpartAccepting, Localpart); + tt(DomainDotTld, DOT, DomainDot); + tt(DomainDotTld, HYPHEN, DomainHyphen); + tt(DomainDotTld, AT, LocalpartAt); + const DomainDotTldColon = tt(DomainDotTld, COLON); + const DomainDotTldColonPort = makeState(Url); + ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort); + const Url$1 = makeState(Url); + const UrlNonaccept = makeState(); + ta(Url$1, qsAccepting, Url$1); + ta(Url$1, qsNonAccepting, UrlNonaccept); + ta(UrlNonaccept, qsAccepting, Url$1); + ta(UrlNonaccept, qsNonAccepting, UrlNonaccept); + tt(DomainDotTld, SLASH, Url$1); + tt(DomainDotTldColonPort, SLASH, Url$1); + const SchemeColon = tt(Scheme, COLON); + const SlashSchemeColon = tt(SlashScheme, COLON); + const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH); + const UriPrefix = tt(SlashSchemeColonSlash, SLASH); + ta(Scheme, groups.domain, Domain); + tt(Scheme, DOT, DomainDot); + tt(Scheme, HYPHEN, DomainHyphen); + ta(SlashScheme, groups.domain, Domain); + tt(SlashScheme, DOT, DomainDot); + tt(SlashScheme, HYPHEN, DomainHyphen); + ta(SchemeColon, groups.domain, Url$1); + tt(SchemeColon, SLASH, Url$1); + tt(SchemeColon, QUERY, Url$1); + ta(UriPrefix, groups.domain, Url$1); + ta(UriPrefix, qsAccepting, Url$1); + tt(UriPrefix, SLASH, Url$1); + const bracketPairs = [ + [OPENBRACE, CLOSEBRACE], + // {} + [OPENBRACKET, CLOSEBRACKET], + // [] + [OPENPAREN, CLOSEPAREN], + // () + [OPENANGLEBRACKET, CLOSEANGLEBRACKET], + // <> + [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN], + // () + [LEFTCORNERBRACKET, RIGHTCORNERBRACKET], + // 「」 + [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET], + // 『』 + [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] + // <> + ]; + for (let i = 0; i < bracketPairs.length; i++) { + const [OPEN, CLOSE] = bracketPairs[i]; + const UrlOpen = tt(Url$1, OPEN); + tt(UrlNonaccept, OPEN, UrlOpen); + tt(UrlOpen, CLOSE, Url$1); + const UrlOpenQ = makeState(Url); + ta(UrlOpen, qsAccepting, UrlOpenQ); + const UrlOpenSyms = makeState(); + ta(UrlOpen, qsNonAccepting); + ta(UrlOpenQ, qsAccepting, UrlOpenQ); + ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms); + ta(UrlOpenSyms, qsAccepting, UrlOpenQ); + ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms); + tt(UrlOpenQ, CLOSE, Url$1); + tt(UrlOpenSyms, CLOSE, Url$1); + } + tt(Start, LOCALHOST, DomainDotTld); + tt(Start, NL, Nl); + return { + start: Start, + tokens: tk + }; +} +function run(start, input, tokens) { + let len = tokens.length; + let cursor = 0; + let multis = []; + let textTokens = []; + while (cursor < len) { + let state = start; + let secondState = null; + let nextState = null; + let multiLength = 0; + let latestAccepting = null; + let sinceAccepts = -1; + while (cursor < len && !(secondState = state.go(tokens[cursor].t))) { + textTokens.push(tokens[cursor++]); + } + while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) { + secondState = null; + state = nextState; + if (state.accepts()) { + sinceAccepts = 0; + latestAccepting = state; + } else if (sinceAccepts >= 0) { + sinceAccepts++; + } + cursor++; + multiLength++; + } + if (sinceAccepts < 0) { + cursor -= multiLength; + if (cursor < len) { + textTokens.push(tokens[cursor]); + cursor++; + } + } else { + if (textTokens.length > 0) { + multis.push(initMultiToken(Text, input, textTokens)); + textTokens = []; + } + cursor -= sinceAccepts; + multiLength -= sinceAccepts; + const Multi = latestAccepting.t; + const subtokens = tokens.slice(cursor - multiLength, cursor); + multis.push(initMultiToken(Multi, input, subtokens)); + } + } + if (textTokens.length > 0) { + multis.push(initMultiToken(Text, input, textTokens)); + } + return multis; +} +function initMultiToken(Multi, input, tokens) { + const startIdx = tokens[0].s; + const endIdx = tokens[tokens.length - 1].e; + const value = input.slice(startIdx, endIdx); + return new Multi(value, tokens); +} +var warn = typeof console !== "undefined" && console && console.warn || (() => { +}); +var warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time."; +var INIT = { + scanner: null, + parser: null, + tokenQueue: [], + pluginQueue: [], + customSchemes: [], + initialized: false +}; +function reset() { + State.groups = {}; + INIT.scanner = null; + INIT.parser = null; + INIT.tokenQueue = []; + INIT.pluginQueue = []; + INIT.customSchemes = []; + INIT.initialized = false; + return INIT; +} +function registerCustomProtocol(scheme2, optionalSlashSlash = false) { + if (INIT.initialized) { + warn(`linkifyjs: already initialized - will not register custom scheme "${scheme2}" ${warnAdvice}`); + } + if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme2)) { + throw new Error(`linkifyjs: incorrect scheme format. +1. Must only contain digits, lowercase ASCII letters or "-" +2. Cannot start or end with "-" +3. "-" cannot repeat`); + } + INIT.customSchemes.push([scheme2, optionalSlashSlash]); +} +function init() { + INIT.scanner = init$2(INIT.customSchemes); + for (let i = 0; i < INIT.tokenQueue.length; i++) { + INIT.tokenQueue[i][1]({ + scanner: INIT.scanner + }); + } + INIT.parser = init$1(INIT.scanner.tokens); + for (let i = 0; i < INIT.pluginQueue.length; i++) { + INIT.pluginQueue[i][1]({ + scanner: INIT.scanner, + parser: INIT.parser + }); + } + INIT.initialized = true; + return INIT; +} +function tokenize(str) { + if (!INIT.initialized) { + init(); + } + return run(INIT.parser.start, str, run$1(INIT.scanner.start, str)); +} +tokenize.scan = run$1; +function find(str, type = null, opts = null) { + if (type && typeof type === "object") { + if (opts) { + throw Error(`linkifyjs: Invalid link type ${type}; must be a string`); + } + opts = type; + type = null; + } + const options2 = new Options(opts); + const tokens = tokenize(str); + const filtered = []; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.isLink && (!type || token.t === type) && options2.check(token)) { + filtered.push(token.toFormattedObject(options2)); + } + } + return filtered; +} + +// node_modules/@tiptap/extension-link/dist/index.js +var UNICODE_WHITESPACE_PATTERN = "[\0-   ᠎ -\u2029  ]"; +var UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN); +var UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`); +var UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, "g"); +function isValidLinkStructure(tokens) { + if (tokens.length === 1) { + return tokens[0].isLink; + } + if (tokens.length === 3 && tokens[1].isLink) { + return ["()", "[]"].includes(tokens[0].value + tokens[2].value); + } + return false; +} +function autolink(options2) { + return new Plugin({ + key: new PluginKey("autolink"), + appendTransaction: (transactions, oldState, newState) => { + const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); + const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink")); + if (!docChanges || preventAutolink) { + return; + } + const { tr: tr2 } = newState; + const transform = combineTransactionSteps(oldState.doc, [...transactions]); + const changes = getChangedRanges(transform); + changes.forEach(({ newRange }) => { + const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node) => node.isTextblock); + let textBlock; + let textBeforeWhitespace; + if (nodesInChangedRanges.length > 1) { + textBlock = nodesInChangedRanges[0]; + textBeforeWhitespace = newState.doc.textBetween( + textBlock.pos, + textBlock.pos + textBlock.node.nodeSize, + void 0, + " " + ); + } else if (nodesInChangedRanges.length) { + const endText = newState.doc.textBetween(newRange.from, newRange.to, " ", " "); + if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) { + return; + } + textBlock = nodesInChangedRanges[0]; + textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " "); + } + if (textBlock && textBeforeWhitespace) { + const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean); + if (wordsBeforeWhitespace.length <= 0) { + return false; + } + const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]; + const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace); + if (!lastWordBeforeSpace) { + return false; + } + const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t) => t.toObject(options2.defaultProtocol)); + if (!isValidLinkStructure(linksBeforeSpace)) { + return false; + } + linksBeforeSpace.filter((link) => link.isLink).map((link) => ({ + ...link, + from: lastWordAndBlockOffset + link.start + 1, + to: lastWordAndBlockOffset + link.end + 1 + })).filter((link) => { + if (!newState.schema.marks.code) { + return true; + } + return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code); + }).filter((link) => options2.validate(link.value)).filter((link) => options2.shouldAutoLink(link.value)).forEach((link) => { + if (getMarksBetween(link.from, link.to, newState.doc).some((item) => item.mark.type === options2.type)) { + return; + } + tr2.addMark( + link.from, + link.to, + options2.type.create({ + href: link.href + }) + ); + }); + } + }); + if (!tr2.steps.length) { + return; + } + return tr2; + } + }); +} +function clickHandler(options2) { + return new Plugin({ + key: new PluginKey("handleClickLink"), + props: { + handleClick: (view, pos, event) => { + var _a, _b; + if (event.button !== 0) { + return false; + } + if (!view.editable) { + return false; + } + let link = null; + if (event.target instanceof HTMLAnchorElement) { + link = event.target; + } else { + const target = event.target; + if (!target) { + return false; + } + const root = options2.editor.view.dom; + link = target.closest("a"); + if (link && !root.contains(link)) { + link = null; + } + } + if (!link) { + return false; + } + let handled = false; + if (options2.enableClickSelection) { + const commandResult = options2.editor.commands.extendMarkRange(options2.type.name); + handled = commandResult; + } + if (options2.openOnClick) { + const attrs = getAttributes(view.state, options2.type.name); + const href = (_a = link.href) != null ? _a : attrs.href; + const target = (_b = link.target) != null ? _b : attrs.target; + if (href) { + window.open(href, target); + handled = true; + } + } + return handled; + } + } + }); +} +function pasteHandler(options2) { + return new Plugin({ + key: new PluginKey("handlePasteLink"), + props: { + handlePaste: (view, _event, slice) => { + const { shouldAutoLink } = options2; + const { state } = view; + const { selection } = state; + const { empty } = selection; + if (empty) { + return false; + } + let textContent = ""; + slice.content.forEach((node) => { + textContent += node.textContent; + }); + const link = find(textContent, { defaultProtocol: options2.defaultProtocol }).find( + (item) => item.isLink && item.value === textContent + ); + if (!textContent || !link || shouldAutoLink !== void 0 && !shouldAutoLink(link.value)) { + return false; + } + return options2.editor.commands.setMark(options2.type, { + href: link.href + }); + } + } + }); +} +var pasteRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi; +function isAllowedUri(uri, protocols) { + const allowedProtocols = ["http", "https", "ftp", "ftps", "mailto", "tel", "callto", "sms", "cid", "xmpp"]; + if (protocols) { + protocols.forEach((protocol) => { + const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme; + if (nextProtocol) { + allowedProtocols.push(nextProtocol); + } + }); + } + return !uri || uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, "").match( + new RegExp( + // eslint-disable-next-line no-useless-escape + `^(?:(?:${allowedProtocols.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`, + "i" + ) + ); +} +var Link = Mark.create({ + name: "link", + priority: 1e3, + keepOnSplit: false, + exitable: true, + onCreate() { + if (this.options.validate && !this.options.shouldAutoLink) { + this.options.shouldAutoLink = this.options.validate; + console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead."); + } + this.options.protocols.forEach((protocol) => { + if (typeof protocol === "string") { + registerCustomProtocol(protocol); + return; + } + registerCustomProtocol(protocol.scheme, protocol.optionalSlashes); + }); + }, + onDestroy() { + reset(); + }, + inclusive() { + return this.options.autolink; + }, + addOptions() { + return { + openOnClick: true, + enableClickSelection: false, + linkOnPaste: true, + autolink: true, + protocols: [], + defaultProtocol: "http", + HTMLAttributes: { + target: "_blank", + rel: "noopener noreferrer nofollow", + class: null + }, + isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols), + validate: (url) => !!url, + shouldAutoLink: (url) => { + const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(url); + const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url); + if (hasProtocol || hasMaybeProtocol && !url.includes("@")) { + return true; + } + const urlWithoutUserinfo = url.includes("@") ? url.split("@").pop() : url; + const hostname = urlWithoutUserinfo.split(/[/?#:]/)[0]; + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) { + return false; + } + if (!/\./.test(hostname)) { + return false; + } + return true; + } + }; + }, + addAttributes() { + return { + href: { + default: null, + parseHTML(element) { + return element.getAttribute("href"); + } + }, + target: { + default: this.options.HTMLAttributes.target + }, + rel: { + default: this.options.HTMLAttributes.rel + }, + class: { + default: this.options.HTMLAttributes.class + }, + title: { + default: null + } + }; + }, + parseHTML() { + return [ + { + tag: "a[href]", + getAttrs: (dom) => { + const href = dom.getAttribute("href"); + if (!href || !this.options.isAllowedUri(href, { + defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return false; + } + return null; + } + } + ]; + }, + renderHTML({ HTMLAttributes }) { + if (!this.options.isAllowedUri(HTMLAttributes.href, { + defaultValidate: (href) => !!isAllowedUri(href, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return ["a", mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: "" }), 0]; + } + return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; + }, + markdownTokenName: "link", + parseMarkdown: (token, helpers) => { + return helpers.applyMark("link", helpers.parseInline(token.tokens || []), { + href: token.href, + title: token.title || null + }); + }, + renderMarkdown: (node, h) => { + var _a, _b, _c, _d; + const href = (_b = (_a = node.attrs) == null ? void 0 : _a.href) != null ? _b : ""; + const title = (_d = (_c = node.attrs) == null ? void 0 : _c.title) != null ? _d : ""; + const text = h.renderChildren(node); + return title ? `[${text}](${href} "${title}")` : `[${text}](${href})`; + }, + addCommands() { + return { + setLink: (attributes) => ({ chain }) => { + const { href } = attributes; + if (!this.options.isAllowedUri(href, { + defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return false; + } + return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run(); + }, + toggleLink: (attributes) => ({ chain }) => { + const { href } = attributes || {}; + if (href && !this.options.isAllowedUri(href, { + defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), + protocols: this.options.protocols, + defaultProtocol: this.options.defaultProtocol + })) { + return false; + } + return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); + }, + unsetLink: () => ({ chain }) => { + return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); + } + }; + }, + addPasteRules() { + return [ + markPasteRule({ + find: (text) => { + const foundLinks = []; + if (text) { + const { protocols, defaultProtocol } = this.options; + const links = find(text).filter( + (item) => item.isLink && this.options.isAllowedUri(item.value, { + defaultValidate: (href) => !!isAllowedUri(href, protocols), + protocols, + defaultProtocol + }) + ); + if (links.length) { + links.forEach((link) => { + if (!this.options.shouldAutoLink(link.value)) { + return; + } + foundLinks.push({ + text: link.value, + data: { + href: link.href + }, + index: link.start + }); + }); + } + } + return foundLinks; + }, + type: this.type, + getAttributes: (match) => { + var _a; + return { + href: (_a = match.data) == null ? void 0 : _a.href + }; + } + }) + ]; + }, + addProseMirrorPlugins() { + const plugins = []; + const { protocols, defaultProtocol } = this.options; + if (this.options.autolink) { + plugins.push( + autolink({ + type: this.type, + defaultProtocol: this.options.defaultProtocol, + validate: (url) => this.options.isAllowedUri(url, { + defaultValidate: (href) => !!isAllowedUri(href, protocols), + protocols, + defaultProtocol + }), + shouldAutoLink: this.options.shouldAutoLink + }) + ); + } + plugins.push( + clickHandler({ + type: this.type, + editor: this.editor, + openOnClick: this.options.openOnClick === "whenNotEditable" ? true : this.options.openOnClick, + enableClickSelection: this.options.enableClickSelection + }) + ); + if (this.options.linkOnPaste) { + plugins.push( + pasteHandler({ + editor: this.editor, + defaultProtocol: this.options.defaultProtocol, + type: this.type, + shouldAutoLink: this.options.shouldAutoLink + }) + ); + } + return plugins; + } +}); +var index_default = Link; + +export { + pasteRegex, + isAllowedUri, + Link, + index_default +}; +//# sourceMappingURL=chunk-MX7X7RGK.js.map diff --git a/frontend/node_modules/.vite/deps/chunk-MX7X7RGK.js.map b/frontend/node_modules/.vite/deps/chunk-MX7X7RGK.js.map new file mode 100644 index 00000000..cedeceeb --- /dev/null +++ b/frontend/node_modules/.vite/deps/chunk-MX7X7RGK.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../linkifyjs/dist/linkify.mjs", "../../@tiptap/extension-link/src/link.ts", "../../@tiptap/extension-link/src/helpers/autolink.ts", "../../@tiptap/extension-link/src/helpers/whitespace.ts", "../../@tiptap/extension-link/src/helpers/clickHandler.ts", "../../@tiptap/extension-link/src/helpers/pasteHandler.ts", "../../@tiptap/extension-link/src/index.ts"], + "sourcesContent": ["// THIS FILE IS AUTOMATICALLY GENERATED DO NOT EDIT DIRECTLY\n// See update-tlds.js for encoding/decoding format\n// https://data.iana.org/TLD/tlds-alpha-by-domain.txt\nconst encodedTlds = 'aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2';\n// Internationalized domain names containing non-ASCII\nconst encodedUtlds = 'ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2';\n\n/**\n * Finite State Machine generation utilities\n */\n\n/**\n * @template T\n * @typedef {{ [group: string]: T[] }} Collections\n */\n\n/**\n * @typedef {{ [group: string]: true }} Flags\n */\n\n// Keys in scanner Collections instances\nconst numeric = 'numeric';\nconst ascii = 'ascii';\nconst alpha = 'alpha';\nconst asciinumeric = 'asciinumeric';\nconst alphanumeric = 'alphanumeric';\nconst domain = 'domain';\nconst emoji = 'emoji';\nconst scheme = 'scheme';\nconst slashscheme = 'slashscheme';\nconst whitespace = 'whitespace';\n\n/**\n * @template T\n * @param {string} name\n * @param {Collections} groups to register in\n * @returns {T[]} Current list of tokens in the given collection\n */\nfunction registerGroup(name, groups) {\n if (!(name in groups)) {\n groups[name] = [];\n }\n return groups[name];\n}\n\n/**\n * @template T\n * @param {T} t token to add\n * @param {Collections} groups\n * @param {Flags} flags\n */\nfunction addToGroups(t, flags, groups) {\n if (flags[numeric]) {\n flags[asciinumeric] = true;\n flags[alphanumeric] = true;\n }\n if (flags[ascii]) {\n flags[asciinumeric] = true;\n flags[alpha] = true;\n }\n if (flags[asciinumeric]) {\n flags[alphanumeric] = true;\n }\n if (flags[alpha]) {\n flags[alphanumeric] = true;\n }\n if (flags[alphanumeric]) {\n flags[domain] = true;\n }\n if (flags[emoji]) {\n flags[domain] = true;\n }\n for (const k in flags) {\n const group = registerGroup(k, groups);\n if (group.indexOf(t) < 0) {\n group.push(t);\n }\n }\n}\n\n/**\n * @template T\n * @param {T} t token to check\n * @param {Collections} groups\n * @returns {Flags} group flags that contain this token\n */\nfunction flagsForToken(t, groups) {\n const result = {};\n for (const c in groups) {\n if (groups[c].indexOf(t) >= 0) {\n result[c] = true;\n }\n }\n return result;\n}\n\n/**\n * @template T\n * @typedef {null | T } Transition\n */\n\n/**\n * Define a basic state machine state. j is the list of character transitions,\n * jr is the list of regex-match transitions, jd is the default state to\n * transition to t is the accepting token type, if any. If this is the terminal\n * state, then it does not emit a token.\n *\n * The template type T represents the type of the token this state accepts. This\n * should be a string (such as of the token exports in `text.js`) or a\n * MultiToken subclass (from `multi.js`)\n *\n * @template T\n * @param {T} [token] Token that this state emits\n */\nfunction State(token = null) {\n // this.n = null; // DEBUG: State name\n /** @type {{ [input: string]: State }} j */\n this.j = {}; // IMPLEMENTATION 1\n // this.j = []; // IMPLEMENTATION 2\n /** @type {[RegExp, State][]} jr */\n this.jr = [];\n /** @type {?State} jd */\n this.jd = null;\n /** @type {?T} t */\n this.t = token;\n}\n\n/**\n * Scanner token groups\n * @type Collections\n */\nState.groups = {};\nState.prototype = {\n accepts() {\n return !!this.t;\n },\n /**\n * Follow an existing transition from the given input to the next state.\n * Does not mutate.\n * @param {string} input character or token type to transition on\n * @returns {?State} the next state, if any\n */\n go(input) {\n const state = this;\n const nextState = state.j[input];\n if (nextState) {\n return nextState;\n }\n for (let i = 0; i < state.jr.length; i++) {\n const regex = state.jr[i][0];\n const nextState = state.jr[i][1]; // note: might be empty to prevent default jump\n if (nextState && regex.test(input)) {\n return nextState;\n }\n }\n // Nowhere left to jump! Return default, if any\n return state.jd;\n },\n /**\n * Whether the state has a transition for the given input. Set the second\n * argument to true to only look for an exact match (and not a default or\n * regular-expression-based transition)\n * @param {string} input\n * @param {boolean} exactOnly\n */\n has(input, exactOnly = false) {\n return exactOnly ? input in this.j : !!this.go(input);\n },\n /**\n * Short for \"transition all\"; create a transition from the array of items\n * in the given list to the same final resulting state.\n * @param {string | string[]} inputs Group of inputs to transition on\n * @param {Transition | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of token groups\n */\n ta(inputs, next, flags, groups) {\n for (let i = 0; i < inputs.length; i++) {\n this.tt(inputs[i], next, flags, groups);\n }\n },\n /**\n * Short for \"take regexp transition\"; defines a transition for this state\n * when it encounters a token which matches the given regular expression\n * @param {RegExp} regexp Regular expression transition (populate first)\n * @param {T | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of token groups\n * @returns {State} taken after the given input\n */\n tr(regexp, next, flags, groups) {\n groups = groups || State.groups;\n let nextState;\n if (next && next.j) {\n nextState = next;\n } else {\n // Token with maybe token groups\n nextState = new State(next);\n if (flags && groups) {\n addToGroups(next, flags, groups);\n }\n }\n this.jr.push([regexp, nextState]);\n return nextState;\n },\n /**\n * Short for \"take transitions\", will take as many sequential transitions as\n * the length of the given input and returns the\n * resulting final state.\n * @param {string | string[]} input\n * @param {T | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of token groups\n * @returns {State} taken after the given input\n */\n ts(input, next, flags, groups) {\n let state = this;\n const len = input.length;\n if (!len) {\n return state;\n }\n for (let i = 0; i < len - 1; i++) {\n state = state.tt(input[i]);\n }\n return state.tt(input[len - 1], next, flags, groups);\n },\n /**\n * Short for \"take transition\", this is a method for building/working with\n * state machines.\n *\n * If a state already exists for the given input, returns it.\n *\n * If a token is specified, that state will emit that token when reached by\n * the linkify engine.\n *\n * If no state exists, it will be initialized with some default transitions\n * that resemble existing default transitions.\n *\n * If a state is given for the second argument, that state will be\n * transitioned to on the given input regardless of what that input\n * previously did.\n *\n * Specify a token group flags to define groups that this token belongs to.\n * The token will be added to corresponding entires in the given groups\n * object.\n *\n * @param {string} input character, token type to transition on\n * @param {T | State} [next] Transition options\n * @param {Flags} [flags] Collections flags to add token to\n * @param {Collections} [groups] Master list of groups\n * @returns {State} taken after the given input\n */\n tt(input, next, flags, groups) {\n groups = groups || State.groups;\n const state = this;\n\n // Check if existing state given, just a basic transition\n if (next && next.j) {\n state.j[input] = next;\n return next;\n }\n const t = next;\n\n // Take the transition with the usual default mechanisms and use that as\n // a template for creating the next state\n let nextState,\n templateState = state.go(input);\n if (templateState) {\n nextState = new State();\n Object.assign(nextState.j, templateState.j);\n nextState.jr.push.apply(nextState.jr, templateState.jr);\n nextState.jd = templateState.jd;\n nextState.t = templateState.t;\n } else {\n nextState = new State();\n }\n if (t) {\n // Ensure newly token is in the same groups as the old token\n if (groups) {\n if (nextState.t && typeof nextState.t === 'string') {\n const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags);\n addToGroups(t, allFlags, groups);\n } else if (flags) {\n addToGroups(t, flags, groups);\n }\n }\n nextState.t = t; // overwrite anything that was previously there\n }\n state.j[input] = nextState;\n return nextState;\n }\n};\n\n// Helper functions to improve minification (not exported outside linkifyjs module)\n\n/**\n * @template T\n * @param {State} state\n * @param {string | string[]} input\n * @param {Flags} [flags]\n * @param {Collections} [groups]\n */\nconst ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State} state\n * @param {RegExp} regexp\n * @param {T | State} [next]\n * @param {Flags} [flags]\n * @param {Collections} [groups]\n */\nconst tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups);\n\n/**\n * @template T\n * @param {State} state\n * @param {string | string[]} input\n * @param {T | State} [next]\n * @param {Flags} [flags]\n * @param {Collections} [groups]\n */\nconst ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups);\n\n/**\n * @template T\n * @param {State} state\n * @param {string} input\n * @param {T | State} [next]\n * @param {Collections} [groups]\n * @param {Flags} [flags]\n */\nconst tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups);\n\n/******************************************************************************\nText Tokens\nIdentifiers for token outputs from the regexp scanner\n******************************************************************************/\n\n// A valid web domain token\nconst WORD = 'WORD'; // only contains a-z\nconst UWORD = 'UWORD'; // contains letters other than a-z, used for IDN\nconst ASCIINUMERICAL = 'ASCIINUMERICAL'; // contains a-z, 0-9\nconst ALPHANUMERICAL = 'ALPHANUMERICAL'; // contains numbers and letters other than a-z, used for IDN\n\n// Special case of word\nconst LOCALHOST = 'LOCALHOST';\n\n// Valid top-level domain, special case of WORD (see tlds.js)\nconst TLD = 'TLD';\n\n// Valid IDN TLD, special case of UWORD (see tlds.js)\nconst UTLD = 'UTLD';\n\n// The scheme portion of a web URI protocol. Supported types include: `mailto`,\n// `file`, and user-defined custom protocols. Limited to schemes that contain\n// only letters\nconst SCHEME = 'SCHEME';\n\n// Similar to SCHEME, except makes distinction for schemes that must always be\n// followed by `://`, not just `:`. Supported types include `http`, `https`,\n// `ftp`, `ftps`\nconst SLASH_SCHEME = 'SLASH_SCHEME';\n\n// Any sequence of digits 0-9\nconst NUM = 'NUM';\n\n// Any number of consecutive whitespace characters that are not newline\nconst WS = 'WS';\n\n// New line (unix style)\nconst NL = 'NL'; // \\n\n\n// Opening/closing bracket classes\n// TODO: Rename OPEN -> LEFT and CLOSE -> RIGHT in v5 to fit with Unicode names\n// Also rename angle brackes to LESSTHAN and GREATER THAN\nconst OPENBRACE = 'OPENBRACE'; // {\nconst CLOSEBRACE = 'CLOSEBRACE'; // }\nconst OPENBRACKET = 'OPENBRACKET'; // [\nconst CLOSEBRACKET = 'CLOSEBRACKET'; // ]\nconst OPENPAREN = 'OPENPAREN'; // (\nconst CLOSEPAREN = 'CLOSEPAREN'; // )\nconst OPENANGLEBRACKET = 'OPENANGLEBRACKET'; // <\nconst CLOSEANGLEBRACKET = 'CLOSEANGLEBRACKET'; // >\nconst FULLWIDTHLEFTPAREN = 'FULLWIDTHLEFTPAREN'; // (\nconst FULLWIDTHRIGHTPAREN = 'FULLWIDTHRIGHTPAREN'; // )\nconst LEFTCORNERBRACKET = 'LEFTCORNERBRACKET'; // 「\nconst RIGHTCORNERBRACKET = 'RIGHTCORNERBRACKET'; // 」\nconst LEFTWHITECORNERBRACKET = 'LEFTWHITECORNERBRACKET'; // 『\nconst RIGHTWHITECORNERBRACKET = 'RIGHTWHITECORNERBRACKET'; // 』\nconst FULLWIDTHLESSTHAN = 'FULLWIDTHLESSTHAN'; // <\nconst FULLWIDTHGREATERTHAN = 'FULLWIDTHGREATERTHAN'; // >\n\n// Various symbols\nconst AMPERSAND = 'AMPERSAND'; // &\nconst APOSTROPHE = 'APOSTROPHE'; // '\nconst ASTERISK = 'ASTERISK'; // *\nconst AT = 'AT'; // @\nconst BACKSLASH = 'BACKSLASH'; // \\\nconst BACKTICK = 'BACKTICK'; // `\nconst CARET = 'CARET'; // ^\nconst COLON = 'COLON'; // :\nconst COMMA = 'COMMA'; // ,\nconst DOLLAR = 'DOLLAR'; // $\nconst DOT = 'DOT'; // .\nconst EQUALS = 'EQUALS'; // =\nconst EXCLAMATION = 'EXCLAMATION'; // !\nconst HYPHEN = 'HYPHEN'; // -\nconst PERCENT = 'PERCENT'; // %\nconst PIPE = 'PIPE'; // |\nconst PLUS = 'PLUS'; // +\nconst POUND = 'POUND'; // #\nconst QUERY = 'QUERY'; // ?\nconst QUOTE = 'QUOTE'; // \"\nconst FULLWIDTHMIDDLEDOT = 'FULLWIDTHMIDDLEDOT'; // ・\n\nconst SEMI = 'SEMI'; // ;\nconst SLASH = 'SLASH'; // /\nconst TILDE = 'TILDE'; // ~\nconst UNDERSCORE = 'UNDERSCORE'; // _\n\n// Emoji symbol\nconst EMOJI$1 = 'EMOJI';\n\n// Default token - anything that is not one of the above\nconst SYM = 'SYM';\n\nvar tk = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tALPHANUMERICAL: ALPHANUMERICAL,\n\tAMPERSAND: AMPERSAND,\n\tAPOSTROPHE: APOSTROPHE,\n\tASCIINUMERICAL: ASCIINUMERICAL,\n\tASTERISK: ASTERISK,\n\tAT: AT,\n\tBACKSLASH: BACKSLASH,\n\tBACKTICK: BACKTICK,\n\tCARET: CARET,\n\tCLOSEANGLEBRACKET: CLOSEANGLEBRACKET,\n\tCLOSEBRACE: CLOSEBRACE,\n\tCLOSEBRACKET: CLOSEBRACKET,\n\tCLOSEPAREN: CLOSEPAREN,\n\tCOLON: COLON,\n\tCOMMA: COMMA,\n\tDOLLAR: DOLLAR,\n\tDOT: DOT,\n\tEMOJI: EMOJI$1,\n\tEQUALS: EQUALS,\n\tEXCLAMATION: EXCLAMATION,\n\tFULLWIDTHGREATERTHAN: FULLWIDTHGREATERTHAN,\n\tFULLWIDTHLEFTPAREN: FULLWIDTHLEFTPAREN,\n\tFULLWIDTHLESSTHAN: FULLWIDTHLESSTHAN,\n\tFULLWIDTHMIDDLEDOT: FULLWIDTHMIDDLEDOT,\n\tFULLWIDTHRIGHTPAREN: FULLWIDTHRIGHTPAREN,\n\tHYPHEN: HYPHEN,\n\tLEFTCORNERBRACKET: LEFTCORNERBRACKET,\n\tLEFTWHITECORNERBRACKET: LEFTWHITECORNERBRACKET,\n\tLOCALHOST: LOCALHOST,\n\tNL: NL,\n\tNUM: NUM,\n\tOPENANGLEBRACKET: OPENANGLEBRACKET,\n\tOPENBRACE: OPENBRACE,\n\tOPENBRACKET: OPENBRACKET,\n\tOPENPAREN: OPENPAREN,\n\tPERCENT: PERCENT,\n\tPIPE: PIPE,\n\tPLUS: PLUS,\n\tPOUND: POUND,\n\tQUERY: QUERY,\n\tQUOTE: QUOTE,\n\tRIGHTCORNERBRACKET: RIGHTCORNERBRACKET,\n\tRIGHTWHITECORNERBRACKET: RIGHTWHITECORNERBRACKET,\n\tSCHEME: SCHEME,\n\tSEMI: SEMI,\n\tSLASH: SLASH,\n\tSLASH_SCHEME: SLASH_SCHEME,\n\tSYM: SYM,\n\tTILDE: TILDE,\n\tTLD: TLD,\n\tUNDERSCORE: UNDERSCORE,\n\tUTLD: UTLD,\n\tUWORD: UWORD,\n\tWORD: WORD,\n\tWS: WS\n});\n\n// Note that these two Unicode ones expand into a really big one with Babel\nconst ASCII_LETTER = /[a-z]/;\nconst LETTER = /\\p{L}/u; // Any Unicode character with letter data type\nconst EMOJI = /\\p{Emoji}/u; // Any Unicode emoji character\nconst EMOJI_VARIATION$1 = /\\ufe0f/;\nconst DIGIT = /\\d/;\nconst SPACE = /\\s/;\n\nvar regexp = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tASCII_LETTER: ASCII_LETTER,\n\tDIGIT: DIGIT,\n\tEMOJI: EMOJI,\n\tEMOJI_VARIATION: EMOJI_VARIATION$1,\n\tLETTER: LETTER,\n\tSPACE: SPACE\n});\n\n/**\n\tThe scanner provides an interface that takes a string of text as input, and\n\toutputs an array of tokens instances that can be used for easy URL parsing.\n*/\n\nconst CR = '\\r'; // carriage-return character\nconst LF = '\\n'; // line-feed character\nconst EMOJI_VARIATION = '\\ufe0f'; // Variation selector, follows heart and others\nconst EMOJI_JOINER = '\\u200d'; // zero-width joiner\nconst OBJECT_REPLACEMENT = '\\ufffc'; // whitespace placeholder that sometimes appears in rich text editors\n\nlet tlds = null,\n utlds = null; // don't change so only have to be computed once\n\n/**\n * Scanner output token:\n * - `t` is the token name (e.g., 'NUM', 'EMOJI', 'TLD')\n * - `v` is the value of the token (e.g., '123', '❤️', 'com')\n * - `s` is the start index of the token in the original string\n * - `e` is the end index of the token in the original string\n * @typedef {{t: string, v: string, s: number, e: number}} Token\n */\n\n/**\n * @template T\n * @typedef {{ [collection: string]: T[] }} Collections\n */\n\n/**\n * Initialize the scanner character-based state machine for the given start\n * state\n * @param {[string, boolean][]} customSchemes List of custom schemes, where each\n * item is a length-2 tuple with the first element set to the string scheme, and\n * the second element set to `true` if the `://` after the scheme is optional\n */\nfunction init$2(customSchemes = []) {\n // Frequently used states (name argument removed during minification)\n /** @type Collections */\n const groups = {}; // of tokens\n State.groups = groups;\n /** @type State */\n const Start = new State();\n if (tlds == null) {\n tlds = decodeTlds(encodedTlds);\n }\n if (utlds == null) {\n utlds = decodeTlds(encodedUtlds);\n }\n\n // States for special URL symbols that accept immediately after start\n tt(Start, \"'\", APOSTROPHE);\n tt(Start, '{', OPENBRACE);\n tt(Start, '}', CLOSEBRACE);\n tt(Start, '[', OPENBRACKET);\n tt(Start, ']', CLOSEBRACKET);\n tt(Start, '(', OPENPAREN);\n tt(Start, ')', CLOSEPAREN);\n tt(Start, '<', OPENANGLEBRACKET);\n tt(Start, '>', CLOSEANGLEBRACKET);\n tt(Start, '(', FULLWIDTHLEFTPAREN);\n tt(Start, ')', FULLWIDTHRIGHTPAREN);\n tt(Start, '「', LEFTCORNERBRACKET);\n tt(Start, '」', RIGHTCORNERBRACKET);\n tt(Start, '『', LEFTWHITECORNERBRACKET);\n tt(Start, '』', RIGHTWHITECORNERBRACKET);\n tt(Start, '<', FULLWIDTHLESSTHAN);\n tt(Start, '>', FULLWIDTHGREATERTHAN);\n tt(Start, '&', AMPERSAND);\n tt(Start, '*', ASTERISK);\n tt(Start, '@', AT);\n tt(Start, '`', BACKTICK);\n tt(Start, '^', CARET);\n tt(Start, ':', COLON);\n tt(Start, ',', COMMA);\n tt(Start, '$', DOLLAR);\n tt(Start, '.', DOT);\n tt(Start, '=', EQUALS);\n tt(Start, '!', EXCLAMATION);\n tt(Start, '-', HYPHEN);\n tt(Start, '%', PERCENT);\n tt(Start, '|', PIPE);\n tt(Start, '+', PLUS);\n tt(Start, '#', POUND);\n tt(Start, '?', QUERY);\n tt(Start, '\"', QUOTE);\n tt(Start, '/', SLASH);\n tt(Start, ';', SEMI);\n tt(Start, '~', TILDE);\n tt(Start, '_', UNDERSCORE);\n tt(Start, '\\\\', BACKSLASH);\n tt(Start, '・', FULLWIDTHMIDDLEDOT);\n const Num = tr(Start, DIGIT, NUM, {\n [numeric]: true\n });\n tr(Num, DIGIT, Num);\n const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, {\n [asciinumeric]: true\n });\n const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, {\n [alphanumeric]: true\n });\n\n // State which emits a word token\n const Word = tr(Start, ASCII_LETTER, WORD, {\n [ascii]: true\n });\n tr(Word, DIGIT, Asciinumeric);\n tr(Word, ASCII_LETTER, Word);\n tr(Asciinumeric, DIGIT, Asciinumeric);\n tr(Asciinumeric, ASCII_LETTER, Asciinumeric);\n\n // Same as previous, but specific to non-fsm.ascii alphabet words\n const UWord = tr(Start, LETTER, UWORD, {\n [alpha]: true\n });\n tr(UWord, ASCII_LETTER); // Non-accepting\n tr(UWord, DIGIT, Alphanumeric);\n tr(UWord, LETTER, UWord);\n tr(Alphanumeric, DIGIT, Alphanumeric);\n tr(Alphanumeric, ASCII_LETTER); // Non-accepting\n tr(Alphanumeric, LETTER, Alphanumeric); // Non-accepting\n\n // Whitespace jumps\n // Tokens of only non-newline whitespace are arbitrarily long\n // If any whitespace except newline, more whitespace!\n const Nl = tt(Start, LF, NL, {\n [whitespace]: true\n });\n const Cr = tt(Start, CR, WS, {\n [whitespace]: true\n });\n const Ws = tr(Start, SPACE, WS, {\n [whitespace]: true\n });\n tt(Start, OBJECT_REPLACEMENT, Ws);\n tt(Cr, LF, Nl); // \\r\\n\n tt(Cr, OBJECT_REPLACEMENT, Ws);\n tr(Cr, SPACE, Ws);\n tt(Ws, CR); // non-accepting state to avoid mixing whitespaces\n tt(Ws, LF); // non-accepting state to avoid mixing whitespaces\n tr(Ws, SPACE, Ws);\n tt(Ws, OBJECT_REPLACEMENT, Ws);\n\n // Emoji tokens. They are not grouped by the scanner except in cases where a\n // zero-width joiner is present\n const Emoji = tr(Start, EMOJI, EMOJI$1, {\n [emoji]: true\n });\n tt(Emoji, '#'); // no transition, emoji regex seems to match #\n tr(Emoji, EMOJI, Emoji);\n tt(Emoji, EMOJI_VARIATION, Emoji);\n // tt(Start, EMOJI_VARIATION, Emoji); // This one is sketchy\n\n const EmojiJoiner = tt(Emoji, EMOJI_JOINER);\n tt(EmojiJoiner, '#');\n tr(EmojiJoiner, EMOJI, Emoji);\n // tt(EmojiJoiner, EMOJI_VARIATION, Emoji); // also sketchy\n\n // Generates states for top-level domains\n // Note that this is most accurate when tlds are in alphabetical order\n const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];\n const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];\n for (let i = 0; i < tlds.length; i++) {\n fastts(Start, tlds[i], TLD, WORD, wordjr);\n }\n for (let i = 0; i < utlds.length; i++) {\n fastts(Start, utlds[i], UTLD, UWORD, uwordjr);\n }\n addToGroups(TLD, {\n tld: true,\n ascii: true\n }, groups);\n addToGroups(UTLD, {\n utld: true,\n alpha: true\n }, groups);\n\n // Collect the states generated by different protocols. NOTE: If any new TLDs\n // get added that are also protocols, set the token to be the same as the\n // protocol to ensure parsing works as expected.\n fastts(Start, 'file', SCHEME, WORD, wordjr);\n fastts(Start, 'mailto', SCHEME, WORD, wordjr);\n fastts(Start, 'http', SLASH_SCHEME, WORD, wordjr);\n fastts(Start, 'https', SLASH_SCHEME, WORD, wordjr);\n fastts(Start, 'ftp', SLASH_SCHEME, WORD, wordjr);\n fastts(Start, 'ftps', SLASH_SCHEME, WORD, wordjr);\n addToGroups(SCHEME, {\n scheme: true,\n ascii: true\n }, groups);\n addToGroups(SLASH_SCHEME, {\n slashscheme: true,\n ascii: true\n }, groups);\n\n // Register custom schemes. Assumes each scheme is asciinumeric with hyphens\n customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1);\n for (let i = 0; i < customSchemes.length; i++) {\n const sch = customSchemes[i][0];\n const optionalSlashSlash = customSchemes[i][1];\n const flags = optionalSlashSlash ? {\n [scheme]: true\n } : {\n [slashscheme]: true\n };\n if (sch.indexOf('-') >= 0) {\n flags[domain] = true;\n } else if (!ASCII_LETTER.test(sch)) {\n flags[numeric] = true; // numbers only\n } else if (DIGIT.test(sch)) {\n flags[asciinumeric] = true;\n } else {\n flags[ascii] = true;\n }\n ts(Start, sch, sch, flags);\n }\n\n // Localhost token\n ts(Start, 'localhost', LOCALHOST, {\n ascii: true\n });\n\n // Set default transition for start state (some symbol)\n Start.jd = new State(SYM);\n return {\n start: Start,\n tokens: Object.assign({\n groups\n }, tk)\n };\n}\n\n/**\n\tGiven a string, returns an array of TOKEN instances representing the\n\tcomposition of that string.\n\n\t@method run\n\t@param {State} start scanner starting state\n\t@param {string} str input string to scan\n\t@return {Token[]} list of tokens, each with a type and value\n*/\nfunction run$1(start, str) {\n // State machine is not case sensitive, so input is tokenized in lowercased\n // form (still returns regular case). Uses selective `toLowerCase` because\n // lowercasing the entire string causes the length and character position to\n // vary in some non-English strings with V8-based runtimes.\n const iterable = stringToArray(str.replace(/[A-Z]/g, c => c.toLowerCase()));\n const charCount = iterable.length; // <= len if there are emojis, etc\n const tokens = []; // return value\n\n // cursor through the string itself, accounting for characters that have\n // width with length 2 such as emojis\n let cursor = 0;\n\n // Cursor through the array-representation of the string\n let charCursor = 0;\n\n // Tokenize the string\n while (charCursor < charCount) {\n let state = start;\n let nextState = null;\n let tokenLength = 0;\n let latestAccepting = null;\n let sinceAccepts = -1;\n let charsSinceAccepts = -1;\n while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {\n state = nextState;\n\n // Keep track of the latest accepting state\n if (state.accepts()) {\n sinceAccepts = 0;\n charsSinceAccepts = 0;\n latestAccepting = state;\n } else if (sinceAccepts >= 0) {\n sinceAccepts += iterable[charCursor].length;\n charsSinceAccepts++;\n }\n tokenLength += iterable[charCursor].length;\n cursor += iterable[charCursor].length;\n charCursor++;\n }\n\n // Roll back to the latest accepting state\n cursor -= sinceAccepts;\n charCursor -= charsSinceAccepts;\n tokenLength -= sinceAccepts;\n\n // No more jumps, just make a new token from the last accepting one\n tokens.push({\n t: latestAccepting.t,\n // token type/name\n v: str.slice(cursor - tokenLength, cursor),\n // string value\n s: cursor - tokenLength,\n // start index\n e: cursor // end index (excluding)\n });\n }\n return tokens;\n}\n\n/**\n * Convert a String to an Array of characters, taking into account that some\n * characters like emojis take up two string indexes.\n *\n * Adapted from core-js (MIT license)\n * https://github.com/zloirock/core-js/blob/2d69cf5f99ab3ea3463c395df81e5a15b68f49d9/packages/core-js/internals/string-multibyte.js\n *\n * @function stringToArray\n * @param {string} str\n * @returns {string[]}\n */\nfunction stringToArray(str) {\n const result = [];\n const len = str.length;\n let index = 0;\n while (index < len) {\n let first = str.charCodeAt(index);\n let second;\n let char = first < 0xd800 || first > 0xdbff || index + 1 === len || (second = str.charCodeAt(index + 1)) < 0xdc00 || second > 0xdfff ? str[index] // single character\n : str.slice(index, index + 2); // two-index characters\n result.push(char);\n index += char.length;\n }\n return result;\n}\n\n/**\n * Fast version of ts function for when transition defaults are well known\n * @param {State} state\n * @param {string} input\n * @param {string} t\n * @param {string} defaultt\n * @param {[RegExp, State][]} jr\n * @returns {State}\n */\nfunction fastts(state, input, t, defaultt, jr) {\n let next;\n const len = input.length;\n for (let i = 0; i < len - 1; i++) {\n const char = input[i];\n if (state.j[char]) {\n next = state.j[char];\n } else {\n next = new State(defaultt);\n next.jr = jr.slice();\n state.j[char] = next;\n }\n state = next;\n }\n next = new State(t);\n next.jr = jr.slice();\n state.j[input[len - 1]] = next;\n return next;\n}\n\n/**\n * Converts a string of Top-Level Domain names encoded in update-tlds.js back\n * into a list of strings.\n * @param {str} encoded encoded TLDs string\n * @returns {str[]} original TLDs list\n */\nfunction decodeTlds(encoded) {\n const words = [];\n const stack = [];\n let i = 0;\n let digits = '0123456789';\n while (i < encoded.length) {\n let popDigitCount = 0;\n while (digits.indexOf(encoded[i + popDigitCount]) >= 0) {\n popDigitCount++; // encountered some digits, have to pop to go one level up trie\n }\n if (popDigitCount > 0) {\n words.push(stack.join('')); // whatever preceded the pop digits must be a word\n for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) {\n stack.pop();\n }\n i += popDigitCount;\n } else {\n stack.push(encoded[i]); // drop down a level into the trie\n i++;\n }\n }\n return words;\n}\n\n/**\n * An object where each key is a valid DOM Event Name such as `click` or `focus`\n * and each value is an event handler function.\n *\n * https://developer.mozilla.org/en-US/docs/Web/API/Element#events\n * @typedef {?{ [event: string]: Function }} EventListeners\n */\n\n/**\n * All formatted properties required to render a link, including `tagName`,\n * `attributes`, `content` and `eventListeners`.\n * @typedef {{ tagName: any, attributes: {[attr: string]: any}, content: string,\n * eventListeners: EventListeners }} IntermediateRepresentation\n */\n\n/**\n * Specify either an object described by the template type `O` or a function.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `O`\n * @template O\n * @typedef {O | ((value: string, type: string, token: MultiToken) => O)} OptObj\n */\n\n/**\n * Specify either a function described by template type `F` or an object.\n *\n * Each key in the object should be a link type (`'url'`, `'hashtag`', etc.). Each\n * value should be a function with template type `F` that is called when the\n * corresponding link type is encountered.\n * @template F\n * @typedef {F | { [type: string]: F}} OptFn\n */\n\n/**\n * Specify either a value with template type `V`, a function that returns `V` or\n * an object where each value resolves to `V`.\n *\n * The function takes a string value (usually the link's href attribute), the\n * link type (`'url'`, `'hashtag`', etc.) and an internal token representation\n * of the link. It should return an object of the template type `V`\n *\n * For the object, each key should be a link type (`'url'`, `'hashtag`', etc.).\n * Each value should either have type `V` or a function that returns V. This\n * function similarly takes a string value and a token.\n *\n * Example valid types for `Opt`:\n *\n * ```js\n * 'hello'\n * (value, type, token) => 'world'\n * { url: 'hello', email: (value, token) => 'world'}\n * ```\n * @template V\n * @typedef {V | ((value: string, type: string, token: MultiToken) => V) | { [type: string]: V | ((value: string, token: MultiToken) => V) }} Opt\n */\n\n/**\n * See available options: https://linkify.js.org/docs/options.html\n * @typedef {{\n * \tdefaultProtocol?: string,\n * events?: OptObj,\n * \tformat?: Opt,\n * \tformatHref?: Opt,\n * \tnl2br?: boolean,\n * \ttagName?: Opt,\n * \ttarget?: Opt,\n * \trel?: Opt,\n * \tvalidate?: Opt,\n * \ttruncate?: Opt,\n * \tclassName?: Opt,\n * \tattributes?: OptObj<({ [attr: string]: any })>,\n * ignoreTags?: string[],\n * \trender?: OptFn<((ir: IntermediateRepresentation) => any)>\n * }} Opts\n */\n\n/**\n * @type Required\n */\nconst defaults = {\n defaultProtocol: 'http',\n events: null,\n format: noop,\n formatHref: noop,\n nl2br: false,\n tagName: 'a',\n target: null,\n rel: null,\n validate: true,\n truncate: Infinity,\n className: null,\n attributes: null,\n ignoreTags: [],\n render: null\n};\n\n/**\n * Utility class for linkify interfaces to apply specified\n * {@link Opts formatting and rendering options}.\n *\n * @param {Opts | Options} [opts] Option value overrides.\n * @param {(ir: IntermediateRepresentation) => any} [defaultRender] (For\n * internal use) default render function that determines how to generate an\n * HTML element based on a link token's derived tagName, attributes and HTML.\n * Similar to render option\n */\nfunction Options(opts, defaultRender = null) {\n let o = Object.assign({}, defaults);\n if (opts) {\n o = Object.assign(o, opts instanceof Options ? opts.o : opts);\n }\n\n // Ensure all ignored tags are uppercase\n const ignoredTags = o.ignoreTags;\n const uppercaseIgnoredTags = [];\n for (let i = 0; i < ignoredTags.length; i++) {\n uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase());\n }\n /** @protected */\n this.o = o;\n if (defaultRender) {\n this.defaultRender = defaultRender;\n }\n this.ignoreTags = uppercaseIgnoredTags;\n}\nOptions.prototype = {\n o: defaults,\n /**\n * @type string[]\n */\n ignoreTags: [],\n /**\n * @param {IntermediateRepresentation} ir\n * @returns {any}\n */\n defaultRender(ir) {\n return ir;\n },\n /**\n * Returns true or false based on whether a token should be displayed as a\n * link based on the user options.\n * @param {MultiToken} token\n * @returns {boolean}\n */\n check(token) {\n return this.get('validate', token.toString(), token);\n },\n // Private methods\n\n /**\n * Resolve an option's value based on the value of the option and the given\n * params. If operator and token are specified and the target option is\n * callable, automatically calls the function with the given argument.\n * @template {keyof Opts} K\n * @param {K} key Name of option to use\n * @param {string} [operator] will be passed to the target option if it's a\n * function. If not specified, RAW function value gets returned\n * @param {MultiToken} [token] The token from linkify.tokenize\n * @returns {Opts[K] | any}\n */\n get(key, operator, token) {\n const isCallable = operator != null;\n let option = this.o[key];\n if (!option) {\n return option;\n }\n if (typeof option === 'object') {\n option = token.t in option ? option[token.t] : defaults[key];\n if (typeof option === 'function' && isCallable) {\n option = option(operator, token);\n }\n } else if (typeof option === 'function' && isCallable) {\n option = option(operator, token.t, token);\n }\n return option;\n },\n /**\n * @template {keyof Opts} L\n * @param {L} key Name of options object to use\n * @param {string} [operator]\n * @param {MultiToken} [token]\n * @returns {Opts[L] | any}\n */\n getObj(key, operator, token) {\n let obj = this.o[key];\n if (typeof obj === 'function' && operator != null) {\n obj = obj(operator, token.t, token);\n }\n return obj;\n },\n /**\n * Convert the given token to a rendered element that may be added to the\n * calling-interface's DOM\n * @param {MultiToken} token Token to render to an HTML element\n * @returns {any} Render result; e.g., HTML string, DOM element, React\n * Component, etc.\n */\n render(token) {\n const ir = token.render(this); // intermediate representation\n const renderFn = this.get('render', null, token) || this.defaultRender;\n return renderFn(ir, token.t, token);\n }\n};\nfunction noop(val) {\n return val;\n}\n\nvar options = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tOptions: Options,\n\tdefaults: defaults\n});\n\n/******************************************************************************\n\tMulti-Tokens\n\tTokens composed of arrays of TextTokens\n******************************************************************************/\n\n/**\n * @param {string} value\n * @param {Token[]} tokens\n */\nfunction MultiToken(value, tokens) {\n this.t = 'token';\n this.v = value;\n this.tk = tokens;\n}\n\n/**\n * Abstract class used for manufacturing tokens of text tokens. That is rather\n * than the value for a token being a small string of text, it's value an array\n * of text tokens.\n *\n * Used for grouping together URLs, emails, hashtags, and other potential\n * creations.\n * @class MultiToken\n * @property {string} t\n * @property {string} v\n * @property {Token[]} tk\n * @abstract\n */\nMultiToken.prototype = {\n isLink: false,\n /**\n * Return the string this token represents.\n * @return {string}\n */\n toString() {\n return this.v;\n },\n /**\n * What should the value for this token be in the `href` HTML attribute?\n * Returns the `.toString` value by default.\n * @param {string} [scheme]\n * @return {string}\n */\n toHref(scheme) {\n return this.toString();\n },\n /**\n * @param {Options} options Formatting options\n * @returns {string}\n */\n toFormattedString(options) {\n const val = this.toString();\n const truncate = options.get('truncate', val, this);\n const formatted = options.get('format', val, this);\n return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + '…' : formatted;\n },\n /**\n *\n * @param {Options} options\n * @returns {string}\n */\n toFormattedHref(options) {\n return options.get('formatHref', this.toHref(options.get('defaultProtocol')), this);\n },\n /**\n * The start index of this token in the original input string\n * @returns {number}\n */\n startIndex() {\n return this.tk[0].s;\n },\n /**\n * The end index of this token in the original input string (up to this\n * index but not including it)\n * @returns {number}\n */\n endIndex() {\n return this.tk[this.tk.length - 1].e;\n },\n /**\n \tReturns an object of relevant values for this token, which includes keys\n \t* type - Kind of token ('url', 'email', etc.)\n \t* value - Original text\n \t* href - The value that should be added to the anchor tag's href\n \t\tattribute\n \t\t@method toObject\n \t@param {string} [protocol] `'http'` by default\n */\n toObject(protocol = defaults.defaultProtocol) {\n return {\n type: this.t,\n value: this.toString(),\n isLink: this.isLink,\n href: this.toHref(protocol),\n start: this.startIndex(),\n end: this.endIndex()\n };\n },\n /**\n *\n * @param {Options} options Formatting option\n */\n toFormattedObject(options) {\n return {\n type: this.t,\n value: this.toFormattedString(options),\n isLink: this.isLink,\n href: this.toFormattedHref(options),\n start: this.startIndex(),\n end: this.endIndex()\n };\n },\n /**\n * Whether this token should be rendered as a link according to the given options\n * @param {Options} options\n * @returns {boolean}\n */\n validate(options) {\n return options.get('validate', this.toString(), this);\n },\n /**\n * Return an object that represents how this link should be rendered.\n * @param {Options} options Formattinng options\n */\n render(options) {\n const token = this;\n const href = this.toHref(options.get('defaultProtocol'));\n const formattedHref = options.get('formatHref', href, this);\n const tagName = options.get('tagName', href, token);\n const content = this.toFormattedString(options);\n const attributes = {};\n const className = options.get('className', href, token);\n const target = options.get('target', href, token);\n const rel = options.get('rel', href, token);\n const attrs = options.getObj('attributes', href, token);\n const eventListeners = options.getObj('events', href, token);\n attributes.href = formattedHref;\n if (className) {\n attributes.class = className;\n }\n if (target) {\n attributes.target = target;\n }\n if (rel) {\n attributes.rel = rel;\n }\n if (attrs) {\n Object.assign(attributes, attrs);\n }\n return {\n tagName,\n attributes,\n content,\n eventListeners\n };\n }\n};\n\n/**\n * Create a new token that can be emitted by the parser state machine\n * @param {string} type readable type of the token\n * @param {object} props properties to assign or override, including isLink = true or false\n * @returns {new (value: string, tokens: Token[]) => MultiToken} new token class\n */\nfunction createTokenClass(type, props) {\n class Token extends MultiToken {\n constructor(value, tokens) {\n super(value, tokens);\n this.t = type;\n }\n }\n for (const p in props) {\n Token.prototype[p] = props[p];\n }\n Token.t = type;\n return Token;\n}\n\n/**\n\tRepresents a list of tokens making up a valid email address\n*/\nconst Email = createTokenClass('email', {\n isLink: true,\n toHref() {\n return 'mailto:' + this.toString();\n }\n});\n\n/**\n\tRepresents some plain text\n*/\nconst Text = createTokenClass('text');\n\n/**\n\tMulti-linebreak token - represents a line break\n\t@class Nl\n*/\nconst Nl = createTokenClass('nl');\n\n/**\n\tRepresents a list of text tokens making up a valid URL\n\t@class Url\n*/\nconst Url = createTokenClass('url', {\n isLink: true,\n /**\n \tLowercases relevant parts of the domain and adds the protocol if\n \trequired. Note that this will not escape unsafe HTML characters in the\n \tURL.\n \t\t@param {string} [scheme] default scheme (e.g., 'https')\n \t@return {string} the full href\n */\n toHref(scheme = defaults.defaultProtocol) {\n // Check if already has a prefix scheme\n return this.hasProtocol() ? this.v : `${scheme}://${this.v}`;\n },\n /**\n * Check whether this URL token has a protocol\n * @return {boolean}\n */\n hasProtocol() {\n const tokens = this.tk;\n return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;\n }\n});\n\nvar multi = /*#__PURE__*/Object.freeze({\n\t__proto__: null,\n\tBase: MultiToken,\n\tEmail: Email,\n\tMultiToken: MultiToken,\n\tNl: Nl,\n\tText: Text,\n\tUrl: Url,\n\tcreateTokenClass: createTokenClass\n});\n\n/**\n\tNot exactly parser, more like the second-stage scanner (although we can\n\ttheoretically hotswap the code here with a real parser in the future... but\n\tfor a little URL-finding utility abstract syntax trees may be a little\n\toverkill).\n\n\tURL format: http://en.wikipedia.org/wiki/URI_scheme\n\tEmail format: http://en.wikipedia.org/wiki/EmailAddress (links to RFC in\n\treference)\n\n\t@module linkify\n\t@submodule parser\n\t@main run\n*/\n\nconst makeState = arg => new State(arg);\n\n/**\n * Generate the parser multi token-based state machine\n * @param {{ groups: Collections }} tokens\n */\nfunction init$1({\n groups\n}) {\n // Types of characters the URL can definitely end in\n const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);\n\n // Types of tokens that can follow a URL and be part of the query string\n // but cannot be the very last characters\n // Characters that cannot appear in the URL at all should be excluded\n const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];\n\n // For addresses without the mailto prefix\n // Tokens allowed in the localpart of the email\n const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];\n\n // The universal starting state.\n /**\n * @type State\n */\n const Start = makeState();\n const Localpart = tt(Start, TILDE); // Local part of the email address\n ta(Localpart, localpartAccepting, Localpart);\n ta(Localpart, groups.domain, Localpart);\n const Domain = makeState(),\n Scheme = makeState(),\n SlashScheme = makeState();\n ta(Start, groups.domain, Domain); // parsed string ends with a potential domain name (A)\n ta(Start, groups.scheme, Scheme); // e.g., 'mailto'\n ta(Start, groups.slashscheme, SlashScheme); // e.g., 'http'\n\n ta(Domain, localpartAccepting, Localpart);\n ta(Domain, groups.domain, Domain);\n const LocalpartAt = tt(Domain, AT); // Local part of the email address plus @\n\n tt(Localpart, AT, LocalpartAt); // close to an email address now\n\n // Local part of an email address can be e.g. 'http' or 'mailto'\n tt(Scheme, AT, LocalpartAt);\n tt(SlashScheme, AT, LocalpartAt);\n const LocalpartDot = tt(Localpart, DOT); // Local part of the email address plus '.' (localpart cannot end in .)\n ta(LocalpartDot, localpartAccepting, Localpart);\n ta(LocalpartDot, groups.domain, Localpart);\n const EmailDomain = makeState();\n ta(LocalpartAt, groups.domain, EmailDomain); // parsed string starts with local email info + @ with a potential domain name\n ta(EmailDomain, groups.domain, EmailDomain);\n const EmailDomainDot = tt(EmailDomain, DOT); // domain followed by DOT\n ta(EmailDomainDot, groups.domain, EmailDomain);\n const Email$1 = makeState(Email); // Possible email address (could have more tlds)\n ta(EmailDomainDot, groups.tld, Email$1);\n ta(EmailDomainDot, groups.utld, Email$1);\n tt(LocalpartAt, LOCALHOST, Email$1);\n\n // Hyphen can jump back to a domain name\n const EmailDomainHyphen = tt(EmailDomain, HYPHEN); // parsed string starts with local email info + @ with a potential domain name\n tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);\n ta(EmailDomainHyphen, groups.domain, EmailDomain);\n ta(Email$1, groups.domain, EmailDomain);\n tt(Email$1, DOT, EmailDomainDot);\n tt(Email$1, HYPHEN, EmailDomainHyphen);\n\n // Final possible email states\n const EmailColon = tt(Email$1, COLON); // URL followed by colon (potential port number here)\n /*const EmailColonPort = */\n ta(EmailColon, groups.numeric, Email); // URL followed by colon and port number\n\n // Account for dots and hyphens. Hyphens are usually parts of domain names\n // (but not TLDs)\n const DomainHyphen = tt(Domain, HYPHEN); // domain followed by hyphen\n const DomainDot = tt(Domain, DOT); // domain followed by DOT\n tt(DomainHyphen, HYPHEN, DomainHyphen);\n ta(DomainHyphen, groups.domain, Domain);\n ta(DomainDot, localpartAccepting, Localpart);\n ta(DomainDot, groups.domain, Domain);\n const DomainDotTld = makeState(Url); // Simplest possible URL with no query string\n ta(DomainDot, groups.tld, DomainDotTld);\n ta(DomainDot, groups.utld, DomainDotTld);\n ta(DomainDotTld, groups.domain, Domain);\n ta(DomainDotTld, localpartAccepting, Localpart);\n tt(DomainDotTld, DOT, DomainDot);\n tt(DomainDotTld, HYPHEN, DomainHyphen);\n tt(DomainDotTld, AT, LocalpartAt);\n const DomainDotTldColon = tt(DomainDotTld, COLON); // URL followed by colon (potential port number here)\n const DomainDotTldColonPort = makeState(Url); // TLD followed by a port number\n ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);\n\n // Long URL with optional port and maybe query string\n const Url$1 = makeState(Url);\n\n // URL with extra symbols at the end, followed by an opening bracket\n const UrlNonaccept = makeState(); // URL followed by some symbols (will not be part of the final URL)\n\n // Query strings\n ta(Url$1, qsAccepting, Url$1);\n ta(Url$1, qsNonAccepting, UrlNonaccept);\n ta(UrlNonaccept, qsAccepting, Url$1);\n ta(UrlNonaccept, qsNonAccepting, UrlNonaccept);\n\n // Become real URLs after `SLASH` or `COLON NUM SLASH`\n // Here works with or without scheme:// prefix\n tt(DomainDotTld, SLASH, Url$1);\n tt(DomainDotTldColonPort, SLASH, Url$1);\n\n // Note that domains that begin with schemes are treated slighly differently\n const SchemeColon = tt(Scheme, COLON); // e.g., 'mailto:'\n const SlashSchemeColon = tt(SlashScheme, COLON); // e.g., 'http:'\n const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH); // e.g., 'http:/'\n\n const UriPrefix = tt(SlashSchemeColonSlash, SLASH); // e.g., 'http://'\n\n // Scheme states can transition to domain states\n ta(Scheme, groups.domain, Domain);\n tt(Scheme, DOT, DomainDot);\n tt(Scheme, HYPHEN, DomainHyphen);\n ta(SlashScheme, groups.domain, Domain);\n tt(SlashScheme, DOT, DomainDot);\n tt(SlashScheme, HYPHEN, DomainHyphen);\n\n // Force URL with scheme prefix followed by anything sane\n ta(SchemeColon, groups.domain, Url$1);\n tt(SchemeColon, SLASH, Url$1);\n tt(SchemeColon, QUERY, Url$1);\n ta(UriPrefix, groups.domain, Url$1);\n ta(UriPrefix, qsAccepting, Url$1);\n tt(UriPrefix, SLASH, Url$1);\n const bracketPairs = [[OPENBRACE, CLOSEBRACE],\n // {}\n [OPENBRACKET, CLOSEBRACKET],\n // []\n [OPENPAREN, CLOSEPAREN],\n // ()\n [OPENANGLEBRACKET, CLOSEANGLEBRACKET],\n // <>\n [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],\n // ()\n [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],\n // 「」\n [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],\n // 『』\n [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] // <>\n ];\n for (let i = 0; i < bracketPairs.length; i++) {\n const [OPEN, CLOSE] = bracketPairs[i];\n const UrlOpen = tt(Url$1, OPEN); // URL followed by open bracket\n\n // Continue not accepting for open brackets\n tt(UrlNonaccept, OPEN, UrlOpen);\n\n // Closing bracket component. This character WILL be included in the URL\n tt(UrlOpen, CLOSE, Url$1);\n\n // URL that beings with an opening bracket, followed by a symbols.\n // Note that the final state can still be `UrlOpen` (if the URL has a\n // single opening bracket for some reason).\n const UrlOpenQ = makeState(Url);\n ta(UrlOpen, qsAccepting, UrlOpenQ);\n const UrlOpenSyms = makeState(); // UrlOpen followed by some symbols it cannot end it\n ta(UrlOpen, qsNonAccepting);\n\n // URL that begins with an opening bracket, followed by some symbols\n ta(UrlOpenQ, qsAccepting, UrlOpenQ);\n ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms);\n ta(UrlOpenSyms, qsAccepting, UrlOpenQ);\n ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);\n\n // Close brace/bracket to become regular URL\n tt(UrlOpenQ, CLOSE, Url$1);\n tt(UrlOpenSyms, CLOSE, Url$1);\n }\n tt(Start, LOCALHOST, DomainDotTld); // localhost is a valid URL state\n tt(Start, NL, Nl); // single new line\n\n return {\n start: Start,\n tokens: tk\n };\n}\n\n/**\n * Run the parser state machine on a list of scanned string-based tokens to\n * create a list of multi tokens, each of which represents a URL, email address,\n * plain text, etc.\n *\n * @param {State} start parser start state\n * @param {string} input the original input used to generate the given tokens\n * @param {Token[]} tokens list of scanned tokens\n * @returns {MultiToken[]}\n */\nfunction run(start, input, tokens) {\n let len = tokens.length;\n let cursor = 0;\n let multis = [];\n let textTokens = [];\n while (cursor < len) {\n let state = start;\n let secondState = null;\n let nextState = null;\n let multiLength = 0;\n let latestAccepting = null;\n let sinceAccepts = -1;\n while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {\n // Starting tokens with nowhere to jump to.\n // Consider these to be just plain text\n textTokens.push(tokens[cursor++]);\n }\n while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {\n // Get the next state\n secondState = null;\n state = nextState;\n\n // Keep track of the latest accepting state\n if (state.accepts()) {\n sinceAccepts = 0;\n latestAccepting = state;\n } else if (sinceAccepts >= 0) {\n sinceAccepts++;\n }\n cursor++;\n multiLength++;\n }\n if (sinceAccepts < 0) {\n // No accepting state was found, part of a regular text token add\n // the first text token to the text tokens array and try again from\n // the next\n cursor -= multiLength;\n if (cursor < len) {\n textTokens.push(tokens[cursor]);\n cursor++;\n }\n } else {\n // Accepting state!\n // First close off the textTokens (if available)\n if (textTokens.length > 0) {\n multis.push(initMultiToken(Text, input, textTokens));\n textTokens = [];\n }\n\n // Roll back to the latest accepting state\n cursor -= sinceAccepts;\n multiLength -= sinceAccepts;\n\n // Create a new multitoken\n const Multi = latestAccepting.t;\n const subtokens = tokens.slice(cursor - multiLength, cursor);\n multis.push(initMultiToken(Multi, input, subtokens));\n }\n }\n\n // Finally close off the textTokens (if available)\n if (textTokens.length > 0) {\n multis.push(initMultiToken(Text, input, textTokens));\n }\n return multis;\n}\n\n/**\n * Utility function for instantiating a new multitoken with all the relevant\n * fields during parsing.\n * @param {new (value: string, tokens: Token[]) => MultiToken} Multi class to instantiate\n * @param {string} input original input string\n * @param {Token[]} tokens consecutive tokens scanned from input string\n * @returns {MultiToken}\n */\nfunction initMultiToken(Multi, input, tokens) {\n const startIdx = tokens[0].s;\n const endIdx = tokens[tokens.length - 1].e;\n const value = input.slice(startIdx, endIdx);\n return new Multi(value, tokens);\n}\n\nconst warn = typeof console !== 'undefined' && console && console.warn || (() => {});\nconst warnAdvice = 'until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.';\n\n// Side-effect initialization state\nconst INIT = {\n scanner: null,\n parser: null,\n tokenQueue: [],\n pluginQueue: [],\n customSchemes: [],\n initialized: false\n};\n\n/**\n * @typedef {{\n * \tstart: State,\n * \ttokens: { groups: Collections } & typeof tk\n * }} ScannerInit\n */\n\n/**\n * @typedef {{\n * \tstart: State,\n * \ttokens: typeof multi\n * }} ParserInit\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit }) => void} TokenPlugin\n */\n\n/**\n * @typedef {(arg: { scanner: ScannerInit, parser: ParserInit }) => void} Plugin\n */\n\n/**\n * De-register all plugins and reset the internal state-machine. Used for\n * testing; not required in practice.\n * @private\n */\nfunction reset() {\n State.groups = {};\n INIT.scanner = null;\n INIT.parser = null;\n INIT.tokenQueue = [];\n INIT.pluginQueue = [];\n INIT.customSchemes = [];\n INIT.initialized = false;\n return INIT;\n}\n\n/**\n * Register a token plugin to allow the scanner to recognize additional token\n * types before the parser state machine is constructed from the results.\n * @param {string} name of plugin to register\n * @param {TokenPlugin} plugin function that accepts the scanner state machine\n * and available scanner tokens and collections and extends the state machine to\n * recognize additional tokens or groups.\n */\nfunction registerTokenPlugin(name, plugin) {\n if (typeof plugin !== 'function') {\n throw new Error(`linkifyjs: Invalid token plugin ${plugin} (expects function)`);\n }\n for (let i = 0; i < INIT.tokenQueue.length; i++) {\n if (name === INIT.tokenQueue[i][0]) {\n warn(`linkifyjs: token plugin \"${name}\" already registered - will be overwritten`);\n INIT.tokenQueue[i] = [name, plugin];\n return;\n }\n }\n INIT.tokenQueue.push([name, plugin]);\n if (INIT.initialized) {\n warn(`linkifyjs: already initialized - will not register token plugin \"${name}\" ${warnAdvice}`);\n }\n}\n\n/**\n * Register a linkify plugin\n * @param {string} name of plugin to register\n * @param {Plugin} plugin function that accepts the parser state machine and\n * extends the parser to recognize additional link types\n */\nfunction registerPlugin(name, plugin) {\n if (typeof plugin !== 'function') {\n throw new Error(`linkifyjs: Invalid plugin ${plugin} (expects function)`);\n }\n for (let i = 0; i < INIT.pluginQueue.length; i++) {\n if (name === INIT.pluginQueue[i][0]) {\n warn(`linkifyjs: plugin \"${name}\" already registered - will be overwritten`);\n INIT.pluginQueue[i] = [name, plugin];\n return;\n }\n }\n INIT.pluginQueue.push([name, plugin]);\n if (INIT.initialized) {\n warn(`linkifyjs: already initialized - will not register plugin \"${name}\" ${warnAdvice}`);\n }\n}\n\n/**\n * Detect URLs with the following additional protocol. Anything with format\n * \"protocol://...\" will be considered a link. If `optionalSlashSlash` is set to\n * `true`, anything with format \"protocol:...\" will be considered a link.\n * @param {string} scheme\n * @param {boolean} [optionalSlashSlash]\n */\nfunction registerCustomProtocol(scheme, optionalSlashSlash = false) {\n if (INIT.initialized) {\n warn(`linkifyjs: already initialized - will not register custom scheme \"${scheme}\" ${warnAdvice}`);\n }\n if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme)) {\n throw new Error(`linkifyjs: incorrect scheme format.\n1. Must only contain digits, lowercase ASCII letters or \"-\"\n2. Cannot start or end with \"-\"\n3. \"-\" cannot repeat`);\n }\n INIT.customSchemes.push([scheme, optionalSlashSlash]);\n}\n\n/**\n * Initialize the linkify state machine. Called automatically the first time\n * linkify is called on a string, but may be called manually as well.\n */\nfunction init() {\n // Initialize scanner state machine and plugins\n INIT.scanner = init$2(INIT.customSchemes);\n for (let i = 0; i < INIT.tokenQueue.length; i++) {\n INIT.tokenQueue[i][1]({\n scanner: INIT.scanner\n });\n }\n\n // Initialize parser state machine and plugins\n INIT.parser = init$1(INIT.scanner.tokens);\n for (let i = 0; i < INIT.pluginQueue.length; i++) {\n INIT.pluginQueue[i][1]({\n scanner: INIT.scanner,\n parser: INIT.parser\n });\n }\n INIT.initialized = true;\n return INIT;\n}\n\n/**\n * Parse a string into tokens that represent linkable and non-linkable sub-components\n * @param {string} str\n * @return {MultiToken[]} tokens\n */\nfunction tokenize(str) {\n if (!INIT.initialized) {\n init();\n }\n return run(INIT.parser.start, str, run$1(INIT.scanner.start, str));\n}\ntokenize.scan = run$1; // for testing\n\n/**\n * Find a list of linkable items in the given string.\n * @param {string} str string to find links in\n * @param {string | Opts} [type] either formatting options or specific type of\n * links to find, e.g., 'url' or 'email'\n * @param {Opts} [opts] formatting options for final output. Cannot be specified\n * if opts already provided in `type` argument\n */\nfunction find(str, type = null, opts = null) {\n if (type && typeof type === 'object') {\n if (opts) {\n throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);\n }\n opts = type;\n type = null;\n }\n const options = new Options(opts);\n const tokens = tokenize(str);\n const filtered = [];\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n if (token.isLink && (!type || token.t === type) && options.check(token)) {\n filtered.push(token.toFormattedObject(options));\n }\n }\n return filtered;\n}\n\n/**\n * Is the given string valid linkable text of some sort. Note that this does not\n * trim the text for you.\n *\n * Optionally pass in a second `type` param, which is the type of link to test\n * for.\n *\n * For example,\n *\n * linkify.test(str, 'email');\n *\n * Returns `true` if str is a valid email.\n * @param {string} str string to test for links\n * @param {string} [type] optional specific link type to look for\n * @returns boolean true/false\n */\nfunction test(str, type = null) {\n const tokens = tokenize(str);\n return tokens.length === 1 && tokens[0].isLink && (!type || tokens[0].t === type);\n}\n\nexport { MultiToken, Options, State, createTokenClass, find, init, multi, options, regexp, registerCustomProtocol, registerPlugin, registerTokenPlugin, reset, stringToArray, test, multi as text, tokenize };\n", "import type { PasteRuleMatch } from '@tiptap/core'\nimport { Mark, markPasteRule, mergeAttributes } from '@tiptap/core'\nimport type { Plugin } from '@tiptap/pm/state'\nimport { find, registerCustomProtocol, reset } from 'linkifyjs'\n\nimport { autolink } from './helpers/autolink.js'\nimport { clickHandler } from './helpers/clickHandler.js'\nimport { pasteHandler } from './helpers/pasteHandler.js'\nimport { UNICODE_WHITESPACE_REGEX_GLOBAL } from './helpers/whitespace.js'\n\nexport interface LinkProtocolOptions {\n /**\n * The protocol scheme to be registered.\n * @default '''\n * @example 'ftp'\n * @example 'git'\n */\n scheme: string\n\n /**\n * If enabled, it allows optional slashes after the protocol.\n * @default false\n * @example true\n */\n optionalSlashes?: boolean\n}\n\nexport const pasteRegex =\n /https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z]{2,}\\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi\n\n/**\n * @deprecated The default behavior is now to open links when the editor is not editable.\n */\ntype DeprecatedOpenWhenNotEditable = 'whenNotEditable'\n\nexport interface LinkOptions {\n /**\n * If enabled, the extension will automatically add links as you type.\n * @default true\n * @example false\n */\n autolink: boolean\n\n /**\n * An array of custom protocols to be registered with linkifyjs.\n * @default []\n * @example ['ftp', 'git']\n */\n protocols: Array\n\n /**\n * Default protocol to use when no protocol is specified.\n * @default 'http'\n */\n defaultProtocol: string\n /**\n * If enabled, links will be opened on click.\n * @default true\n * @example false\n */\n openOnClick: boolean | DeprecatedOpenWhenNotEditable\n /**\n * If enabled, the link will be selected when clicked.\n * @default false\n * @example true\n */\n enableClickSelection: boolean\n /**\n * Adds a link to the current selection if the pasted content only contains an url.\n * @default true\n * @example false\n */\n linkOnPaste: boolean\n\n /**\n * HTML attributes to add to the link element.\n * @default {}\n * @example { class: 'foo' }\n */\n HTMLAttributes: Record\n\n /**\n * @deprecated Use the `shouldAutoLink` option instead.\n * A validation function that modifies link verification for the auto linker.\n * @param url - The url to be validated.\n * @returns - True if the url is valid, false otherwise.\n */\n validate: (url: string) => boolean\n\n /**\n * A validation function which is used for configuring link verification for preventing XSS attacks.\n * Only modify this if you know what you're doing.\n *\n * @returns {boolean} `true` if the URL is valid, `false` otherwise.\n *\n * @example\n * isAllowedUri: (url, { defaultValidate, protocols, defaultProtocol }) => {\n * return url.startsWith('./') || defaultValidate(url)\n * }\n */\n isAllowedUri: (\n /**\n * The URL to be validated.\n */\n url: string,\n ctx: {\n /**\n * The default validation function.\n */\n defaultValidate: (url: string) => boolean\n /**\n * An array of allowed protocols for the URL (e.g., \"http\", \"https\"). As defined in the `protocols` option.\n */\n protocols: Array\n /**\n * A string that represents the default protocol (e.g., 'http'). As defined in the `defaultProtocol` option.\n */\n defaultProtocol: string\n },\n ) => boolean\n\n /**\n * Determines whether a valid link should be automatically linked in the content.\n *\n * @param {string} url - The URL that has already been validated.\n * @returns {boolean} - True if the link should be auto-linked; false if it should not be auto-linked.\n */\n shouldAutoLink: (url: string) => boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n link: {\n /**\n * Set a link mark\n * @param attributes The link attributes\n * @example editor.commands.setLink({ href: 'https://tiptap.dev' })\n */\n setLink: (attributes: {\n href: string\n target?: string | null\n rel?: string | null\n class?: string | null\n title?: string | null\n }) => ReturnType\n /**\n * Toggle a link mark\n * @param attributes The link attributes\n * @example editor.commands.toggleLink({ href: 'https://tiptap.dev' })\n */\n toggleLink: (attributes?: {\n href: string\n target?: string | null\n rel?: string | null\n class?: string | null\n title?: string | null\n }) => ReturnType\n /**\n * Unset a link mark\n * @example editor.commands.unsetLink()\n */\n unsetLink: () => ReturnType\n }\n }\n}\n\nexport function isAllowedUri(uri: string | undefined, protocols?: LinkOptions['protocols']) {\n const allowedProtocols: string[] = ['http', 'https', 'ftp', 'ftps', 'mailto', 'tel', 'callto', 'sms', 'cid', 'xmpp']\n\n if (protocols) {\n protocols.forEach(protocol => {\n const nextProtocol = typeof protocol === 'string' ? protocol : protocol.scheme\n\n if (nextProtocol) {\n allowedProtocols.push(nextProtocol)\n }\n })\n }\n\n return (\n !uri ||\n uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, '').match(\n new RegExp(\n // eslint-disable-next-line no-useless-escape\n `^(?:(?:${allowedProtocols.join('|')}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,\n 'i',\n ),\n )\n )\n}\n\n/**\n * This extension allows you to create links.\n * @see https://www.tiptap.dev/api/marks/link\n */\nexport const Link = Mark.create({\n name: 'link',\n\n priority: 1000,\n\n keepOnSplit: false,\n\n exitable: true,\n\n onCreate() {\n // TODO: v4 - remove validate option\n if (this.options.validate && !this.options.shouldAutoLink) {\n // Copy the validate function to the shouldAutoLink option\n this.options.shouldAutoLink = this.options.validate\n console.warn('The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.')\n }\n this.options.protocols.forEach(protocol => {\n if (typeof protocol === 'string') {\n registerCustomProtocol(protocol)\n return\n }\n registerCustomProtocol(protocol.scheme, protocol.optionalSlashes)\n })\n },\n\n onDestroy() {\n reset()\n },\n\n inclusive() {\n return this.options.autolink\n },\n\n addOptions() {\n return {\n openOnClick: true,\n enableClickSelection: false,\n linkOnPaste: true,\n autolink: true,\n protocols: [],\n defaultProtocol: 'http',\n HTMLAttributes: {\n target: '_blank',\n rel: 'noopener noreferrer nofollow',\n class: null,\n },\n isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),\n validate: url => !!url,\n shouldAutoLink: url => {\n // URLs with explicit protocols (e.g., https://) should be auto-linked\n // But not if @ appears before :// (that would be userinfo like user:pass@host)\n const hasProtocol = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)\n const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url)\n\n if (hasProtocol || (hasMaybeProtocol && !url.includes('@'))) {\n return true\n }\n // Strip userinfo (user:pass@) if present, then extract hostname\n const urlWithoutUserinfo = url.includes('@') ? url.split('@').pop()! : url\n const hostname = urlWithoutUserinfo.split(/[/?#:]/)[0]\n\n // Don't auto-link IP addresses without protocol\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname)) {\n return false\n }\n // Don't auto-link single-word hostnames without TLD (e.g., \"localhost\")\n if (!/\\./.test(hostname)) {\n return false\n }\n return true\n },\n }\n },\n\n addAttributes() {\n return {\n href: {\n default: null,\n parseHTML(element) {\n return element.getAttribute('href')\n },\n },\n target: {\n default: this.options.HTMLAttributes.target,\n },\n rel: {\n default: this.options.HTMLAttributes.rel,\n },\n class: {\n default: this.options.HTMLAttributes.class,\n },\n title: {\n default: null,\n },\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 'a[href]',\n getAttrs: dom => {\n const href = (dom as HTMLElement).getAttribute('href')\n\n // prevent XSS attacks\n if (\n !href ||\n !this.options.isAllowedUri(href, {\n defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })\n ) {\n return false\n }\n return null\n },\n },\n ]\n },\n\n renderHTML({ HTMLAttributes }) {\n // prevent XSS attacks\n if (\n !this.options.isAllowedUri(HTMLAttributes.href, {\n defaultValidate: href => !!isAllowedUri(href, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })\n ) {\n // strip out the href\n return ['a', mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: '' }), 0]\n }\n\n return ['a', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]\n },\n\n markdownTokenName: 'link',\n\n parseMarkdown: (token, helpers) => {\n return helpers.applyMark('link', helpers.parseInline(token.tokens || []), {\n href: token.href,\n title: token.title || null,\n })\n },\n\n renderMarkdown: (node, h) => {\n const href = node.attrs?.href ?? ''\n const title = node.attrs?.title ?? ''\n const text = h.renderChildren(node)\n\n return title ? `[${text}](${href} \"${title}\")` : `[${text}](${href})`\n },\n\n addCommands() {\n return {\n setLink:\n attributes =>\n ({ chain }) => {\n const { href } = attributes\n\n if (\n !this.options.isAllowedUri(href, {\n defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })\n ) {\n return false\n }\n\n return chain().setMark(this.name, attributes).setMeta('preventAutolink', true).run()\n },\n\n toggleLink:\n attributes =>\n ({ chain }) => {\n const { href } = attributes || {}\n\n if (\n href &&\n !this.options.isAllowedUri(href, {\n defaultValidate: url => !!isAllowedUri(url, this.options.protocols),\n protocols: this.options.protocols,\n defaultProtocol: this.options.defaultProtocol,\n })\n ) {\n return false\n }\n\n return chain()\n .toggleMark(this.name, attributes, { extendEmptyMarkRange: true })\n .setMeta('preventAutolink', true)\n .run()\n },\n\n unsetLink:\n () =>\n ({ chain }) => {\n return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta('preventAutolink', true).run()\n },\n }\n },\n\n addPasteRules() {\n return [\n markPasteRule({\n find: text => {\n const foundLinks: PasteRuleMatch[] = []\n\n if (text) {\n const { protocols, defaultProtocol } = this.options\n const links = find(text).filter(\n item =>\n item.isLink &&\n this.options.isAllowedUri(item.value, {\n defaultValidate: href => !!isAllowedUri(href, protocols),\n protocols,\n defaultProtocol,\n }),\n )\n\n if (links.length) {\n links.forEach(link => {\n if (!this.options.shouldAutoLink(link.value)) {\n return\n }\n\n foundLinks.push({\n text: link.value,\n data: {\n href: link.href,\n },\n index: link.start,\n })\n })\n }\n }\n\n return foundLinks\n },\n type: this.type,\n getAttributes: match => {\n return {\n href: match.data?.href,\n }\n },\n }),\n ]\n },\n\n addProseMirrorPlugins() {\n const plugins: Plugin[] = []\n const { protocols, defaultProtocol } = this.options\n\n if (this.options.autolink) {\n plugins.push(\n autolink({\n type: this.type,\n defaultProtocol: this.options.defaultProtocol,\n validate: url =>\n this.options.isAllowedUri(url, {\n defaultValidate: href => !!isAllowedUri(href, protocols),\n protocols,\n defaultProtocol,\n }),\n shouldAutoLink: this.options.shouldAutoLink,\n }),\n )\n }\n\n plugins.push(\n clickHandler({\n type: this.type,\n editor: this.editor,\n openOnClick: this.options.openOnClick === 'whenNotEditable' ? true : this.options.openOnClick,\n enableClickSelection: this.options.enableClickSelection,\n }),\n )\n\n if (this.options.linkOnPaste) {\n plugins.push(\n pasteHandler({\n editor: this.editor,\n defaultProtocol: this.options.defaultProtocol,\n type: this.type,\n shouldAutoLink: this.options.shouldAutoLink,\n }),\n )\n }\n\n return plugins\n },\n})\n", "import type { NodeWithPos } from '@tiptap/core'\nimport { combineTransactionSteps, findChildrenInRange, getChangedRanges, getMarksBetween } from '@tiptap/core'\nimport type { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport type { MultiToken } from 'linkifyjs'\nimport { tokenize } from 'linkifyjs'\n\nimport { UNICODE_WHITESPACE_REGEX, UNICODE_WHITESPACE_REGEX_END } from './whitespace.js'\n\n/**\n * Check if the provided tokens form a valid link structure, which can either be a single link token\n * or a link token surrounded by parentheses or square brackets.\n *\n * This ensures that only complete and valid text is hyperlinked, preventing cases where a valid\n * top-level domain (TLD) is immediately followed by an invalid character, like a number. For\n * example, with the `find` method from Linkify, entering `example.com1` would result in\n * `example.com` being linked and the trailing `1` left as plain text. By using the `tokenize`\n * method, we can perform more comprehensive validation on the input text.\n */\nfunction isValidLinkStructure(tokens: Array>) {\n if (tokens.length === 1) {\n return tokens[0].isLink\n }\n\n if (tokens.length === 3 && tokens[1].isLink) {\n return ['()', '[]'].includes(tokens[0].value + tokens[2].value)\n }\n\n return false\n}\n\ntype AutolinkOptions = {\n type: MarkType\n defaultProtocol: string\n validate: (url: string) => boolean\n shouldAutoLink: (url: string) => boolean\n}\n\n/**\n * This plugin allows you to automatically add links to your editor.\n * @param options The plugin options\n * @returns The plugin instance\n */\nexport function autolink(options: AutolinkOptions): Plugin {\n return new Plugin({\n key: new PluginKey('autolink'),\n appendTransaction: (transactions, oldState, newState) => {\n /**\n * Does the transaction change the document?\n */\n const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc)\n\n /**\n * Prevent autolink if the transaction is not a document change or if the transaction has the meta `preventAutolink`.\n */\n const preventAutolink = transactions.some(transaction => transaction.getMeta('preventAutolink'))\n\n /**\n * Prevent autolink if the transaction is not a document change\n * or if the transaction has the meta `preventAutolink`.\n */\n if (!docChanges || preventAutolink) {\n return\n }\n\n const { tr } = newState\n const transform = combineTransactionSteps(oldState.doc, [...transactions])\n const changes = getChangedRanges(transform)\n\n changes.forEach(({ newRange }) => {\n // Now let’s see if we can add new links.\n const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, node => node.isTextblock)\n\n let textBlock: NodeWithPos | undefined\n let textBeforeWhitespace: string | undefined\n\n if (nodesInChangedRanges.length > 1) {\n // Grab the first node within the changed ranges (ex. the first of two paragraphs when hitting enter).\n textBlock = nodesInChangedRanges[0]\n textBeforeWhitespace = newState.doc.textBetween(\n textBlock.pos,\n textBlock.pos + textBlock.node.nodeSize,\n undefined,\n ' ',\n )\n } else if (nodesInChangedRanges.length) {\n const endText = newState.doc.textBetween(newRange.from, newRange.to, ' ', ' ')\n if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) {\n return\n }\n textBlock = nodesInChangedRanges[0]\n textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, undefined, ' ')\n }\n\n if (textBlock && textBeforeWhitespace) {\n const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean)\n\n if (wordsBeforeWhitespace.length <= 0) {\n return false\n }\n\n const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]\n const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace)\n\n if (!lastWordBeforeSpace) {\n return false\n }\n\n const linksBeforeSpace = tokenize(lastWordBeforeSpace).map(t => t.toObject(options.defaultProtocol))\n\n if (!isValidLinkStructure(linksBeforeSpace)) {\n return false\n }\n\n linksBeforeSpace\n .filter(link => link.isLink)\n // Calculate link position.\n .map(link => ({\n ...link,\n from: lastWordAndBlockOffset + link.start + 1,\n to: lastWordAndBlockOffset + link.end + 1,\n }))\n // ignore link inside code mark\n .filter(link => {\n if (!newState.schema.marks.code) {\n return true\n }\n\n return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code)\n })\n // validate link\n .filter(link => options.validate(link.value))\n // check whether should autolink\n .filter(link => options.shouldAutoLink(link.value))\n // Add link mark.\n .forEach(link => {\n if (getMarksBetween(link.from, link.to, newState.doc).some(item => item.mark.type === options.type)) {\n return\n }\n\n tr.addMark(\n link.from,\n link.to,\n options.type.create({\n href: link.href,\n }),\n )\n })\n }\n })\n\n if (!tr.steps.length) {\n return\n }\n\n return tr\n },\n })\n}\n", "// From DOMPurify\n// https://github.com/cure53/DOMPurify/blob/main/src/regexp.ts\nexport const UNICODE_WHITESPACE_PATTERN = '[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]'\n\nexport const UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN)\nexport const UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`)\nexport const UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, 'g')\n", "import type { Editor } from '@tiptap/core'\nimport { getAttributes } from '@tiptap/core'\nimport type { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\ntype ClickHandlerOptions = {\n type: MarkType\n editor: Editor\n openOnClick?: boolean\n enableClickSelection?: boolean\n}\n\nexport function clickHandler(options: ClickHandlerOptions): Plugin {\n return new Plugin({\n key: new PluginKey('handleClickLink'),\n props: {\n handleClick: (view, pos, event) => {\n if (event.button !== 0) {\n return false\n }\n\n if (!view.editable) {\n return false\n }\n\n let link: HTMLAnchorElement | null = null\n\n if (event.target instanceof HTMLAnchorElement) {\n link = event.target\n } else {\n const target = event.target as HTMLElement | null\n if (!target) {\n return false\n }\n\n const root = options.editor.view.dom\n\n // Tntentionally limit the lookup to the editor root.\n // Using tag names like DIV as boundaries breaks with custom NodeViews,\n link = target.closest('a')\n\n if (link && !root.contains(link)) {\n link = null\n }\n }\n\n if (!link) {\n return false\n }\n\n let handled = false\n\n if (options.enableClickSelection) {\n const commandResult = options.editor.commands.extendMarkRange(options.type.name)\n handled = commandResult\n }\n\n if (options.openOnClick) {\n const attrs = getAttributes(view.state, options.type.name)\n const href = link.href ?? attrs.href\n const target = link.target ?? attrs.target\n\n if (href) {\n window.open(href, target)\n handled = true\n }\n }\n\n return handled\n },\n },\n })\n}\n", "import type { Editor } from '@tiptap/core'\nimport type { MarkType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { find } from 'linkifyjs'\n\nimport type { LinkOptions } from '../link.js'\n\ntype PasteHandlerOptions = {\n editor: Editor\n defaultProtocol: string\n type: MarkType\n shouldAutoLink?: LinkOptions['shouldAutoLink']\n}\n\nexport function pasteHandler(options: PasteHandlerOptions): Plugin {\n return new Plugin({\n key: new PluginKey('handlePasteLink'),\n props: {\n handlePaste: (view, _event, slice) => {\n const { shouldAutoLink } = options\n const { state } = view\n const { selection } = state\n const { empty } = selection\n\n if (empty) {\n return false\n }\n\n let textContent = ''\n\n slice.content.forEach(node => {\n textContent += node.textContent\n })\n\n const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(\n item => item.isLink && item.value === textContent,\n )\n\n if (!textContent || !link || (shouldAutoLink !== undefined && !shouldAutoLink(link.value))) {\n return false\n }\n\n return options.editor.commands.setMark(options.type, {\n href: link.href,\n })\n },\n },\n })\n}\n", "import { Link } from './link.js'\n\nexport * from './link.js'\n\nexport default Link\n"], + "mappings": ";;;;;;;;;;;;;;AAGA,IAAM,cAAc;AAEpB,IAAM,eAAe;AAgBrB,IAAM,UAAU;AAChB,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,eAAe;AACrB,IAAM,eAAe;AACrB,IAAM,SAAS;AACf,IAAM,QAAQ;AACd,IAAM,SAAS;AACf,IAAM,cAAc;AACpB,IAAM,aAAa;AAQnB,SAAS,cAAc,MAAM,QAAQ;AACnC,MAAI,EAAE,QAAQ,SAAS;AACrB,WAAO,IAAI,IAAI,CAAC;AAAA,EAClB;AACA,SAAO,OAAO,IAAI;AACpB;AAQA,SAAS,YAAY,GAAG,OAAO,QAAQ;AACrC,MAAI,MAAM,OAAO,GAAG;AAClB,UAAM,YAAY,IAAI;AACtB,UAAM,YAAY,IAAI;AAAA,EACxB;AACA,MAAI,MAAM,KAAK,GAAG;AAChB,UAAM,YAAY,IAAI;AACtB,UAAM,KAAK,IAAI;AAAA,EACjB;AACA,MAAI,MAAM,YAAY,GAAG;AACvB,UAAM,YAAY,IAAI;AAAA,EACxB;AACA,MAAI,MAAM,KAAK,GAAG;AAChB,UAAM,YAAY,I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KAAK,QAAQ;MACrC,CAAC;IACH;AAEA,QAAI,KAAK,QAAQ,aAAa;AAC5B,cAAQ;QACN,aAAa;UACX,QAAQ,KAAK;UACb,iBAAiB,KAAK,QAAQ;UAC9B,MAAM,KAAK;UACX,gBAAgB,KAAK,QAAQ;QAC/B,CAAC;MACH;IACF;AAEA,WAAO;EACT;AACF,CAAC;AKpeD,IAAO,gBAAQ;", + "names": ["nextState", "regexp", "Nl", "scheme", "options", "scheme", "options", "options", "tr", "Plugin", "PluginKey", "find"] +} diff --git a/frontend/node_modules/.vite/deps/chunk-YRIELJS7.js b/frontend/node_modules/.vite/deps/chunk-YRIELJS7.js new file mode 100644 index 00000000..7ec10bc8 --- /dev/null +++ b/frontend/node_modules/.vite/deps/chunk-YRIELJS7.js @@ -0,0 +1,18528 @@ +// node_modules/orderedmap/dist/index.js +function OrderedMap(content) { + this.content = content; +} +OrderedMap.prototype = { + constructor: OrderedMap, + find: function(key) { + for (var i = 0; i < this.content.length; i += 2) + if (this.content[i] === key) return i; + return -1; + }, + // :: (string) → ?any + // Retrieve the value stored under `key`, or return undefined when + // no such key exists. + get: function(key) { + var found2 = this.find(key); + return found2 == -1 ? void 0 : this.content[found2 + 1]; + }, + // :: (string, any, ?string) → OrderedMap + // Create a new map by replacing the value of `key` with a new + // value, or adding a binding to the end of the map. If `newKey` is + // given, the key of the binding will be replaced with that key. + update: function(key, value, newKey) { + var self = newKey && newKey != key ? this.remove(newKey) : this; + var found2 = self.find(key), content = self.content.slice(); + if (found2 == -1) { + content.push(newKey || key, value); + } else { + content[found2 + 1] = value; + if (newKey) content[found2] = newKey; + } + return new OrderedMap(content); + }, + // :: (string) → OrderedMap + // Return a map with the given key removed, if it existed. + remove: function(key) { + var found2 = this.find(key); + if (found2 == -1) return this; + var content = this.content.slice(); + content.splice(found2, 2); + return new OrderedMap(content); + }, + // :: (string, any) → OrderedMap + // Add a new key to the start of the map. + addToStart: function(key, value) { + return new OrderedMap([key, value].concat(this.remove(key).content)); + }, + // :: (string, any) → OrderedMap + // Add a new key to the end of the map. + addToEnd: function(key, value) { + var content = this.remove(key).content.slice(); + content.push(key, value); + return new OrderedMap(content); + }, + // :: (string, string, any) → OrderedMap + // Add a key after the given key. If `place` is not found, the new + // key is added to the end. + addBefore: function(place, key, value) { + var without = this.remove(key), content = without.content.slice(); + var found2 = without.find(place); + content.splice(found2 == -1 ? content.length : found2, 0, key, value); + return new OrderedMap(content); + }, + // :: ((key: string, value: any)) + // Call the given function for each key/value pair in the map, in + // order. + forEach: function(f) { + for (var i = 0; i < this.content.length; i += 2) + f(this.content[i], this.content[i + 1]); + }, + // :: (union) → OrderedMap + // Create a new map by prepending the keys in this map that don't + // appear in `map` before the keys in `map`. + prepend: function(map) { + map = OrderedMap.from(map); + if (!map.size) return this; + return new OrderedMap(map.content.concat(this.subtract(map).content)); + }, + // :: (union) → OrderedMap + // Create a new map by appending the keys in this map that don't + // appear in `map` after the keys in `map`. + append: function(map) { + map = OrderedMap.from(map); + if (!map.size) return this; + return new OrderedMap(this.subtract(map).content.concat(map.content)); + }, + // :: (union) → OrderedMap + // Create a map containing all the keys in this map that don't + // appear in `map`. + subtract: function(map) { + var result = this; + map = OrderedMap.from(map); + for (var i = 0; i < map.content.length; i += 2) + result = result.remove(map.content[i]); + return result; + }, + // :: () → Object + // Turn ordered map into a plain object. + toObject: function() { + var result = {}; + this.forEach(function(key, value) { + result[key] = value; + }); + return result; + }, + // :: number + // The amount of keys in this map. + get size() { + return this.content.length >> 1; + } +}; +OrderedMap.from = function(value) { + if (value instanceof OrderedMap) return value; + var content = []; + if (value) for (var prop in value) content.push(prop, value[prop]); + return new OrderedMap(content); +}; +var dist_default = OrderedMap; + +// node_modules/prosemirror-model/dist/index.js +function findDiffStart(a, b, pos) { + for (let i = 0; ; i++) { + if (i == a.childCount || i == b.childCount) + return a.childCount == b.childCount ? null : pos; + let childA = a.child(i), childB = b.child(i); + if (childA == childB) { + pos += childA.nodeSize; + continue; + } + if (!childA.sameMarkup(childB)) + return pos; + if (childA.isText && childA.text != childB.text) { + for (let j = 0; childA.text[j] == childB.text[j]; j++) + pos++; + return pos; + } + if (childA.content.size || childB.content.size) { + let inner = findDiffStart(childA.content, childB.content, pos + 1); + if (inner != null) + return inner; + } + pos += childA.nodeSize; + } +} +function findDiffEnd(a, b, posA, posB) { + for (let iA = a.childCount, iB = b.childCount; ; ) { + if (iA == 0 || iB == 0) + return iA == iB ? null : { a: posA, b: posB }; + let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize; + if (childA == childB) { + posA -= size; + posB -= size; + continue; + } + if (!childA.sameMarkup(childB)) + return { a: posA, b: posB }; + if (childA.isText && childA.text != childB.text) { + let same = 0, minSize = Math.min(childA.text.length, childB.text.length); + while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) { + same++; + posA--; + posB--; + } + return { a: posA, b: posB }; + } + if (childA.content.size || childB.content.size) { + let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1); + if (inner) + return inner; + } + posA -= size; + posB -= size; + } +} +var Fragment = class _Fragment { + /** + @internal + */ + constructor(content, size) { + this.content = content; + this.size = size || 0; + if (size == null) + for (let i = 0; i < content.length; i++) + this.size += content[i].nodeSize; + } + /** + Invoke a callback for all descendant nodes between the given two + positions (relative to start of this fragment). Doesn't descend + into a node when the callback returns `false`. + */ + nodesBetween(from, to, f, nodeStart = 0, parent) { + for (let i = 0, pos = 0; pos < to; i++) { + let child = this.content[i], end = pos + child.nodeSize; + if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) { + let start = pos + 1; + child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start); + } + pos = end; + } + } + /** + Call the given callback for every descendant node. `pos` will be + relative to the start of the fragment. The callback may return + `false` to prevent traversal of a given node's children. + */ + descendants(f) { + this.nodesBetween(0, this.size, f); + } + /** + Extract the text between `from` and `to`. See the same method on + [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween). + */ + textBetween(from, to, blockSeparator, leafText) { + let text = "", first2 = true; + this.nodesBetween(from, to, (node, pos) => { + let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : ""; + if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) { + if (first2) + first2 = false; + else + text += blockSeparator; + } + text += nodeText; + }, 0); + return text; + } + /** + Create a new fragment containing the combined content of this + fragment and the other. + */ + append(other) { + if (!other.size) + return this; + if (!this.size) + return other; + let last = this.lastChild, first2 = other.firstChild, content = this.content.slice(), i = 0; + if (last.isText && last.sameMarkup(first2)) { + content[content.length - 1] = last.withText(last.text + first2.text); + i = 1; + } + for (; i < other.content.length; i++) + content.push(other.content[i]); + return new _Fragment(content, this.size + other.size); + } + /** + Cut out the sub-fragment between the two given positions. + */ + cut(from, to = this.size) { + if (from == 0 && to == this.size) + return this; + let result = [], size = 0; + if (to > from) + for (let i = 0, pos = 0; pos < to; i++) { + let child = this.content[i], end = pos + child.nodeSize; + if (end > from) { + if (pos < from || end > to) { + if (child.isText) + child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos)); + else + child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1)); + } + result.push(child); + size += child.nodeSize; + } + pos = end; + } + return new _Fragment(result, size); + } + /** + @internal + */ + cutByIndex(from, to) { + if (from == to) + return _Fragment.empty; + if (from == 0 && to == this.content.length) + return this; + return new _Fragment(this.content.slice(from, to)); + } + /** + Create a new fragment in which the node at the given index is + replaced by the given node. + */ + replaceChild(index, node) { + let current = this.content[index]; + if (current == node) + return this; + let copy2 = this.content.slice(); + let size = this.size + node.nodeSize - current.nodeSize; + copy2[index] = node; + return new _Fragment(copy2, size); + } + /** + Create a new fragment by prepending the given node to this + fragment. + */ + addToStart(node) { + return new _Fragment([node].concat(this.content), this.size + node.nodeSize); + } + /** + Create a new fragment by appending the given node to this + fragment. + */ + addToEnd(node) { + return new _Fragment(this.content.concat(node), this.size + node.nodeSize); + } + /** + Compare this fragment to another one. + */ + eq(other) { + if (this.content.length != other.content.length) + return false; + for (let i = 0; i < this.content.length; i++) + if (!this.content[i].eq(other.content[i])) + return false; + return true; + } + /** + The first child of the fragment, or `null` if it is empty. + */ + get firstChild() { + return this.content.length ? this.content[0] : null; + } + /** + The last child of the fragment, or `null` if it is empty. + */ + get lastChild() { + return this.content.length ? this.content[this.content.length - 1] : null; + } + /** + The number of child nodes in this fragment. + */ + get childCount() { + return this.content.length; + } + /** + Get the child node at the given index. Raise an error when the + index is out of range. + */ + child(index) { + let found2 = this.content[index]; + if (!found2) + throw new RangeError("Index " + index + " out of range for " + this); + return found2; + } + /** + Get the child node at the given index, if it exists. + */ + maybeChild(index) { + return this.content[index] || null; + } + /** + Call `f` for every child node, passing the node, its offset + into this parent node, and its index. + */ + forEach(f) { + for (let i = 0, p = 0; i < this.content.length; i++) { + let child = this.content[i]; + f(child, p, i); + p += child.nodeSize; + } + } + /** + Find the first position at which this fragment and another + fragment differ, or `null` if they are the same. + */ + findDiffStart(other, pos = 0) { + return findDiffStart(this, other, pos); + } + /** + Find the first position, searching from the end, at which this + fragment and the given fragment differ, or `null` if they are + the same. Since this position will not be the same in both + nodes, an object with two separate positions is returned. + */ + findDiffEnd(other, pos = this.size, otherPos = other.size) { + return findDiffEnd(this, other, pos, otherPos); + } + /** + Find the index and inner offset corresponding to a given relative + position in this fragment. The result object will be reused + (overwritten) the next time the function is called. @internal + */ + findIndex(pos) { + if (pos == 0) + return retIndex(0, pos); + if (pos == this.size) + return retIndex(this.content.length, pos); + if (pos > this.size || pos < 0) + throw new RangeError(`Position ${pos} outside of fragment (${this})`); + for (let i = 0, curPos = 0; ; i++) { + let cur = this.child(i), end = curPos + cur.nodeSize; + if (end >= pos) { + if (end == pos) + return retIndex(i + 1, end); + return retIndex(i, curPos); + } + curPos = end; + } + } + /** + Return a debugging string that describes this fragment. + */ + toString() { + return "<" + this.toStringInner() + ">"; + } + /** + @internal + */ + toStringInner() { + return this.content.join(", "); + } + /** + Create a JSON-serializeable representation of this fragment. + */ + toJSON() { + return this.content.length ? this.content.map((n) => n.toJSON()) : null; + } + /** + Deserialize a fragment from its JSON representation. + */ + static fromJSON(schema, value) { + if (!value) + return _Fragment.empty; + if (!Array.isArray(value)) + throw new RangeError("Invalid input for Fragment.fromJSON"); + return new _Fragment(value.map(schema.nodeFromJSON)); + } + /** + Build a fragment from an array of nodes. Ensures that adjacent + text nodes with the same marks are joined together. + */ + static fromArray(array) { + if (!array.length) + return _Fragment.empty; + let joined, size = 0; + for (let i = 0; i < array.length; i++) { + let node = array[i]; + size += node.nodeSize; + if (i && node.isText && array[i - 1].sameMarkup(node)) { + if (!joined) + joined = array.slice(0, i); + joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text); + } else if (joined) { + joined.push(node); + } + } + return new _Fragment(joined || array, size); + } + /** + Create a fragment from something that can be interpreted as a + set of nodes. For `null`, it returns the empty fragment. For a + fragment, the fragment itself. For a node or array of nodes, a + fragment containing those nodes. + */ + static from(nodes) { + if (!nodes) + return _Fragment.empty; + if (nodes instanceof _Fragment) + return nodes; + if (Array.isArray(nodes)) + return this.fromArray(nodes); + if (nodes.attrs) + return new _Fragment([nodes], nodes.nodeSize); + throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")); + } +}; +Fragment.empty = new Fragment([], 0); +var found = { index: 0, offset: 0 }; +function retIndex(index, offset) { + found.index = index; + found.offset = offset; + return found; +} +function compareDeep(a, b) { + if (a === b) + return true; + if (!(a && typeof a == "object") || !(b && typeof b == "object")) + return false; + let array = Array.isArray(a); + if (Array.isArray(b) != array) + return false; + if (array) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!compareDeep(a[i], b[i])) + return false; + } else { + for (let p in a) + if (!(p in b) || !compareDeep(a[p], b[p])) + return false; + for (let p in b) + if (!(p in a)) + return false; + } + return true; +} +var Mark = class _Mark2 { + /** + @internal + */ + constructor(type, attrs) { + this.type = type; + this.attrs = attrs; + } + /** + Given a set of marks, create a new set which contains this one as + well, in the right position. If this mark is already in the set, + the set itself is returned. If any marks that are set to be + [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present, + those are replaced by this one. + */ + addToSet(set) { + let copy2, placed = false; + for (let i = 0; i < set.length; i++) { + let other = set[i]; + if (this.eq(other)) + return set; + if (this.type.excludes(other.type)) { + if (!copy2) + copy2 = set.slice(0, i); + } else if (other.type.excludes(this.type)) { + return set; + } else { + if (!placed && other.type.rank > this.type.rank) { + if (!copy2) + copy2 = set.slice(0, i); + copy2.push(this); + placed = true; + } + if (copy2) + copy2.push(other); + } + } + if (!copy2) + copy2 = set.slice(); + if (!placed) + copy2.push(this); + return copy2; + } + /** + Remove this mark from the given set, returning a new set. If this + mark is not in the set, the set itself is returned. + */ + removeFromSet(set) { + for (let i = 0; i < set.length; i++) + if (this.eq(set[i])) + return set.slice(0, i).concat(set.slice(i + 1)); + return set; + } + /** + Test whether this mark is in the given set of marks. + */ + isInSet(set) { + for (let i = 0; i < set.length; i++) + if (this.eq(set[i])) + return true; + return false; + } + /** + Test whether this mark has the same type and attributes as + another mark. + */ + eq(other) { + return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs); + } + /** + Convert this mark to a JSON-serializeable representation. + */ + toJSON() { + let obj = { type: this.type.name }; + for (let _ in this.attrs) { + obj.attrs = this.attrs; + break; + } + return obj; + } + /** + Deserialize a mark from JSON. + */ + static fromJSON(schema, json) { + if (!json) + throw new RangeError("Invalid input for Mark.fromJSON"); + let type = schema.marks[json.type]; + if (!type) + throw new RangeError(`There is no mark type ${json.type} in this schema`); + let mark = type.create(json.attrs); + type.checkAttrs(mark.attrs); + return mark; + } + /** + Test whether two sets of marks are identical. + */ + static sameSet(a, b) { + if (a == b) + return true; + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!a[i].eq(b[i])) + return false; + return true; + } + /** + Create a properly sorted mark set from null, a single mark, or an + unsorted array of marks. + */ + static setFrom(marks) { + if (!marks || Array.isArray(marks) && marks.length == 0) + return _Mark2.none; + if (marks instanceof _Mark2) + return [marks]; + let copy2 = marks.slice(); + copy2.sort((a, b) => a.type.rank - b.type.rank); + return copy2; + } +}; +Mark.none = []; +var ReplaceError = class extends Error { +}; +var Slice = class _Slice { + /** + Create a slice. When specifying a non-zero open depth, you must + make sure that there are nodes of at least that depth at the + appropriate side of the fragment—i.e. if the fragment is an + empty paragraph node, `openStart` and `openEnd` can't be greater + than 1. + + It is not necessary for the content of open nodes to conform to + the schema's content constraints, though it should be a valid + start/end/middle for such a node, depending on which sides are + open. + */ + constructor(content, openStart, openEnd) { + this.content = content; + this.openStart = openStart; + this.openEnd = openEnd; + } + /** + The size this slice would add when inserted into a document. + */ + get size() { + return this.content.size - this.openStart - this.openEnd; + } + /** + @internal + */ + insertAt(pos, fragment) { + let content = insertInto(this.content, pos + this.openStart, fragment); + return content && new _Slice(content, this.openStart, this.openEnd); + } + /** + @internal + */ + removeBetween(from, to) { + return new _Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd); + } + /** + Tests whether this slice is equal to another slice. + */ + eq(other) { + return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd; + } + /** + @internal + */ + toString() { + return this.content + "(" + this.openStart + "," + this.openEnd + ")"; + } + /** + Convert a slice to a JSON-serializable representation. + */ + toJSON() { + if (!this.content.size) + return null; + let json = { content: this.content.toJSON() }; + if (this.openStart > 0) + json.openStart = this.openStart; + if (this.openEnd > 0) + json.openEnd = this.openEnd; + return json; + } + /** + Deserialize a slice from its JSON representation. + */ + static fromJSON(schema, json) { + if (!json) + return _Slice.empty; + let openStart = json.openStart || 0, openEnd = json.openEnd || 0; + if (typeof openStart != "number" || typeof openEnd != "number") + throw new RangeError("Invalid input for Slice.fromJSON"); + return new _Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd); + } + /** + Create a slice from a fragment by taking the maximum possible + open value on both side of the fragment. + */ + static maxOpen(fragment, openIsolating = true) { + let openStart = 0, openEnd = 0; + for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) + openStart++; + for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) + openEnd++; + return new _Slice(fragment, openStart, openEnd); + } +}; +Slice.empty = new Slice(Fragment.empty, 0, 0); +function removeRange(content, from, to) { + let { index, offset } = content.findIndex(from), child = content.maybeChild(index); + let { index: indexTo, offset: offsetTo } = content.findIndex(to); + if (offset == from || child.isText) { + if (offsetTo != to && !content.child(indexTo).isText) + throw new RangeError("Removing non-flat range"); + return content.cut(0, from).append(content.cut(to)); + } + if (index != indexTo) + throw new RangeError("Removing non-flat range"); + return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1))); +} +function insertInto(content, dist, insert, parent) { + let { index, offset } = content.findIndex(dist), child = content.maybeChild(index); + if (offset == dist || child.isText) { + if (parent && !parent.canReplace(index, index, insert)) + return null; + return content.cut(0, dist).append(insert).append(content.cut(dist)); + } + let inner = insertInto(child.content, dist - offset - 1, insert, child); + return inner && content.replaceChild(index, child.copy(inner)); +} +function replace($from, $to, slice) { + if (slice.openStart > $from.depth) + throw new ReplaceError("Inserted content deeper than insertion position"); + if ($from.depth - slice.openStart != $to.depth - slice.openEnd) + throw new ReplaceError("Inconsistent open depths"); + return replaceOuter($from, $to, slice, 0); +} +function replaceOuter($from, $to, slice, depth) { + let index = $from.index(depth), node = $from.node(depth); + if (index == $to.index(depth) && depth < $from.depth - slice.openStart) { + let inner = replaceOuter($from, $to, slice, depth + 1); + return node.copy(node.content.replaceChild(index, inner)); + } else if (!slice.content.size) { + return close(node, replaceTwoWay($from, $to, depth)); + } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { + let parent = $from.parent, content = parent.content; + return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset))); + } else { + let { start, end } = prepareSliceForReplace(slice, $from); + return close(node, replaceThreeWay($from, start, end, $to, depth)); + } +} +function checkJoin(main, sub) { + if (!sub.type.compatibleContent(main.type)) + throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name); +} +function joinable($before, $after, depth) { + let node = $before.node(depth); + checkJoin(node, $after.node(depth)); + return node; +} +function addNode(child, target) { + let last = target.length - 1; + if (last >= 0 && child.isText && child.sameMarkup(target[last])) + target[last] = child.withText(target[last].text + child.text); + else + target.push(child); +} +function addRange($start, $end, depth, target) { + let node = ($end || $start).node(depth); + let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount; + if ($start) { + startIndex = $start.index(depth); + if ($start.depth > depth) { + startIndex++; + } else if ($start.textOffset) { + addNode($start.nodeAfter, target); + startIndex++; + } + } + for (let i = startIndex; i < endIndex; i++) + addNode(node.child(i), target); + if ($end && $end.depth == depth && $end.textOffset) + addNode($end.nodeBefore, target); +} +function close(node, content) { + node.type.checkContent(content); + return node.copy(content); +} +function replaceThreeWay($from, $start, $end, $to, depth) { + let openStart = $from.depth > depth && joinable($from, $start, depth + 1); + let openEnd = $to.depth > depth && joinable($end, $to, depth + 1); + let content = []; + addRange(null, $from, depth, content); + if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { + checkJoin(openStart, openEnd); + addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content); + } else { + if (openStart) + addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); + addRange($start, $end, depth, content); + if (openEnd) + addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); + } + addRange($to, null, depth, content); + return new Fragment(content); +} +function replaceTwoWay($from, $to, depth) { + let content = []; + addRange(null, $from, depth, content); + if ($from.depth > depth) { + let type = joinable($from, $to, depth + 1); + addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content); + } + addRange($to, null, depth, content); + return new Fragment(content); +} +function prepareSliceForReplace(slice, $along) { + let extra = $along.depth - slice.openStart, parent = $along.node(extra); + let node = parent.copy(slice.content); + for (let i = extra - 1; i >= 0; i--) + node = $along.node(i).copy(Fragment.from(node)); + return { + start: node.resolveNoCache(slice.openStart + extra), + end: node.resolveNoCache(node.content.size - slice.openEnd - extra) + }; +} +var ResolvedPos = class _ResolvedPos { + /** + @internal + */ + constructor(pos, path, parentOffset) { + this.pos = pos; + this.path = path; + this.parentOffset = parentOffset; + this.depth = path.length / 3 - 1; + } + /** + @internal + */ + resolveDepth(val) { + if (val == null) + return this.depth; + if (val < 0) + return this.depth + val; + return val; + } + /** + The parent node that the position points into. Note that even if + a position points into a text node, that node is not considered + the parent—text nodes are ‘flat’ in this model, and have no content. + */ + get parent() { + return this.node(this.depth); + } + /** + The root node in which the position was resolved. + */ + get doc() { + return this.node(0); + } + /** + The ancestor node at the given level. `p.node(p.depth)` is the + same as `p.parent`. + */ + node(depth) { + return this.path[this.resolveDepth(depth) * 3]; + } + /** + The index into the ancestor at the given level. If this points + at the 3rd node in the 2nd paragraph on the top level, for + example, `p.index(0)` is 1 and `p.index(1)` is 2. + */ + index(depth) { + return this.path[this.resolveDepth(depth) * 3 + 1]; + } + /** + The index pointing after this position into the ancestor at the + given level. + */ + indexAfter(depth) { + depth = this.resolveDepth(depth); + return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1); + } + /** + The (absolute) position at the start of the node at the given + level. + */ + start(depth) { + depth = this.resolveDepth(depth); + return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; + } + /** + The (absolute) position at the end of the node at the given + level. + */ + end(depth) { + depth = this.resolveDepth(depth); + return this.start(depth) + this.node(depth).content.size; + } + /** + The (absolute) position directly before the wrapping node at the + given level, or, when `depth` is `this.depth + 1`, the original + position. + */ + before(depth) { + depth = this.resolveDepth(depth); + if (!depth) + throw new RangeError("There is no position before the top-level node"); + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]; + } + /** + The (absolute) position directly after the wrapping node at the + given level, or the original position when `depth` is `this.depth + 1`. + */ + after(depth) { + depth = this.resolveDepth(depth); + if (!depth) + throw new RangeError("There is no position after the top-level node"); + return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize; + } + /** + When this position points into a text node, this returns the + distance between the position and the start of the text node. + Will be zero for positions that point between nodes. + */ + get textOffset() { + return this.pos - this.path[this.path.length - 1]; + } + /** + Get the node directly after the position, if any. If the position + points into a text node, only the part of that node after the + position is returned. + */ + get nodeAfter() { + let parent = this.parent, index = this.index(this.depth); + if (index == parent.childCount) + return null; + let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index); + return dOff ? parent.child(index).cut(dOff) : child; + } + /** + Get the node directly before the position, if any. If the + position points into a text node, only the part of that node + before the position is returned. + */ + get nodeBefore() { + let index = this.index(this.depth); + let dOff = this.pos - this.path[this.path.length - 1]; + if (dOff) + return this.parent.child(index).cut(0, dOff); + return index == 0 ? null : this.parent.child(index - 1); + } + /** + Get the position at the given index in the parent node at the + given depth (which defaults to `this.depth`). + */ + posAtIndex(index, depth) { + depth = this.resolveDepth(depth); + let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; + for (let i = 0; i < index; i++) + pos += node.child(i).nodeSize; + return pos; + } + /** + Get the marks at this position, factoring in the surrounding + marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the + position is at the start of a non-empty node, the marks of the + node after it (if any) are returned. + */ + marks() { + let parent = this.parent, index = this.index(); + if (parent.content.size == 0) + return Mark.none; + if (this.textOffset) + return parent.child(index).marks; + let main = parent.maybeChild(index - 1), other = parent.maybeChild(index); + if (!main) { + let tmp = main; + main = other; + other = tmp; + } + let marks = main.marks; + for (var i = 0; i < marks.length; i++) + if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) + marks = marks[i--].removeFromSet(marks); + return marks; + } + /** + Get the marks after the current position, if any, except those + that are non-inclusive and not present at position `$end`. This + is mostly useful for getting the set of marks to preserve after a + deletion. Will return `null` if this position is at the end of + its parent node or its parent node isn't a textblock (in which + case no marks should be preserved). + */ + marksAcross($end) { + let after = this.parent.maybeChild(this.index()); + if (!after || !after.isInline) + return null; + let marks = after.marks, next = $end.parent.maybeChild($end.index()); + for (var i = 0; i < marks.length; i++) + if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) + marks = marks[i--].removeFromSet(marks); + return marks; + } + /** + The depth up to which this position and the given (non-resolved) + position share the same parent nodes. + */ + sharedDepth(pos) { + for (let depth = this.depth; depth > 0; depth--) + if (this.start(depth) <= pos && this.end(depth) >= pos) + return depth; + return 0; + } + /** + Returns a range based on the place where this position and the + given position diverge around block content. If both point into + the same textblock, for example, a range around that textblock + will be returned. If they point into different blocks, the range + around those blocks in their shared ancestor is returned. You can + pass in an optional predicate that will be called with a parent + node to see if a range into that parent is acceptable. + */ + blockRange(other = this, pred) { + if (other.pos < this.pos) + return other.blockRange(this); + for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) + if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) + return new NodeRange(this, other, d); + return null; + } + /** + Query whether the given position shares the same parent node. + */ + sameParent(other) { + return this.pos - this.parentOffset == other.pos - other.parentOffset; + } + /** + Return the greater of this and the given position. + */ + max(other) { + return other.pos > this.pos ? other : this; + } + /** + Return the smaller of this and the given position. + */ + min(other) { + return other.pos < this.pos ? other : this; + } + /** + @internal + */ + toString() { + let str = ""; + for (let i = 1; i <= this.depth; i++) + str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1); + return str + ":" + this.parentOffset; + } + /** + @internal + */ + static resolve(doc3, pos) { + if (!(pos >= 0 && pos <= doc3.content.size)) + throw new RangeError("Position " + pos + " out of range"); + let path = []; + let start = 0, parentOffset = pos; + for (let node = doc3; ; ) { + let { index, offset } = node.content.findIndex(parentOffset); + let rem = parentOffset - offset; + path.push(node, index, start + offset); + if (!rem) + break; + node = node.child(index); + if (node.isText) + break; + parentOffset = rem - 1; + start += offset + 1; + } + return new _ResolvedPos(pos, path, parentOffset); + } + /** + @internal + */ + static resolveCached(doc3, pos) { + let cache = resolveCache.get(doc3); + if (cache) { + for (let i = 0; i < cache.elts.length; i++) { + let elt = cache.elts[i]; + if (elt.pos == pos) + return elt; + } + } else { + resolveCache.set(doc3, cache = new ResolveCache()); + } + let result = cache.elts[cache.i] = _ResolvedPos.resolve(doc3, pos); + cache.i = (cache.i + 1) % resolveCacheSize; + return result; + } +}; +var ResolveCache = class { + constructor() { + this.elts = []; + this.i = 0; + } +}; +var resolveCacheSize = 12; +var resolveCache = /* @__PURE__ */ new WeakMap(); +var NodeRange = class { + /** + Construct a node range. `$from` and `$to` should point into the + same node until at least the given `depth`, since a node range + denotes an adjacent set of nodes in a single parent node. + */ + constructor($from, $to, depth) { + this.$from = $from; + this.$to = $to; + this.depth = depth; + } + /** + The position at the start of the range. + */ + get start() { + return this.$from.before(this.depth + 1); + } + /** + The position at the end of the range. + */ + get end() { + return this.$to.after(this.depth + 1); + } + /** + The parent node that the range points into. + */ + get parent() { + return this.$from.node(this.depth); + } + /** + The start index of the range in the parent node. + */ + get startIndex() { + return this.$from.index(this.depth); + } + /** + The end index of the range in the parent node. + */ + get endIndex() { + return this.$to.indexAfter(this.depth); + } +}; +var emptyAttrs = /* @__PURE__ */ Object.create(null); +var Node = class _Node2 { + /** + @internal + */ + constructor(type, attrs, content, marks = Mark.none) { + this.type = type; + this.attrs = attrs; + this.marks = marks; + this.content = content || Fragment.empty; + } + /** + The array of this node's child nodes. + */ + get children() { + return this.content.content; + } + /** + The size of this node, as defined by the integer-based [indexing + scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the + amount of characters. For other leaf nodes, it is one. For + non-leaf nodes, it is the size of the content plus two (the + start and end token). + */ + get nodeSize() { + return this.isLeaf ? 1 : 2 + this.content.size; + } + /** + The number of children that the node has. + */ + get childCount() { + return this.content.childCount; + } + /** + Get the child node at the given index. Raises an error when the + index is out of range. + */ + child(index) { + return this.content.child(index); + } + /** + Get the child node at the given index, if it exists. + */ + maybeChild(index) { + return this.content.maybeChild(index); + } + /** + Call `f` for every child node, passing the node, its offset + into this parent node, and its index. + */ + forEach(f) { + this.content.forEach(f); + } + /** + Invoke a callback for all descendant nodes recursively between + the given two positions that are relative to start of this + node's content. The callback is invoked with the node, its + position relative to the original node (method receiver), + its parent node, and its child index. When the callback returns + false for a given node, that node's children will not be + recursed over. The last parameter can be used to specify a + starting position to count from. + */ + nodesBetween(from, to, f, startPos = 0) { + this.content.nodesBetween(from, to, f, startPos, this); + } + /** + Call the given callback for every descendant node. Doesn't + descend into a node when the callback returns `false`. + */ + descendants(f) { + this.nodesBetween(0, this.content.size, f); + } + /** + Concatenates all the text nodes found in this fragment and its + children. + */ + get textContent() { + return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, ""); + } + /** + Get all text between positions `from` and `to`. When + `blockSeparator` is given, it will be inserted to separate text + from different block nodes. If `leafText` is given, it'll be + inserted for every non-text leaf node encountered, otherwise + [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used. + */ + textBetween(from, to, blockSeparator, leafText) { + return this.content.textBetween(from, to, blockSeparator, leafText); + } + /** + Returns this node's first child, or `null` if there are no + children. + */ + get firstChild() { + return this.content.firstChild; + } + /** + Returns this node's last child, or `null` if there are no + children. + */ + get lastChild() { + return this.content.lastChild; + } + /** + Test whether two nodes represent the same piece of document. + */ + eq(other) { + return this == other || this.sameMarkup(other) && this.content.eq(other.content); + } + /** + Compare the markup (type, attributes, and marks) of this node to + those of another. Returns `true` if both have the same markup. + */ + sameMarkup(other) { + return this.hasMarkup(other.type, other.attrs, other.marks); + } + /** + Check whether this node's markup correspond to the given type, + attributes, and marks. + */ + hasMarkup(type, attrs, marks) { + return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none); + } + /** + Create a new node with the same markup as this node, containing + the given content (or empty, if no content is given). + */ + copy(content = null) { + if (content == this.content) + return this; + return new _Node2(this.type, this.attrs, content, this.marks); + } + /** + Create a copy of this node, with the given set of marks instead + of the node's own marks. + */ + mark(marks) { + return marks == this.marks ? this : new _Node2(this.type, this.attrs, this.content, marks); + } + /** + Create a copy of this node with only the content between the + given positions. If `to` is not given, it defaults to the end of + the node. + */ + cut(from, to = this.content.size) { + if (from == 0 && to == this.content.size) + return this; + return this.copy(this.content.cut(from, to)); + } + /** + Cut out the part of the document between the given positions, and + return it as a `Slice` object. + */ + slice(from, to = this.content.size, includeParents = false) { + if (from == to) + return Slice.empty; + let $from = this.resolve(from), $to = this.resolve(to); + let depth = includeParents ? 0 : $from.sharedDepth(to); + let start = $from.start(depth), node = $from.node(depth); + let content = node.content.cut($from.pos - start, $to.pos - start); + return new Slice(content, $from.depth - depth, $to.depth - depth); + } + /** + Replace the part of the document between the given positions with + the given slice. The slice must 'fit', meaning its open sides + must be able to connect to the surrounding content, and its + content nodes must be valid children for the node they are placed + into. If any of this is violated, an error of type + [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown. + */ + replace(from, to, slice) { + return replace(this.resolve(from), this.resolve(to), slice); + } + /** + Find the node directly after the given position. + */ + nodeAt(pos) { + for (let node = this; ; ) { + let { index, offset } = node.content.findIndex(pos); + node = node.maybeChild(index); + if (!node) + return null; + if (offset == pos || node.isText) + return node; + pos -= offset + 1; + } + } + /** + Find the (direct) child node after the given offset, if any, + and return it along with its index and offset relative to this + node. + */ + childAfter(pos) { + let { index, offset } = this.content.findIndex(pos); + return { node: this.content.maybeChild(index), index, offset }; + } + /** + Find the (direct) child node before the given offset, if any, + and return it along with its index and offset relative to this + node. + */ + childBefore(pos) { + if (pos == 0) + return { node: null, index: 0, offset: 0 }; + let { index, offset } = this.content.findIndex(pos); + if (offset < pos) + return { node: this.content.child(index), index, offset }; + let node = this.content.child(index - 1); + return { node, index: index - 1, offset: offset - node.nodeSize }; + } + /** + Resolve the given position in the document, returning an + [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context. + */ + resolve(pos) { + return ResolvedPos.resolveCached(this, pos); + } + /** + @internal + */ + resolveNoCache(pos) { + return ResolvedPos.resolve(this, pos); + } + /** + Test whether a given mark or mark type occurs in this document + between the two given positions. + */ + rangeHasMark(from, to, type) { + let found2 = false; + if (to > from) + this.nodesBetween(from, to, (node) => { + if (type.isInSet(node.marks)) + found2 = true; + return !found2; + }); + return found2; + } + /** + True when this is a block (non-inline node) + */ + get isBlock() { + return this.type.isBlock; + } + /** + True when this is a textblock node, a block node with inline + content. + */ + get isTextblock() { + return this.type.isTextblock; + } + /** + True when this node allows inline content. + */ + get inlineContent() { + return this.type.inlineContent; + } + /** + True when this is an inline node (a text node or a node that can + appear among text). + */ + get isInline() { + return this.type.isInline; + } + /** + True when this is a text node. + */ + get isText() { + return this.type.isText; + } + /** + True when this is a leaf node. + */ + get isLeaf() { + return this.type.isLeaf; + } + /** + True when this is an atom, i.e. when it does not have directly + editable content. This is usually the same as `isLeaf`, but can + be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom) + on a node's spec (typically used when the node is displayed as + an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)). + */ + get isAtom() { + return this.type.isAtom; + } + /** + Return a string representation of this node for debugging + purposes. + */ + toString() { + if (this.type.spec.toDebugString) + return this.type.spec.toDebugString(this); + let name = this.type.name; + if (this.content.size) + name += "(" + this.content.toStringInner() + ")"; + return wrapMarks(this.marks, name); + } + /** + Get the content match in this node at the given index. + */ + contentMatchAt(index) { + let match = this.type.contentMatch.matchFragment(this.content, 0, index); + if (!match) + throw new Error("Called contentMatchAt on a node with invalid content"); + return match; + } + /** + Test whether replacing the range between `from` and `to` (by + child index) with the given replacement fragment (which defaults + to the empty fragment) would leave the node's content valid. You + can optionally pass `start` and `end` indices into the + replacement fragment. + */ + canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) { + let one = this.contentMatchAt(from).matchFragment(replacement, start, end); + let two = one && one.matchFragment(this.content, to); + if (!two || !two.validEnd) + return false; + for (let i = start; i < end; i++) + if (!this.type.allowsMarks(replacement.child(i).marks)) + return false; + return true; + } + /** + Test whether replacing the range `from` to `to` (by index) with + a node of the given type would leave the node's content valid. + */ + canReplaceWith(from, to, type, marks) { + if (marks && !this.type.allowsMarks(marks)) + return false; + let start = this.contentMatchAt(from).matchType(type); + let end = start && start.matchFragment(this.content, to); + return end ? end.validEnd : false; + } + /** + Test whether the given node's content could be appended to this + node. If that node is empty, this will only return true if there + is at least one node type that can appear in both nodes (to avoid + merging completely incompatible nodes). + */ + canAppend(other) { + if (other.content.size) + return this.canReplace(this.childCount, this.childCount, other.content); + else + return this.type.compatibleContent(other.type); + } + /** + Check whether this node and its descendants conform to the + schema, and raise an exception when they do not. + */ + check() { + this.type.checkContent(this.content); + this.type.checkAttrs(this.attrs); + let copy2 = Mark.none; + for (let i = 0; i < this.marks.length; i++) { + let mark = this.marks[i]; + mark.type.checkAttrs(mark.attrs); + copy2 = mark.addToSet(copy2); + } + if (!Mark.sameSet(copy2, this.marks)) + throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`); + this.content.forEach((node) => node.check()); + } + /** + Return a JSON-serializeable representation of this node. + */ + toJSON() { + let obj = { type: this.type.name }; + for (let _ in this.attrs) { + obj.attrs = this.attrs; + break; + } + if (this.content.size) + obj.content = this.content.toJSON(); + if (this.marks.length) + obj.marks = this.marks.map((n) => n.toJSON()); + return obj; + } + /** + Deserialize a node from its JSON representation. + */ + static fromJSON(schema, json) { + if (!json) + throw new RangeError("Invalid input for Node.fromJSON"); + let marks = void 0; + if (json.marks) { + if (!Array.isArray(json.marks)) + throw new RangeError("Invalid mark data for Node.fromJSON"); + marks = json.marks.map(schema.markFromJSON); + } + if (json.type == "text") { + if (typeof json.text != "string") + throw new RangeError("Invalid text node in JSON"); + return schema.text(json.text, marks); + } + let content = Fragment.fromJSON(schema, json.content); + let node = schema.nodeType(json.type).create(json.attrs, content, marks); + node.type.checkAttrs(node.attrs); + return node; + } +}; +Node.prototype.text = void 0; +var TextNode = class _TextNode extends Node { + /** + @internal + */ + constructor(type, attrs, content, marks) { + super(type, attrs, null, marks); + if (!content) + throw new RangeError("Empty text nodes are not allowed"); + this.text = content; + } + toString() { + if (this.type.spec.toDebugString) + return this.type.spec.toDebugString(this); + return wrapMarks(this.marks, JSON.stringify(this.text)); + } + get textContent() { + return this.text; + } + textBetween(from, to) { + return this.text.slice(from, to); + } + get nodeSize() { + return this.text.length; + } + mark(marks) { + return marks == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks); + } + withText(text) { + if (text == this.text) + return this; + return new _TextNode(this.type, this.attrs, text, this.marks); + } + cut(from = 0, to = this.text.length) { + if (from == 0 && to == this.text.length) + return this; + return this.withText(this.text.slice(from, to)); + } + eq(other) { + return this.sameMarkup(other) && this.text == other.text; + } + toJSON() { + let base2 = super.toJSON(); + base2.text = this.text; + return base2; + } +}; +function wrapMarks(marks, str) { + for (let i = marks.length - 1; i >= 0; i--) + str = marks[i].type.name + "(" + str + ")"; + return str; +} +var ContentMatch = class _ContentMatch { + /** + @internal + */ + constructor(validEnd) { + this.validEnd = validEnd; + this.next = []; + this.wrapCache = []; + } + /** + @internal + */ + static parse(string, nodeTypes) { + let stream = new TokenStream(string, nodeTypes); + if (stream.next == null) + return _ContentMatch.empty; + let expr = parseExpr(stream); + if (stream.next) + stream.err("Unexpected trailing text"); + let match = dfa(nfa(expr)); + checkForDeadEnds(match, stream); + return match; + } + /** + Match a node type, returning a match after that node if + successful. + */ + matchType(type) { + for (let i = 0; i < this.next.length; i++) + if (this.next[i].type == type) + return this.next[i].next; + return null; + } + /** + Try to match a fragment. Returns the resulting match when + successful. + */ + matchFragment(frag, start = 0, end = frag.childCount) { + let cur = this; + for (let i = start; cur && i < end; i++) + cur = cur.matchType(frag.child(i).type); + return cur; + } + /** + @internal + */ + get inlineContent() { + return this.next.length != 0 && this.next[0].type.isInline; + } + /** + Get the first matching node type at this match position that can + be generated. + */ + get defaultType() { + for (let i = 0; i < this.next.length; i++) { + let { type } = this.next[i]; + if (!(type.isText || type.hasRequiredAttrs())) + return type; + } + return null; + } + /** + @internal + */ + compatible(other) { + for (let i = 0; i < this.next.length; i++) + for (let j = 0; j < other.next.length; j++) + if (this.next[i].type == other.next[j].type) + return true; + return false; + } + /** + Try to match the given fragment, and if that fails, see if it can + be made to match by inserting nodes in front of it. When + successful, return a fragment of inserted nodes (which may be + empty if nothing had to be inserted). When `toEnd` is true, only + return a fragment if the resulting match goes to the end of the + content expression. + */ + fillBefore(after, toEnd = false, startIndex = 0) { + let seen = [this]; + function search(match, types) { + let finished = match.matchFragment(after, startIndex); + if (finished && (!toEnd || finished.validEnd)) + return Fragment.from(types.map((tp) => tp.createAndFill())); + for (let i = 0; i < match.next.length; i++) { + let { type, next } = match.next[i]; + if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { + seen.push(next); + let found2 = search(next, types.concat(type)); + if (found2) + return found2; + } + } + return null; + } + return search(this, []); + } + /** + Find a set of wrapping node types that would allow a node of the + given type to appear at this position. The result may be empty + (when it fits directly) and will be null when no such wrapping + exists. + */ + findWrapping(target) { + for (let i = 0; i < this.wrapCache.length; i += 2) + if (this.wrapCache[i] == target) + return this.wrapCache[i + 1]; + let computed = this.computeWrapping(target); + this.wrapCache.push(target, computed); + return computed; + } + /** + @internal + */ + computeWrapping(target) { + let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }]; + while (active.length) { + let current = active.shift(), match = current.match; + if (match.matchType(target)) { + let result = []; + for (let obj = current; obj.type; obj = obj.via) + result.push(obj.type); + return result.reverse(); + } + for (let i = 0; i < match.next.length; i++) { + let { type, next } = match.next[i]; + if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) { + active.push({ match: type.contentMatch, type, via: current }); + seen[type.name] = true; + } + } + } + return null; + } + /** + The number of outgoing edges this node has in the finite + automaton that describes the content expression. + */ + get edgeCount() { + return this.next.length; + } + /** + Get the _n_​th outgoing edge from this node in the finite + automaton that describes the content expression. + */ + edge(n) { + if (n >= this.next.length) + throw new RangeError(`There's no ${n}th edge in this content match`); + return this.next[n]; + } + /** + @internal + */ + toString() { + let seen = []; + function scan(m) { + seen.push(m); + for (let i = 0; i < m.next.length; i++) + if (seen.indexOf(m.next[i].next) == -1) + scan(m.next[i].next); + } + scan(this); + return seen.map((m, i) => { + let out = i + (m.validEnd ? "*" : " ") + " "; + for (let i2 = 0; i2 < m.next.length; i2++) + out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next); + return out; + }).join("\n"); + } +}; +ContentMatch.empty = new ContentMatch(true); +var TokenStream = class { + constructor(string, nodeTypes) { + this.string = string; + this.nodeTypes = nodeTypes; + this.inline = null; + this.pos = 0; + this.tokens = string.split(/\s*(?=\b|\W|$)/); + if (this.tokens[this.tokens.length - 1] == "") + this.tokens.pop(); + if (this.tokens[0] == "") + this.tokens.shift(); + } + get next() { + return this.tokens[this.pos]; + } + eat(tok) { + return this.next == tok && (this.pos++ || true); + } + err(str) { + throw new SyntaxError(str + " (in content expression '" + this.string + "')"); + } +}; +function parseExpr(stream) { + let exprs = []; + do { + exprs.push(parseExprSeq(stream)); + } while (stream.eat("|")); + return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; +} +function parseExprSeq(stream) { + let exprs = []; + do { + exprs.push(parseExprSubscript(stream)); + } while (stream.next && stream.next != ")" && stream.next != "|"); + return exprs.length == 1 ? exprs[0] : { type: "seq", exprs }; +} +function parseExprSubscript(stream) { + let expr = parseExprAtom(stream); + for (; ; ) { + if (stream.eat("+")) + expr = { type: "plus", expr }; + else if (stream.eat("*")) + expr = { type: "star", expr }; + else if (stream.eat("?")) + expr = { type: "opt", expr }; + else if (stream.eat("{")) + expr = parseExprRange(stream, expr); + else + break; + } + return expr; +} +function parseNum(stream) { + if (/\D/.test(stream.next)) + stream.err("Expected number, got '" + stream.next + "'"); + let result = Number(stream.next); + stream.pos++; + return result; +} +function parseExprRange(stream, expr) { + let min = parseNum(stream), max = min; + if (stream.eat(",")) { + if (stream.next != "}") + max = parseNum(stream); + else + max = -1; + } + if (!stream.eat("}")) + stream.err("Unclosed braced range"); + return { type: "range", min, max, expr }; +} +function resolveName(stream, name) { + let types = stream.nodeTypes, type = types[name]; + if (type) + return [type]; + let result = []; + for (let typeName in types) { + let type2 = types[typeName]; + if (type2.isInGroup(name)) + result.push(type2); + } + if (result.length == 0) + stream.err("No node type or group '" + name + "' found"); + return result; +} +function parseExprAtom(stream) { + if (stream.eat("(")) { + let expr = parseExpr(stream); + if (!stream.eat(")")) + stream.err("Missing closing paren"); + return expr; + } else if (!/\W/.test(stream.next)) { + let exprs = resolveName(stream, stream.next).map((type) => { + if (stream.inline == null) + stream.inline = type.isInline; + else if (stream.inline != type.isInline) + stream.err("Mixing inline and block content"); + return { type: "name", value: type }; + }); + stream.pos++; + return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; + } else { + stream.err("Unexpected token '" + stream.next + "'"); + } +} +function nfa(expr) { + let nfa2 = [[]]; + connect(compile(expr, 0), node()); + return nfa2; + function node() { + return nfa2.push([]) - 1; + } + function edge(from, to, term) { + let edge2 = { term, to }; + nfa2[from].push(edge2); + return edge2; + } + function connect(edges, to) { + edges.forEach((edge2) => edge2.to = to); + } + function compile(expr2, from) { + if (expr2.type == "choice") { + return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from)), []); + } else if (expr2.type == "seq") { + for (let i = 0; ; i++) { + let next = compile(expr2.exprs[i], from); + if (i == expr2.exprs.length - 1) + return next; + connect(next, from = node()); + } + } else if (expr2.type == "star") { + let loop = node(); + edge(from, loop); + connect(compile(expr2.expr, loop), loop); + return [edge(loop)]; + } else if (expr2.type == "plus") { + let loop = node(); + connect(compile(expr2.expr, from), loop); + connect(compile(expr2.expr, loop), loop); + return [edge(loop)]; + } else if (expr2.type == "opt") { + return [edge(from)].concat(compile(expr2.expr, from)); + } else if (expr2.type == "range") { + let cur = from; + for (let i = 0; i < expr2.min; i++) { + let next = node(); + connect(compile(expr2.expr, cur), next); + cur = next; + } + if (expr2.max == -1) { + connect(compile(expr2.expr, cur), cur); + } else { + for (let i = expr2.min; i < expr2.max; i++) { + let next = node(); + edge(cur, next); + connect(compile(expr2.expr, cur), next); + cur = next; + } + } + return [edge(cur)]; + } else if (expr2.type == "name") { + return [edge(from, void 0, expr2.value)]; + } else { + throw new Error("Unknown expr type"); + } + } +} +function cmp(a, b) { + return b - a; +} +function nullFrom(nfa2, node) { + let result = []; + scan(node); + return result.sort(cmp); + function scan(node2) { + let edges = nfa2[node2]; + if (edges.length == 1 && !edges[0].term) + return scan(edges[0].to); + result.push(node2); + for (let i = 0; i < edges.length; i++) { + let { term, to } = edges[i]; + if (!term && result.indexOf(to) == -1) + scan(to); + } + } +} +function dfa(nfa2) { + let labeled = /* @__PURE__ */ Object.create(null); + return explore(nullFrom(nfa2, 0)); + function explore(states) { + let out = []; + states.forEach((node) => { + nfa2[node].forEach(({ term, to }) => { + if (!term) + return; + let set; + for (let i = 0; i < out.length; i++) + if (out[i][0] == term) + set = out[i][1]; + nullFrom(nfa2, to).forEach((node2) => { + if (!set) + out.push([term, set = []]); + if (set.indexOf(node2) == -1) + set.push(node2); + }); + }); + }); + let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1); + for (let i = 0; i < out.length; i++) { + let states2 = out[i][1].sort(cmp); + state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) }); + } + return state; + } +} +function checkForDeadEnds(match, stream) { + for (let i = 0, work = [match]; i < work.length; i++) { + let state = work[i], dead = !state.validEnd, nodes = []; + for (let j = 0; j < state.next.length; j++) { + let { type, next } = state.next[j]; + nodes.push(type.name); + if (dead && !(type.isText || type.hasRequiredAttrs())) + dead = false; + if (work.indexOf(next) == -1) + work.push(next); + } + if (dead) + stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)"); + } +} +function defaultAttrs(attrs) { + let defaults = /* @__PURE__ */ Object.create(null); + for (let attrName in attrs) { + let attr = attrs[attrName]; + if (!attr.hasDefault) + return null; + defaults[attrName] = attr.default; + } + return defaults; +} +function computeAttrs(attrs, value) { + let built = /* @__PURE__ */ Object.create(null); + for (let name in attrs) { + let given = value && value[name]; + if (given === void 0) { + let attr = attrs[name]; + if (attr.hasDefault) + given = attr.default; + else + throw new RangeError("No value supplied for attribute " + name); + } + built[name] = given; + } + return built; +} +function checkAttrs(attrs, values, type, name) { + for (let name2 in values) + if (!(name2 in attrs)) + throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`); + for (let name2 in attrs) { + let attr = attrs[name2]; + if (attr.validate) + attr.validate(values[name2]); + } +} +function initAttrs(typeName, attrs) { + let result = /* @__PURE__ */ Object.create(null); + if (attrs) + for (let name in attrs) + result[name] = new Attribute(typeName, name, attrs[name]); + return result; +} +var NodeType = class _NodeType { + /** + @internal + */ + constructor(name, schema, spec) { + this.name = name; + this.schema = schema; + this.spec = spec; + this.markSet = null; + this.groups = spec.group ? spec.group.split(" ") : []; + this.attrs = initAttrs(name, spec.attrs); + this.defaultAttrs = defaultAttrs(this.attrs); + this.contentMatch = null; + this.inlineContent = null; + this.isBlock = !(spec.inline || name == "text"); + this.isText = name == "text"; + } + /** + True if this is an inline type. + */ + get isInline() { + return !this.isBlock; + } + /** + True if this is a textblock type, a block that contains inline + content. + */ + get isTextblock() { + return this.isBlock && this.inlineContent; + } + /** + True for node types that allow no content. + */ + get isLeaf() { + return this.contentMatch == ContentMatch.empty; + } + /** + True when this node is an atom, i.e. when it does not have + directly editable content. + */ + get isAtom() { + return this.isLeaf || !!this.spec.atom; + } + /** + Return true when this node type is part of the given + [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group). + */ + isInGroup(group) { + return this.groups.indexOf(group) > -1; + } + /** + The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option. + */ + get whitespace() { + return this.spec.whitespace || (this.spec.code ? "pre" : "normal"); + } + /** + Tells you whether this node type has any required attributes. + */ + hasRequiredAttrs() { + for (let n in this.attrs) + if (this.attrs[n].isRequired) + return true; + return false; + } + /** + Indicates whether this node allows some of the same content as + the given node type. + */ + compatibleContent(other) { + return this == other || this.contentMatch.compatible(other.contentMatch); + } + /** + @internal + */ + computeAttrs(attrs) { + if (!attrs && this.defaultAttrs) + return this.defaultAttrs; + else + return computeAttrs(this.attrs, attrs); + } + /** + Create a `Node` of this type. The given attributes are + checked and defaulted (you can pass `null` to use the type's + defaults entirely, if no required attributes exist). `content` + may be a `Fragment`, a node, an array of nodes, or + `null`. Similarly `marks` may be `null` to default to the empty + set of marks. + */ + create(attrs = null, content, marks) { + if (this.isText) + throw new Error("NodeType.create can't construct text nodes"); + return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks)); + } + /** + Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content + against the node type's content restrictions, and throw an error + if it doesn't match. + */ + createChecked(attrs = null, content, marks) { + content = Fragment.from(content); + this.checkContent(content); + return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks)); + } + /** + Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is + necessary to add nodes to the start or end of the given fragment + to make it fit the node. If no fitting wrapping can be found, + return null. Note that, due to the fact that required nodes can + always be created, this will always succeed if you pass null or + `Fragment.empty` as content. + */ + createAndFill(attrs = null, content, marks) { + attrs = this.computeAttrs(attrs); + content = Fragment.from(content); + if (content.size) { + let before = this.contentMatch.fillBefore(content); + if (!before) + return null; + content = before.append(content); + } + let matched = this.contentMatch.matchFragment(content); + let after = matched && matched.fillBefore(Fragment.empty, true); + if (!after) + return null; + return new Node(this, attrs, content.append(after), Mark.setFrom(marks)); + } + /** + Returns true if the given fragment is valid content for this node + type. + */ + validContent(content) { + let result = this.contentMatch.matchFragment(content); + if (!result || !result.validEnd) + return false; + for (let i = 0; i < content.childCount; i++) + if (!this.allowsMarks(content.child(i).marks)) + return false; + return true; + } + /** + Throws a RangeError if the given fragment is not valid content for this + node type. + @internal + */ + checkContent(content) { + if (!this.validContent(content)) + throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`); + } + /** + @internal + */ + checkAttrs(attrs) { + checkAttrs(this.attrs, attrs, "node", this.name); + } + /** + Check whether the given mark type is allowed in this node. + */ + allowsMarkType(markType) { + return this.markSet == null || this.markSet.indexOf(markType) > -1; + } + /** + Test whether the given set of marks are allowed in this node. + */ + allowsMarks(marks) { + if (this.markSet == null) + return true; + for (let i = 0; i < marks.length; i++) + if (!this.allowsMarkType(marks[i].type)) + return false; + return true; + } + /** + Removes the marks that are not allowed in this node from the given set. + */ + allowedMarks(marks) { + if (this.markSet == null) + return marks; + let copy2; + for (let i = 0; i < marks.length; i++) { + if (!this.allowsMarkType(marks[i].type)) { + if (!copy2) + copy2 = marks.slice(0, i); + } else if (copy2) { + copy2.push(marks[i]); + } + } + return !copy2 ? marks : copy2.length ? copy2 : Mark.none; + } + /** + @internal + */ + static compile(nodes, schema) { + let result = /* @__PURE__ */ Object.create(null); + nodes.forEach((name, spec) => result[name] = new _NodeType(name, schema, spec)); + let topType = schema.spec.topNode || "doc"; + if (!result[topType]) + throw new RangeError("Schema is missing its top node type ('" + topType + "')"); + if (!result.text) + throw new RangeError("Every schema needs a 'text' type"); + for (let _ in result.text.attrs) + throw new RangeError("The text node type should not have attributes"); + return result; + } +}; +function validateType(typeName, attrName, type) { + let types = type.split("|"); + return (value) => { + let name = value === null ? "null" : typeof value; + if (types.indexOf(name) < 0) + throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`); + }; +} +var Attribute = class { + constructor(typeName, attrName, options) { + this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default"); + this.default = options.default; + this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate; + } + get isRequired() { + return !this.hasDefault; + } +}; +var MarkType = class _MarkType { + /** + @internal + */ + constructor(name, rank, schema, spec) { + this.name = name; + this.rank = rank; + this.schema = schema; + this.spec = spec; + this.attrs = initAttrs(name, spec.attrs); + this.excluded = null; + let defaults = defaultAttrs(this.attrs); + this.instance = defaults ? new Mark(this, defaults) : null; + } + /** + Create a mark of this type. `attrs` may be `null` or an object + containing only some of the mark's attributes. The others, if + they have defaults, will be added. + */ + create(attrs = null) { + if (!attrs && this.instance) + return this.instance; + return new Mark(this, computeAttrs(this.attrs, attrs)); + } + /** + @internal + */ + static compile(marks, schema) { + let result = /* @__PURE__ */ Object.create(null), rank = 0; + marks.forEach((name, spec) => result[name] = new _MarkType(name, rank++, schema, spec)); + return result; + } + /** + When there is a mark of this type in the given set, a new set + without it is returned. Otherwise, the input set is returned. + */ + removeFromSet(set) { + for (var i = 0; i < set.length; i++) + if (set[i].type == this) { + set = set.slice(0, i).concat(set.slice(i + 1)); + i--; + } + return set; + } + /** + Tests whether there is a mark of this type in the given set. + */ + isInSet(set) { + for (let i = 0; i < set.length; i++) + if (set[i].type == this) + return set[i]; + } + /** + @internal + */ + checkAttrs(attrs) { + checkAttrs(this.attrs, attrs, "mark", this.name); + } + /** + Queries whether a given mark type is + [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one. + */ + excludes(other) { + return this.excluded.indexOf(other) > -1; + } +}; +var Schema = class { + /** + Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec). + */ + constructor(spec) { + this.linebreakReplacement = null; + this.cached = /* @__PURE__ */ Object.create(null); + let instanceSpec = this.spec = {}; + for (let prop in spec) + instanceSpec[prop] = spec[prop]; + instanceSpec.nodes = dist_default.from(spec.nodes), instanceSpec.marks = dist_default.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this); + this.marks = MarkType.compile(this.spec.marks, this); + let contentExprCache = /* @__PURE__ */ Object.create(null); + for (let prop in this.nodes) { + if (prop in this.marks) + throw new RangeError(prop + " can not be both a node and a mark"); + let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks; + type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)); + type.inlineContent = type.contentMatch.inlineContent; + if (type.spec.linebreakReplacement) { + if (this.linebreakReplacement) + throw new RangeError("Multiple linebreak nodes defined"); + if (!type.isInline || !type.isLeaf) + throw new RangeError("Linebreak replacement nodes must be inline leaf nodes"); + this.linebreakReplacement = type; + } + type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null; + } + for (let prop in this.marks) { + let type = this.marks[prop], excl = type.spec.excludes; + type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" ")); + } + this.nodeFromJSON = (json) => Node.fromJSON(this, json); + this.markFromJSON = (json) => Mark.fromJSON(this, json); + this.topNodeType = this.nodes[this.spec.topNode || "doc"]; + this.cached.wrappings = /* @__PURE__ */ Object.create(null); + } + /** + Create a node in this schema. The `type` may be a string or a + `NodeType` instance. Attributes will be extended with defaults, + `content` may be a `Fragment`, `null`, a `Node`, or an array of + nodes. + */ + node(type, attrs = null, content, marks) { + if (typeof type == "string") + type = this.nodeType(type); + else if (!(type instanceof NodeType)) + throw new RangeError("Invalid node type: " + type); + else if (type.schema != this) + throw new RangeError("Node type from different schema used (" + type.name + ")"); + return type.createChecked(attrs, content, marks); + } + /** + Create a text node in the schema. Empty text nodes are not + allowed. + */ + text(text, marks) { + let type = this.nodes.text; + return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks)); + } + /** + Create a mark with the given type and attributes. + */ + mark(type, attrs) { + if (typeof type == "string") + type = this.marks[type]; + return type.create(attrs); + } + /** + @internal + */ + nodeType(name) { + let found2 = this.nodes[name]; + if (!found2) + throw new RangeError("Unknown node type: " + name); + return found2; + } +}; +function gatherMarks(schema, marks) { + let found2 = []; + for (let i = 0; i < marks.length; i++) { + let name = marks[i], mark = schema.marks[name], ok = mark; + if (mark) { + found2.push(mark); + } else { + for (let prop in schema.marks) { + let mark2 = schema.marks[prop]; + if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1) + found2.push(ok = mark2); + } + } + if (!ok) + throw new SyntaxError("Unknown mark type: '" + marks[i] + "'"); + } + return found2; +} +function isTagRule(rule) { + return rule.tag != null; +} +function isStyleRule(rule) { + return rule.style != null; +} +var DOMParser = class _DOMParser { + /** + Create a parser that targets the given schema, using the given + parsing rules. + */ + constructor(schema, rules) { + this.schema = schema; + this.rules = rules; + this.tags = []; + this.styles = []; + let matchedStyles = this.matchedStyles = []; + rules.forEach((rule) => { + if (isTagRule(rule)) { + this.tags.push(rule); + } else if (isStyleRule(rule)) { + let prop = /[^=]*/.exec(rule.style)[0]; + if (matchedStyles.indexOf(prop) < 0) + matchedStyles.push(prop); + this.styles.push(rule); + } + }); + this.normalizeLists = !this.tags.some((r) => { + if (!/^(ul|ol)\b/.test(r.tag) || !r.node) + return false; + let node = schema.nodes[r.node]; + return node.contentMatch.matchType(node); + }); + } + /** + Parse a document from the content of a DOM node. + */ + parse(dom, options = {}) { + let context = new ParseContext(this, options, false); + context.addAll(dom, Mark.none, options.from, options.to); + return context.finish(); + } + /** + Parses the content of the given DOM node, like + [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of + options. But unlike that method, which produces a whole node, + this one returns a slice that is open at the sides, meaning that + the schema constraints aren't applied to the start of nodes to + the left of the input and the end of nodes at the end. + */ + parseSlice(dom, options = {}) { + let context = new ParseContext(this, options, true); + context.addAll(dom, Mark.none, options.from, options.to); + return Slice.maxOpen(context.finish()); + } + /** + @internal + */ + matchTag(dom, context, after) { + for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) { + let rule = this.tags[i]; + if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) { + if (rule.getAttrs) { + let result = rule.getAttrs(dom); + if (result === false) + continue; + rule.attrs = result || void 0; + } + return rule; + } + } + } + /** + @internal + */ + matchStyle(prop, value, context, after) { + for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) { + let rule = this.styles[i], style2 = rule.style; + if (style2.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop, + // or has an '=' sign after the prop, followed by the given + // value. + style2.length > prop.length && (style2.charCodeAt(prop.length) != 61 || style2.slice(prop.length + 1) != value)) + continue; + if (rule.getAttrs) { + let result = rule.getAttrs(value); + if (result === false) + continue; + rule.attrs = result || void 0; + } + return rule; + } + } + /** + @internal + */ + static schemaRules(schema) { + let result = []; + function insert(rule) { + let priority = rule.priority == null ? 50 : rule.priority, i = 0; + for (; i < result.length; i++) { + let next = result[i], nextPriority = next.priority == null ? 50 : next.priority; + if (nextPriority < priority) + break; + } + result.splice(i, 0, rule); + } + for (let name in schema.marks) { + let rules = schema.marks[name].spec.parseDOM; + if (rules) + rules.forEach((rule) => { + insert(rule = copy(rule)); + if (!(rule.mark || rule.ignore || rule.clearMark)) + rule.mark = name; + }); + } + for (let name in schema.nodes) { + let rules = schema.nodes[name].spec.parseDOM; + if (rules) + rules.forEach((rule) => { + insert(rule = copy(rule)); + if (!(rule.node || rule.ignore || rule.mark)) + rule.node = name; + }); + } + return result; + } + /** + Construct a DOM parser using the parsing rules listed in a + schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by + [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority). + */ + static fromSchema(schema) { + return schema.cached.domParser || (schema.cached.domParser = new _DOMParser(schema, _DOMParser.schemaRules(schema))); + } +}; +var blockTags = { + address: true, + article: true, + aside: true, + blockquote: true, + canvas: true, + dd: true, + div: true, + dl: true, + fieldset: true, + figcaption: true, + figure: true, + footer: true, + form: true, + h1: true, + h2: true, + h3: true, + h4: true, + h5: true, + h6: true, + header: true, + hgroup: true, + hr: true, + li: true, + noscript: true, + ol: true, + output: true, + p: true, + pre: true, + section: true, + table: true, + tfoot: true, + ul: true +}; +var ignoreTags = { + head: true, + noscript: true, + object: true, + script: true, + style: true, + title: true +}; +var listTags = { ol: true, ul: true }; +var OPT_PRESERVE_WS = 1; +var OPT_PRESERVE_WS_FULL = 2; +var OPT_OPEN_LEFT = 4; +function wsOptionsFor(type, preserveWhitespace, base2) { + if (preserveWhitespace != null) + return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0); + return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT; +} +var NodeContext = class { + constructor(type, attrs, marks, solid, match, options) { + this.type = type; + this.attrs = attrs; + this.marks = marks; + this.solid = solid; + this.options = options; + this.content = []; + this.activeMarks = Mark.none; + this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch); + } + findWrapping(node) { + if (!this.match) { + if (!this.type) + return []; + let fill = this.type.contentMatch.fillBefore(Fragment.from(node)); + if (fill) { + this.match = this.type.contentMatch.matchFragment(fill); + } else { + let start = this.type.contentMatch, wrap2; + if (wrap2 = start.findWrapping(node.type)) { + this.match = start; + return wrap2; + } else { + return null; + } + } + } + return this.match.findWrapping(node.type); + } + finish(openEnd) { + if (!(this.options & OPT_PRESERVE_WS)) { + let last = this.content[this.content.length - 1], m; + if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { + let text = last; + if (last.text.length == m[0].length) + this.content.pop(); + else + this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length)); + } + } + let content = Fragment.from(this.content); + if (!openEnd && this.match) + content = content.append(this.match.fillBefore(Fragment.empty, true)); + return this.type ? this.type.create(this.attrs, content, this.marks) : content; + } + inlineContext(node) { + if (this.type) + return this.type.inlineContent; + if (this.content.length) + return this.content[0].isInline; + return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase()); + } +}; +var ParseContext = class { + constructor(parser, options, isOpen) { + this.parser = parser; + this.options = options; + this.isOpen = isOpen; + this.open = 0; + this.localPreserveWS = false; + let topNode = options.topNode, topContext; + let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0); + if (topNode) + topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions); + else if (isOpen) + topContext = new NodeContext(null, null, Mark.none, true, null, topOptions); + else + topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions); + this.nodes = [topContext]; + this.find = options.findPositions; + this.needsBlock = false; + } + get top() { + return this.nodes[this.open]; + } + // Add a DOM node to the content. Text is inserted as text node, + // otherwise, the node is passed to `addElement` or, if it has a + // `style` attribute, `addElementWithStyles`. + addDOM(dom, marks) { + if (dom.nodeType == 3) + this.addTextNode(dom, marks); + else if (dom.nodeType == 1) + this.addElement(dom, marks); + } + addTextNode(dom, marks) { + let value = dom.nodeValue; + let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0; + let { schema } = this.parser; + if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) { + if (!preserveWS) { + value = value.replace(/[ \t\r\n\u000c]+/g, " "); + if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { + let nodeBefore = top.content[top.content.length - 1]; + let domNodeBefore = dom.previousSibling; + if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)) + value = value.slice(1); + } + } else if (preserveWS === "full") { + value = value.replace(/\r\n?/g, "\n"); + } else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) { + let lines = value.split(/\r?\n|\r/); + for (let i = 0; i < lines.length; i++) { + if (i) + this.insertNode(schema.linebreakReplacement.create(), marks, true); + if (lines[i]) + this.insertNode(schema.text(lines[i]), marks, !/\S/.test(lines[i])); + } + value = ""; + } else { + value = value.replace(/\r?\n|\r/g, " "); + } + if (value) + this.insertNode(schema.text(value), marks, !/\S/.test(value)); + this.findInText(dom); + } else { + this.findInside(dom); + } + } + // Try to find a handler for the given tag and use that to parse. If + // none is found, the element's content nodes are added directly. + addElement(dom, marks, matchAfter) { + let outerWS = this.localPreserveWS, top = this.top; + if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace)) + this.localPreserveWS = true; + let name = dom.nodeName.toLowerCase(), ruleID; + if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) + normalizeList(dom); + let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter)); + out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { + this.findInside(dom); + this.ignoreFallback(dom, marks); + } else if (!rule || rule.skip || rule.closeParent) { + if (rule && rule.closeParent) + this.open = Math.max(0, this.open - 1); + else if (rule && rule.skip.nodeType) + dom = rule.skip; + let sync, oldNeedsBlock = this.needsBlock; + if (blockTags.hasOwnProperty(name)) { + if (top.content.length && top.content[0].isInline && this.open) { + this.open--; + top = this.top; + } + sync = true; + if (!top.type) + this.needsBlock = true; + } else if (!dom.firstChild) { + this.leafFallback(dom, marks); + break out; + } + let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks); + if (innerMarks) + this.addAll(dom, innerMarks); + if (sync) + this.sync(top); + this.needsBlock = oldNeedsBlock; + } else { + let innerMarks = this.readStyles(dom, marks); + if (innerMarks) + this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0); + } + this.localPreserveWS = outerWS; + } + // Called for leaf DOM nodes that would otherwise be ignored + leafFallback(dom, marks) { + if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) + this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks); + } + // Called for ignored nodes + ignoreFallback(dom, marks) { + if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent)) + this.findPlace(this.parser.schema.text("-"), marks, true); + } + // Run any style parser associated with the node's styles. Either + // return an updated array of marks, or null to indicate some of the + // styles had a rule with `ignore` set. + readStyles(dom, marks) { + let styles = dom.style; + if (styles && styles.length) + for (let i = 0; i < this.parser.matchedStyles.length; i++) { + let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name); + if (value) + for (let after = void 0; ; ) { + let rule = this.parser.matchStyle(name, value, this, after); + if (!rule) + break; + if (rule.ignore) + return null; + if (rule.clearMark) + marks = marks.filter((m) => !rule.clearMark(m)); + else + marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs)); + if (rule.consuming === false) + after = rule; + else + break; + } + } + return marks; + } + // Look up a handler for the given node. If none are found, return + // false. Otherwise, apply it, use its return value to drive the way + // the node's content is wrapped, and return true. + addElementByRule(dom, rule, marks, continueAfter) { + let sync, nodeType; + if (rule.node) { + nodeType = this.parser.schema.nodes[rule.node]; + if (!nodeType.isLeaf) { + let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace); + if (inner) { + sync = true; + marks = inner; + } + } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) { + this.leafFallback(dom, marks); + } + } else { + let markType = this.parser.schema.marks[rule.mark]; + marks = marks.concat(markType.create(rule.attrs)); + } + let startIn = this.top; + if (nodeType && nodeType.isLeaf) { + this.findInside(dom); + } else if (continueAfter) { + this.addElement(dom, marks, continueAfter); + } else if (rule.getContent) { + this.findInside(dom); + rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false)); + } else { + let contentDOM = dom; + if (typeof rule.contentElement == "string") + contentDOM = dom.querySelector(rule.contentElement); + else if (typeof rule.contentElement == "function") + contentDOM = rule.contentElement(dom); + else if (rule.contentElement) + contentDOM = rule.contentElement; + this.findAround(dom, contentDOM, true); + this.addAll(contentDOM, marks); + this.findAround(dom, contentDOM, false); + } + if (sync && this.sync(startIn)) + this.open--; + } + // Add all child nodes between `startIndex` and `endIndex` (or the + // whole node, if not given). If `sync` is passed, use it to + // synchronize after every block element. + addAll(parent, marks, startIndex, endIndex) { + let index = startIndex || 0; + for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) { + this.findAtPoint(parent, index); + this.addDOM(dom, marks); + } + this.findAtPoint(parent, index); + } + // Try to find a way to fit the given node type into the current + // context. May add intermediate wrappers and/or leave non-solid + // nodes that we're in. + findPlace(node, marks, cautious) { + let route, sync; + for (let depth = this.open, penalty = 0; depth >= 0; depth--) { + let cx = this.nodes[depth]; + let found2 = cx.findWrapping(node); + if (found2 && (!route || route.length > found2.length + penalty)) { + route = found2; + sync = cx; + if (!found2.length) + break; + } + if (cx.solid) { + if (cautious) + break; + penalty += 2; + } + } + if (!route) + return null; + this.sync(sync); + for (let i = 0; i < route.length; i++) + marks = this.enterInner(route[i], null, marks, false); + return marks; + } + // Try to insert the given node, adjusting the context when needed. + insertNode(node, marks, cautious) { + if (node.isInline && this.needsBlock && !this.top.type) { + let block = this.textblockFromContext(); + if (block) + marks = this.enterInner(block, null, marks); + } + let innerMarks = this.findPlace(node, marks, cautious); + if (innerMarks) { + this.closeExtra(); + let top = this.top; + if (top.match) + top.match = top.match.matchType(node.type); + let nodeMarks = Mark.none; + for (let m of innerMarks.concat(node.marks)) + if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type)) + nodeMarks = m.addToSet(nodeMarks); + top.content.push(node.mark(nodeMarks)); + return true; + } + return false; + } + // Try to start a node of the given type, adjusting the context when + // necessary. + enter(type, attrs, marks, preserveWS) { + let innerMarks = this.findPlace(type.create(attrs), marks, false); + if (innerMarks) + innerMarks = this.enterInner(type, attrs, marks, true, preserveWS); + return innerMarks; + } + // Open a node of the given type + enterInner(type, attrs, marks, solid = false, preserveWS) { + this.closeExtra(); + let top = this.top; + top.match = top.match && top.match.matchType(type); + let options = wsOptionsFor(type, preserveWS, top.options); + if (top.options & OPT_OPEN_LEFT && top.content.length == 0) + options |= OPT_OPEN_LEFT; + let applyMarks = Mark.none; + marks = marks.filter((m) => { + if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) { + applyMarks = m.addToSet(applyMarks); + return false; + } + return true; + }); + this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options)); + this.open++; + return marks; + } + // Make sure all nodes above this.open are finished and added to + // their parents + closeExtra(openEnd = false) { + let i = this.nodes.length - 1; + if (i > this.open) { + for (; i > this.open; i--) + this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); + this.nodes.length = this.open + 1; + } + } + finish() { + this.open = 0; + this.closeExtra(this.isOpen); + return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen)); + } + sync(to) { + for (let i = this.open; i >= 0; i--) { + if (this.nodes[i] == to) { + this.open = i; + return true; + } else if (this.localPreserveWS) { + this.nodes[i].options |= OPT_PRESERVE_WS; + } + } + return false; + } + get currentPos() { + this.closeExtra(); + let pos = 0; + for (let i = this.open; i >= 0; i--) { + let content = this.nodes[i].content; + for (let j = content.length - 1; j >= 0; j--) + pos += content[j].nodeSize; + if (i) + pos++; + } + return pos; + } + findAtPoint(parent, offset) { + if (this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].node == parent && this.find[i].offset == offset) + this.find[i].pos = this.currentPos; + } + } + findInside(parent) { + if (this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) + this.find[i].pos = this.currentPos; + } + } + findAround(parent, content, before) { + if (parent != content && this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) { + let pos = content.compareDocumentPosition(this.find[i].node); + if (pos & (before ? 2 : 4)) + this.find[i].pos = this.currentPos; + } + } + } + findInText(textNode) { + if (this.find) + for (let i = 0; i < this.find.length; i++) { + if (this.find[i].node == textNode) + this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); + } + } + // Determines whether the given context string matches this context. + matchesContext(context) { + if (context.indexOf("|") > -1) + return context.split(/\s*\|\s*/).some(this.matchesContext, this); + let parts = context.split("/"); + let option = this.options.context; + let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type); + let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1); + let match = (i, depth) => { + for (; i >= 0; i--) { + let part = parts[i]; + if (part == "") { + if (i == parts.length - 1 || i == 0) + continue; + for (; depth >= minDepth; depth--) + if (match(i - 1, depth)) + return true; + return false; + } else { + let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null; + if (!next || next.name != part && !next.isInGroup(part)) + return false; + depth--; + } + } + return true; + }; + return match(parts.length - 1, this.open); + } + textblockFromContext() { + let $context = this.options.context; + if ($context) + for (let d = $context.depth; d >= 0; d--) { + let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType; + if (deflt && deflt.isTextblock && deflt.defaultAttrs) + return deflt; + } + for (let name in this.parser.schema.nodes) { + let type = this.parser.schema.nodes[name]; + if (type.isTextblock && type.defaultAttrs) + return type; + } + } +}; +function normalizeList(dom) { + for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { + let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null; + if (name && listTags.hasOwnProperty(name) && prevItem) { + prevItem.appendChild(child); + child = prevItem; + } else if (name == "li") { + prevItem = child; + } else if (name) { + prevItem = null; + } + } +} +function matches(dom, selector) { + return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector); +} +function copy(obj) { + let copy2 = {}; + for (let prop in obj) + copy2[prop] = obj[prop]; + return copy2; +} +function markMayApply(markType, nodeType) { + let nodes = nodeType.schema.nodes; + for (let name in nodes) { + let parent = nodes[name]; + if (!parent.allowsMarkType(markType)) + continue; + let seen = [], scan = (match) => { + seen.push(match); + for (let i = 0; i < match.edgeCount; i++) { + let { type, next } = match.edge(i); + if (type == nodeType) + return true; + if (seen.indexOf(next) < 0 && scan(next)) + return true; + } + }; + if (scan(parent.contentMatch)) + return true; + } +} +var DOMSerializer = class _DOMSerializer { + /** + Create a serializer. `nodes` should map node names to functions + that take a node and return a description of the corresponding + DOM. `marks` does the same for mark names, but also gets an + argument that tells it whether the mark's content is block or + inline content (for typical use, it'll always be inline). A mark + serializer may be `null` to indicate that marks of that type + should not be serialized. + */ + constructor(nodes, marks) { + this.nodes = nodes; + this.marks = marks; + } + /** + Serialize the content of this fragment to a DOM fragment. When + not in the browser, the `document` option, containing a DOM + document, should be passed so that the serializer can create + nodes. + */ + serializeFragment(fragment, options = {}, target) { + if (!target) + target = doc(options).createDocumentFragment(); + let top = target, active = []; + fragment.forEach((node) => { + if (active.length || node.marks.length) { + let keep = 0, rendered = 0; + while (keep < active.length && rendered < node.marks.length) { + let next = node.marks[rendered]; + if (!this.marks[next.type.name]) { + rendered++; + continue; + } + if (!next.eq(active[keep][0]) || next.type.spec.spanning === false) + break; + keep++; + rendered++; + } + while (keep < active.length) + top = active.pop()[1]; + while (rendered < node.marks.length) { + let add = node.marks[rendered++]; + let markDOM = this.serializeMark(add, node.isInline, options); + if (markDOM) { + active.push([add, top]); + top.appendChild(markDOM.dom); + top = markDOM.contentDOM || markDOM.dom; + } + } + } + top.appendChild(this.serializeNodeInner(node, options)); + }); + return target; + } + /** + @internal + */ + serializeNodeInner(node, options) { + let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs); + if (contentDOM) { + if (node.isLeaf) + throw new RangeError("Content hole not allowed in a leaf node spec"); + this.serializeFragment(node.content, options, contentDOM); + } + return dom; + } + /** + Serialize this node to a DOM node. This can be useful when you + need to serialize a part of a document, as opposed to the whole + document. To serialize a whole document, use + [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on + its [content](https://prosemirror.net/docs/ref/#model.Node.content). + */ + serializeNode(node, options = {}) { + let dom = this.serializeNodeInner(node, options); + for (let i = node.marks.length - 1; i >= 0; i--) { + let wrap2 = this.serializeMark(node.marks[i], node.isInline, options); + if (wrap2) { + (wrap2.contentDOM || wrap2.dom).appendChild(dom); + dom = wrap2.dom; + } + } + return dom; + } + /** + @internal + */ + serializeMark(mark, inline, options = {}) { + let toDOM = this.marks[mark.type.name]; + return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs); + } + static renderSpec(doc3, structure, xmlNS = null, blockArraysIn) { + return renderSpec(doc3, structure, xmlNS, blockArraysIn); + } + /** + Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM) + properties in a schema's node and mark specs. + */ + static fromSchema(schema) { + return schema.cached.domSerializer || (schema.cached.domSerializer = new _DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))); + } + /** + Gather the serializers in a schema's node specs into an object. + This can be useful as a base to build a custom serializer from. + */ + static nodesFromSchema(schema) { + let result = gatherToDOM(schema.nodes); + if (!result.text) + result.text = (node) => node.text; + return result; + } + /** + Gather the serializers in a schema's mark specs into an object. + */ + static marksFromSchema(schema) { + return gatherToDOM(schema.marks); + } +}; +function gatherToDOM(obj) { + let result = {}; + for (let name in obj) { + let toDOM = obj[name].spec.toDOM; + if (toDOM) + result[name] = toDOM; + } + return result; +} +function doc(options) { + return options.document || window.document; +} +var suspiciousAttributeCache = /* @__PURE__ */ new WeakMap(); +function suspiciousAttributes(attrs) { + let value = suspiciousAttributeCache.get(attrs); + if (value === void 0) + suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs)); + return value; +} +function suspiciousAttributesInner(attrs) { + let result = null; + function scan(value) { + if (value && typeof value == "object") { + if (Array.isArray(value)) { + if (typeof value[0] == "string") { + if (!result) + result = []; + result.push(value); + } else { + for (let i = 0; i < value.length; i++) + scan(value[i]); + } + } else { + for (let prop in value) + scan(value[prop]); + } + } + } + scan(attrs); + return result; +} +function renderSpec(doc3, structure, xmlNS, blockArraysIn) { + if (typeof structure == "string") + return { dom: doc3.createTextNode(structure) }; + if (structure.nodeType != null) + return { dom: structure }; + if (structure.dom && structure.dom.nodeType != null) + return structure; + let tagName = structure[0], suspicious; + if (typeof tagName != "string") + throw new RangeError("Invalid array passed to renderSpec"); + if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1) + throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack."); + let space = tagName.indexOf(" "); + if (space > 0) { + xmlNS = tagName.slice(0, space); + tagName = tagName.slice(space + 1); + } + let contentDOM; + let dom = xmlNS ? doc3.createElementNS(xmlNS, tagName) : doc3.createElement(tagName); + let attrs = structure[1], start = 1; + if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { + start = 2; + for (let name in attrs) + if (attrs[name] != null) { + let space2 = name.indexOf(" "); + if (space2 > 0) + dom.setAttributeNS(name.slice(0, space2), name.slice(space2 + 1), attrs[name]); + else if (name == "style" && dom.style) + dom.style.cssText = attrs[name]; + else + dom.setAttribute(name, attrs[name]); + } + } + for (let i = start; i < structure.length; i++) { + let child = structure[i]; + if (child === 0) { + if (i < structure.length - 1 || i > start) + throw new RangeError("Content hole must be the only child of its parent node"); + return { dom, contentDOM: dom }; + } else { + let { dom: inner, contentDOM: innerContent } = renderSpec(doc3, child, xmlNS, blockArraysIn); + dom.appendChild(inner); + if (innerContent) { + if (contentDOM) + throw new RangeError("Multiple content holes"); + contentDOM = innerContent; + } + } + } + return { dom, contentDOM }; +} + +// node_modules/prosemirror-transform/dist/index.js +var lower16 = 65535; +var factor16 = Math.pow(2, 16); +function makeRecover(index, offset) { + return index + offset * factor16; +} +function recoverIndex(value) { + return value & lower16; +} +function recoverOffset(value) { + return (value - (value & lower16)) / factor16; +} +var DEL_BEFORE = 1; +var DEL_AFTER = 2; +var DEL_ACROSS = 4; +var DEL_SIDE = 8; +var MapResult = class { + /** + @internal + */ + constructor(pos, delInfo, recover) { + this.pos = pos; + this.delInfo = delInfo; + this.recover = recover; + } + /** + Tells you whether the position was deleted, that is, whether the + step removed the token on the side queried (via the `assoc`) + argument from the document. + */ + get deleted() { + return (this.delInfo & DEL_SIDE) > 0; + } + /** + Tells you whether the token before the mapped position was deleted. + */ + get deletedBefore() { + return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; + } + /** + True when the token after the mapped position was deleted. + */ + get deletedAfter() { + return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; + } + /** + Tells whether any of the steps mapped through deletes across the + position (including both the token before and after the + position). + */ + get deletedAcross() { + return (this.delInfo & DEL_ACROSS) > 0; + } +}; +var StepMap = class _StepMap { + /** + Create a position map. The modifications to the document are + represented as an array of numbers, in which each group of three + represents a modified chunk as `[start, oldSize, newSize]`. + */ + constructor(ranges, inverted = false) { + this.ranges = ranges; + this.inverted = inverted; + if (!ranges.length && _StepMap.empty) + return _StepMap.empty; + } + /** + @internal + */ + recover(value) { + let diff = 0, index = recoverIndex(value); + if (!this.inverted) + for (let i = 0; i < index; i++) + diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; + return this.ranges[index * 3] + diff + recoverOffset(value); + } + mapResult(pos, assoc = 1) { + return this._map(pos, assoc, false); + } + map(pos, assoc = 1) { + return this._map(pos, assoc, true); + } + /** + @internal + */ + _map(pos, assoc, simple) { + let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (let i = 0; i < this.ranges.length; i += 3) { + let start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) + break; + let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize; + if (pos <= end) { + let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc; + let result = start + diff + (side < 0 ? 0 : newSize); + if (simple) + return result; + let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start); + let del2 = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS; + if (assoc < 0 ? pos != start : pos != end) + del2 |= DEL_SIDE; + return new MapResult(result, del2, recover); + } + diff += newSize - oldSize; + } + return simple ? pos + diff : new MapResult(pos + diff, 0, null); + } + /** + @internal + */ + touches(pos, recover) { + let diff = 0, index = recoverIndex(recover); + let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (let i = 0; i < this.ranges.length; i += 3) { + let start = this.ranges[i] - (this.inverted ? diff : 0); + if (start > pos) + break; + let oldSize = this.ranges[i + oldIndex], end = start + oldSize; + if (pos <= end && i == index * 3) + return true; + diff += this.ranges[i + newIndex] - oldSize; + } + return false; + } + /** + Calls the given function on each of the changed ranges included in + this map. + */ + forEach(f) { + let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; + for (let i = 0, diff = 0; i < this.ranges.length; i += 3) { + let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); + let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex]; + f(oldStart, oldStart + oldSize, newStart, newStart + newSize); + diff += newSize - oldSize; + } + } + /** + Create an inverted version of this map. The result can be used to + map positions in the post-step document to the pre-step document. + */ + invert() { + return new _StepMap(this.ranges, !this.inverted); + } + /** + @internal + */ + toString() { + return (this.inverted ? "-" : "") + JSON.stringify(this.ranges); + } + /** + Create a map that moves all positions by offset `n` (which may be + negative). This can be useful when applying steps meant for a + sub-document to a larger document, or vice-versa. + */ + static offset(n) { + return n == 0 ? _StepMap.empty : new _StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]); + } +}; +StepMap.empty = new StepMap([]); +var Mapping = class _Mapping { + /** + Create a new mapping with the given position maps. + */ + constructor(maps, mirror, from = 0, to = maps ? maps.length : 0) { + this.mirror = mirror; + this.from = from; + this.to = to; + this._maps = maps || []; + this.ownData = !(maps || mirror); + } + /** + The step maps in this mapping. + */ + get maps() { + return this._maps; + } + /** + Create a mapping that maps only through a part of this one. + */ + slice(from = 0, to = this.maps.length) { + return new _Mapping(this._maps, this.mirror, from, to); + } + /** + Add a step map to the end of this mapping. If `mirrors` is + given, it should be the index of the step map that is the mirror + image of this one. + */ + appendMap(map, mirrors) { + if (!this.ownData) { + this._maps = this._maps.slice(); + this.mirror = this.mirror && this.mirror.slice(); + this.ownData = true; + } + this.to = this._maps.push(map); + if (mirrors != null) + this.setMirror(this._maps.length - 1, mirrors); + } + /** + Add all the step maps in a given mapping to this one (preserving + mirroring information). + */ + appendMapping(mapping) { + for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) { + let mirr = mapping.getMirror(i); + this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : void 0); + } + } + /** + Finds the offset of the step map that mirrors the map at the + given offset, in this mapping (as per the second argument to + `appendMap`). + */ + getMirror(n) { + if (this.mirror) { + for (let i = 0; i < this.mirror.length; i++) + if (this.mirror[i] == n) + return this.mirror[i + (i % 2 ? -1 : 1)]; + } + } + /** + @internal + */ + setMirror(n, m) { + if (!this.mirror) + this.mirror = []; + this.mirror.push(n, m); + } + /** + Append the inverse of the given mapping to this one. + */ + appendMappingInverted(mapping) { + for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) { + let mirr = mapping.getMirror(i); + this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : void 0); + } + } + /** + Create an inverted version of this mapping. + */ + invert() { + let inverse = new _Mapping(); + inverse.appendMappingInverted(this); + return inverse; + } + /** + Map a position through this mapping. + */ + map(pos, assoc = 1) { + if (this.mirror) + return this._map(pos, assoc, true); + for (let i = this.from; i < this.to; i++) + pos = this._maps[i].map(pos, assoc); + return pos; + } + /** + Map a position through this mapping, returning a mapping + result. + */ + mapResult(pos, assoc = 1) { + return this._map(pos, assoc, false); + } + /** + @internal + */ + _map(pos, assoc, simple) { + let delInfo = 0; + for (let i = this.from; i < this.to; i++) { + let map = this._maps[i], result = map.mapResult(pos, assoc); + if (result.recover != null) { + let corr = this.getMirror(i); + if (corr != null && corr > i && corr < this.to) { + i = corr; + pos = this._maps[corr].recover(result.recover); + continue; + } + } + delInfo |= result.delInfo; + pos = result.pos; + } + return simple ? pos : new MapResult(pos, delInfo, null); + } +}; +var stepsByID = /* @__PURE__ */ Object.create(null); +var Step = class { + /** + Get the step map that represents the changes made by this step, + and which can be used to transform between positions in the old + and the new document. + */ + getMap() { + return StepMap.empty; + } + /** + Try to merge this step with another one, to be applied directly + after it. Returns the merged step when possible, null if the + steps can't be merged. + */ + merge(other) { + return null; + } + /** + Deserialize a step from its JSON representation. Will call + through to the step class' own implementation of this method. + */ + static fromJSON(schema, json) { + if (!json || !json.stepType) + throw new RangeError("Invalid input for Step.fromJSON"); + let type = stepsByID[json.stepType]; + if (!type) + throw new RangeError(`No step type ${json.stepType} defined`); + return type.fromJSON(schema, json); + } + /** + To be able to serialize steps to JSON, each step needs a string + ID to attach to its JSON representation. Use this method to + register an ID for your step classes. Try to pick something + that's unlikely to clash with steps from other modules. + */ + static jsonID(id, stepClass) { + if (id in stepsByID) + throw new RangeError("Duplicate use of step JSON ID " + id); + stepsByID[id] = stepClass; + stepClass.prototype.jsonID = id; + return stepClass; + } +}; +var StepResult = class _StepResult { + /** + @internal + */ + constructor(doc3, failed) { + this.doc = doc3; + this.failed = failed; + } + /** + Create a successful step result. + */ + static ok(doc3) { + return new _StepResult(doc3, null); + } + /** + Create a failed step result. + */ + static fail(message) { + return new _StepResult(null, message); + } + /** + Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given + arguments. Create a successful result if it succeeds, and a + failed one if it throws a `ReplaceError`. + */ + static fromReplace(doc3, from, to, slice) { + try { + return _StepResult.ok(doc3.replace(from, to, slice)); + } catch (e) { + if (e instanceof ReplaceError) + return _StepResult.fail(e.message); + throw e; + } + } +}; +function mapFragment(fragment, f, parent) { + let mapped = []; + for (let i = 0; i < fragment.childCount; i++) { + let child = fragment.child(i); + if (child.content.size) + child = child.copy(mapFragment(child.content, f, child)); + if (child.isInline) + child = f(child, parent, i); + mapped.push(child); + } + return Fragment.fromArray(mapped); +} +var AddMarkStep = class _AddMarkStep extends Step { + /** + Create a mark step. + */ + constructor(from, to, mark) { + super(); + this.from = from; + this.to = to; + this.mark = mark; + } + apply(doc3) { + let oldSlice = doc3.slice(this.from, this.to), $from = doc3.resolve(this.from); + let parent = $from.node($from.sharedDepth(this.to)); + let slice = new Slice(mapFragment(oldSlice.content, (node, parent2) => { + if (!node.isAtom || !parent2.type.allowsMarkType(this.mark.type)) + return node; + return node.mark(this.mark.addToSet(node.marks)); + }, parent), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc3, this.from, this.to, slice); + } + invert() { + return new RemoveMarkStep(this.from, this.to, this.mark); + } + map(mapping) { + let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted || from.pos >= to.pos) + return null; + return new _AddMarkStep(from.pos, to.pos, this.mark); + } + merge(other) { + if (other instanceof _AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) + return new _AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); + return null; + } + toJSON() { + return { + stepType: "addMark", + mark: this.mark.toJSON(), + from: this.from, + to: this.to + }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + throw new RangeError("Invalid input for AddMarkStep.fromJSON"); + return new _AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); + } +}; +Step.jsonID("addMark", AddMarkStep); +var RemoveMarkStep = class _RemoveMarkStep extends Step { + /** + Create a mark-removing step. + */ + constructor(from, to, mark) { + super(); + this.from = from; + this.to = to; + this.mark = mark; + } + apply(doc3) { + let oldSlice = doc3.slice(this.from, this.to); + let slice = new Slice(mapFragment(oldSlice.content, (node) => { + return node.mark(this.mark.removeFromSet(node.marks)); + }, doc3), oldSlice.openStart, oldSlice.openEnd); + return StepResult.fromReplace(doc3, this.from, this.to, slice); + } + invert() { + return new AddMarkStep(this.from, this.to, this.mark); + } + map(mapping) { + let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deleted && to.deleted || from.pos >= to.pos) + return null; + return new _RemoveMarkStep(from.pos, to.pos, this.mark); + } + merge(other) { + if (other instanceof _RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) + return new _RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); + return null; + } + toJSON() { + return { + stepType: "removeMark", + mark: this.mark.toJSON(), + from: this.from, + to: this.to + }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + throw new RangeError("Invalid input for RemoveMarkStep.fromJSON"); + return new _RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); + } +}; +Step.jsonID("removeMark", RemoveMarkStep); +var AddNodeMarkStep = class _AddNodeMarkStep extends Step { + /** + Create a node mark step. + */ + constructor(pos, mark) { + super(); + this.pos = pos; + this.mark = mark; + } + apply(doc3) { + let node = doc3.nodeAt(this.pos); + if (!node) + return StepResult.fail("No node at mark step's position"); + let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks)); + return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); + } + invert(doc3) { + let node = doc3.nodeAt(this.pos); + if (node) { + let newSet = this.mark.addToSet(node.marks); + if (newSet.length == node.marks.length) { + for (let i = 0; i < node.marks.length; i++) + if (!node.marks[i].isInSet(newSet)) + return new _AddNodeMarkStep(this.pos, node.marks[i]); + return new _AddNodeMarkStep(this.pos, this.mark); + } + } + return new RemoveNodeMarkStep(this.pos, this.mark); + } + map(mapping) { + let pos = mapping.mapResult(this.pos, 1); + return pos.deletedAfter ? null : new _AddNodeMarkStep(pos.pos, this.mark); + } + toJSON() { + return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.pos != "number") + throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON"); + return new _AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); + } +}; +Step.jsonID("addNodeMark", AddNodeMarkStep); +var RemoveNodeMarkStep = class _RemoveNodeMarkStep extends Step { + /** + Create a mark-removing step. + */ + constructor(pos, mark) { + super(); + this.pos = pos; + this.mark = mark; + } + apply(doc3) { + let node = doc3.nodeAt(this.pos); + if (!node) + return StepResult.fail("No node at mark step's position"); + let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks)); + return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); + } + invert(doc3) { + let node = doc3.nodeAt(this.pos); + if (!node || !this.mark.isInSet(node.marks)) + return this; + return new AddNodeMarkStep(this.pos, this.mark); + } + map(mapping) { + let pos = mapping.mapResult(this.pos, 1); + return pos.deletedAfter ? null : new _RemoveNodeMarkStep(pos.pos, this.mark); + } + toJSON() { + return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() }; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.pos != "number") + throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON"); + return new _RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); + } +}; +Step.jsonID("removeNodeMark", RemoveNodeMarkStep); +var ReplaceStep = class _ReplaceStep extends Step { + /** + The given `slice` should fit the 'gap' between `from` and + `to`—the depths must line up, and the surrounding nodes must be + able to be joined with the open sides of the slice. When + `structure` is true, the step will fail if the content between + from and to is not just a sequence of closing and then opening + tokens (this is to guard against rebased replace steps + overwriting something they weren't supposed to). + */ + constructor(from, to, slice, structure = false) { + super(); + this.from = from; + this.to = to; + this.slice = slice; + this.structure = structure; + } + apply(doc3) { + if (this.structure && contentBetween(doc3, this.from, this.to)) + return StepResult.fail("Structure replace would overwrite content"); + return StepResult.fromReplace(doc3, this.from, this.to, this.slice); + } + getMap() { + return new StepMap([this.from, this.to - this.from, this.slice.size]); + } + invert(doc3) { + return new _ReplaceStep(this.from, this.from + this.slice.size, doc3.slice(this.from, this.to)); + } + map(mapping) { + let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + if (from.deletedAcross && to.deletedAcross) + return null; + return new _ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure); + } + merge(other) { + if (!(other instanceof _ReplaceStep) || other.structure || this.structure) + return null; + if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) { + let slice = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd); + return new _ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure); + } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) { + let slice = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd); + return new _ReplaceStep(other.from, this.to, slice, this.structure); + } else { + return null; + } + } + toJSON() { + let json = { stepType: "replace", from: this.from, to: this.to }; + if (this.slice.size) + json.slice = this.slice.toJSON(); + if (this.structure) + json.structure = true; + return json; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number") + throw new RangeError("Invalid input for ReplaceStep.fromJSON"); + return new _ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure); + } +}; +Step.jsonID("replace", ReplaceStep); +var ReplaceAroundStep = class _ReplaceAroundStep extends Step { + /** + Create a replace-around step with the given range and gap. + `insert` should be the point in the slice into which the content + of the gap should be moved. `structure` has the same meaning as + it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class. + */ + constructor(from, to, gapFrom, gapTo, slice, insert, structure = false) { + super(); + this.from = from; + this.to = to; + this.gapFrom = gapFrom; + this.gapTo = gapTo; + this.slice = slice; + this.insert = insert; + this.structure = structure; + } + apply(doc3) { + if (this.structure && (contentBetween(doc3, this.from, this.gapFrom) || contentBetween(doc3, this.gapTo, this.to))) + return StepResult.fail("Structure gap-replace would overwrite content"); + let gap = doc3.slice(this.gapFrom, this.gapTo); + if (gap.openStart || gap.openEnd) + return StepResult.fail("Gap is not a flat range"); + let inserted = this.slice.insertAt(this.insert, gap.content); + if (!inserted) + return StepResult.fail("Content does not fit in gap"); + return StepResult.fromReplace(doc3, this.from, this.to, inserted); + } + getMap() { + return new StepMap([ + this.from, + this.gapFrom - this.from, + this.insert, + this.gapTo, + this.to - this.gapTo, + this.slice.size - this.insert + ]); + } + invert(doc3) { + let gap = this.gapTo - this.gapFrom; + return new _ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc3.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure); + } + map(mapping) { + let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); + let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1); + let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1); + if (from.deletedAcross && to.deletedAcross || gapFrom < from.pos || gapTo > to.pos) + return null; + return new _ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure); + } + toJSON() { + let json = { + stepType: "replaceAround", + from: this.from, + to: this.to, + gapFrom: this.gapFrom, + gapTo: this.gapTo, + insert: this.insert + }; + if (this.slice.size) + json.slice = this.slice.toJSON(); + if (this.structure) + json.structure = true; + return json; + } + /** + @internal + */ + static fromJSON(schema, json) { + if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number") + throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON"); + return new _ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure); + } +}; +Step.jsonID("replaceAround", ReplaceAroundStep); +function contentBetween(doc3, from, to) { + let $from = doc3.resolve(from), dist = to - from, depth = $from.depth; + while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { + depth--; + dist--; + } + if (dist > 0) { + let next = $from.node(depth).maybeChild($from.indexAfter(depth)); + while (dist > 0) { + if (!next || next.isLeaf) + return true; + next = next.firstChild; + dist--; + } + } + return false; +} +function addMark(tr, from, to, mark) { + let removed = [], added = []; + let removing, adding; + tr.doc.nodesBetween(from, to, (node, pos, parent) => { + if (!node.isInline) + return; + let marks = node.marks; + if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) { + let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to); + let newSet = mark.addToSet(marks); + for (let i = 0; i < marks.length; i++) { + if (!marks[i].isInSet(newSet)) { + if (removing && removing.to == start && removing.mark.eq(marks[i])) + removing.to = end; + else + removed.push(removing = new RemoveMarkStep(start, end, marks[i])); + } + } + if (adding && adding.to == start) + adding.to = end; + else + added.push(adding = new AddMarkStep(start, end, mark)); + } + }); + removed.forEach((s) => tr.step(s)); + added.forEach((s) => tr.step(s)); +} +function removeMark(tr, from, to, mark) { + let matched = [], step = 0; + tr.doc.nodesBetween(from, to, (node, pos) => { + if (!node.isInline) + return; + step++; + let toRemove = null; + if (mark instanceof MarkType) { + let set = node.marks, found2; + while (found2 = mark.isInSet(set)) { + (toRemove || (toRemove = [])).push(found2); + set = found2.removeFromSet(set); + } + } else if (mark) { + if (mark.isInSet(node.marks)) + toRemove = [mark]; + } else { + toRemove = node.marks; + } + if (toRemove && toRemove.length) { + let end = Math.min(pos + node.nodeSize, to); + for (let i = 0; i < toRemove.length; i++) { + let style2 = toRemove[i], found2; + for (let j = 0; j < matched.length; j++) { + let m = matched[j]; + if (m.step == step - 1 && style2.eq(matched[j].style)) + found2 = m; + } + if (found2) { + found2.to = end; + found2.step = step; + } else { + matched.push({ style: style2, from: Math.max(pos, from), to: end, step }); + } + } + } + }); + matched.forEach((m) => tr.step(new RemoveMarkStep(m.from, m.to, m.style))); +} +function clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) { + let node = tr.doc.nodeAt(pos); + let replSteps = [], cur = pos + 1; + for (let i = 0; i < node.childCount; i++) { + let child = node.child(i), end = cur + child.nodeSize; + let allowed = match.matchType(child.type); + if (!allowed) { + replSteps.push(new ReplaceStep(cur, end, Slice.empty)); + } else { + match = allowed; + for (let j = 0; j < child.marks.length; j++) + if (!parentType.allowsMarkType(child.marks[j].type)) + tr.step(new RemoveMarkStep(cur, end, child.marks[j])); + if (clearNewlines && child.isText && parentType.whitespace != "pre") { + let m, newline = /\r?\n|\r/g, slice; + while (m = newline.exec(child.text)) { + if (!slice) + slice = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0); + replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice)); + } + } + } + cur = end; + } + if (!match.validEnd) { + let fill = match.fillBefore(Fragment.empty, true); + tr.replace(cur, cur, new Slice(fill, 0, 0)); + } + for (let i = replSteps.length - 1; i >= 0; i--) + tr.step(replSteps[i]); +} +function canCut(node, start, end) { + return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end)); +} +function liftTarget(range) { + let parent = range.parent; + let content = parent.content.cutByIndex(range.startIndex, range.endIndex); + for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) { + let node = range.$from.node(depth); + let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter; + if (depth < range.depth && node.canReplace(index, endIndex, content)) + return depth; + if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) + break; + if (index) + contentBefore = 1; + if (endIndex < node.childCount) + contentAfter = 1; + } + return null; +} +function lift(tr, range, target) { + let { $from, $to, depth } = range; + let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1); + let start = gapStart, end = gapEnd; + let before = Fragment.empty, openStart = 0; + for (let d = depth, splitting = false; d > target; d--) + if (splitting || $from.index(d) > 0) { + splitting = true; + before = Fragment.from($from.node(d).copy(before)); + openStart++; + } else { + start--; + } + let after = Fragment.empty, openEnd = 0; + for (let d = depth, splitting = false; d > target; d--) + if (splitting || $to.after(d + 1) < $to.end(d)) { + splitting = true; + after = Fragment.from($to.node(d).copy(after)); + openEnd++; + } else { + end++; + } + tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true)); +} +function findWrapping(range, nodeType, attrs = null, innerRange = range) { + let around = findWrappingOutside(range, nodeType); + let inner = around && findWrappingInside(innerRange, nodeType); + if (!inner) + return null; + return around.map(withAttrs).concat({ type: nodeType, attrs }).concat(inner.map(withAttrs)); +} +function withAttrs(type) { + return { type, attrs: null }; +} +function findWrappingOutside(range, type) { + let { parent, startIndex, endIndex } = range; + let around = parent.contentMatchAt(startIndex).findWrapping(type); + if (!around) + return null; + let outer = around.length ? around[0] : type; + return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null; +} +function findWrappingInside(range, type) { + let { parent, startIndex, endIndex } = range; + let inner = parent.child(startIndex); + let inside = type.contentMatch.findWrapping(inner.type); + if (!inside) + return null; + let lastType = inside.length ? inside[inside.length - 1] : type; + let innerMatch = lastType.contentMatch; + for (let i = startIndex; innerMatch && i < endIndex; i++) + innerMatch = innerMatch.matchType(parent.child(i).type); + if (!innerMatch || !innerMatch.validEnd) + return null; + return inside; +} +function wrap(tr, range, wrappers) { + let content = Fragment.empty; + for (let i = wrappers.length - 1; i >= 0; i--) { + if (content.size) { + let match = wrappers[i].type.contentMatch.matchFragment(content); + if (!match || !match.validEnd) + throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper"); + } + content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); + } + let start = range.start, end = range.end; + tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true)); +} +function setBlockType(tr, from, to, type, attrs) { + if (!type.isTextblock) + throw new RangeError("Type given to setBlockType should be a textblock"); + let mapFrom = tr.steps.length; + tr.doc.nodesBetween(from, to, (node, pos) => { + let attrsHere = typeof attrs == "function" ? attrs(node) : attrs; + if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) { + let convertNewlines = null; + if (type.schema.linebreakReplacement) { + let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement); + if (pre && !supportLinebreak) + convertNewlines = false; + else if (!pre && supportLinebreak) + convertNewlines = true; + } + if (convertNewlines === false) + replaceLinebreaks(tr, node, pos, mapFrom); + clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null); + let mapping = tr.mapping.slice(mapFrom); + let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1); + tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true)); + if (convertNewlines === true) + replaceNewlines(tr, node, pos, mapFrom); + return false; + } + }); +} +function replaceNewlines(tr, node, pos, mapFrom) { + node.forEach((child, offset) => { + if (child.isText) { + let m, newline = /\r?\n|\r/g; + while (m = newline.exec(child.text)) { + let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index); + tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create()); + } + } + }); +} +function replaceLinebreaks(tr, node, pos, mapFrom) { + node.forEach((child, offset) => { + if (child.type == child.type.schema.linebreakReplacement) { + let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset); + tr.replaceWith(start, start + 1, node.type.schema.text("\n")); + } + }); +} +function canChangeType(doc3, pos, type) { + let $pos = doc3.resolve(pos), index = $pos.index(); + return $pos.parent.canReplaceWith(index, index + 1, type); +} +function setNodeMarkup(tr, pos, type, attrs, marks) { + let node = tr.doc.nodeAt(pos); + if (!node) + throw new RangeError("No node at given position"); + if (!type) + type = node.type; + let newNode = type.create(attrs, null, marks || node.marks); + if (node.isLeaf) + return tr.replaceWith(pos, pos + node.nodeSize, newNode); + if (!type.validContent(node.content)) + throw new RangeError("Invalid content for node type " + type.name); + tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true)); +} +function canSplit(doc3, pos, depth = 1, typesAfter) { + let $pos = doc3.resolve(pos), base2 = $pos.depth - depth; + let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent; + if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))) + return false; + for (let d = $pos.depth - 1, i = depth - 2; d > base2; d--, i--) { + let node = $pos.node(d), index2 = $pos.index(d); + if (node.type.spec.isolating) + return false; + let rest = node.content.cutByIndex(index2, node.childCount); + let overrideChild = typesAfter && typesAfter[i + 1]; + if (overrideChild) + rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs)); + let after = typesAfter && typesAfter[i] || node; + if (!node.canReplace(index2 + 1, node.childCount) || !after.type.validContent(rest)) + return false; + } + let index = $pos.indexAfter(base2); + let baseType = typesAfter && typesAfter[0]; + return $pos.node(base2).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base2 + 1).type); +} +function split(tr, pos, depth = 1, typesAfter) { + let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; + for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) { + before = Fragment.from($pos.node(d).copy(before)); + let typeAfter = typesAfter && typesAfter[i]; + after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); + } + tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)); +} +function canJoin(doc3, pos) { + let $pos = doc3.resolve(pos), index = $pos.index(); + return joinable2($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1); +} +function canAppendWithSubstitutedLinebreaks(a, b) { + if (!b.content.size) + a.type.compatibleContent(b.type); + let match = a.contentMatchAt(a.childCount); + let { linebreakReplacement } = a.type.schema; + for (let i = 0; i < b.childCount; i++) { + let child = b.child(i); + let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type; + match = match.matchType(type); + if (!match) + return false; + if (!a.type.allowsMarks(child.marks)) + return false; + } + return match.validEnd; +} +function joinable2(a, b) { + return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b)); +} +function joinPoint(doc3, pos, dir = -1) { + let $pos = doc3.resolve(pos); + for (let d = $pos.depth; ; d--) { + let before, after, index = $pos.index(d); + if (d == $pos.depth) { + before = $pos.nodeBefore; + after = $pos.nodeAfter; + } else if (dir > 0) { + before = $pos.node(d + 1); + index++; + after = $pos.node(d).maybeChild(index); + } else { + before = $pos.node(d).maybeChild(index - 1); + after = $pos.node(d + 1); + } + if (before && !before.isTextblock && joinable2(before, after) && $pos.node(d).canReplace(index, index + 1)) + return pos; + if (d == 0) + break; + pos = dir < 0 ? $pos.before(d) : $pos.after(d); + } +} +function join(tr, pos, depth) { + let convertNewlines = null; + let { linebreakReplacement } = tr.doc.type.schema; + let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type; + if (linebreakReplacement && beforeType.inlineContent) { + let pre = beforeType.whitespace == "pre"; + let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement); + if (pre && !supportLinebreak) + convertNewlines = false; + else if (!pre && supportLinebreak) + convertNewlines = true; + } + let mapFrom = tr.steps.length; + if (convertNewlines === false) { + let $after = tr.doc.resolve(pos + depth); + replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom); + } + if (beforeType.inlineContent) + clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null); + let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth); + tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true)); + if (convertNewlines === true) { + let $full = tr.doc.resolve(start); + replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length); + } + return tr; +} +function insertPoint(doc3, pos, nodeType) { + let $pos = doc3.resolve(pos); + if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) + return pos; + if ($pos.parentOffset == 0) + for (let d = $pos.depth - 1; d >= 0; d--) { + let index = $pos.index(d); + if ($pos.node(d).canReplaceWith(index, index, nodeType)) + return $pos.before(d + 1); + if (index > 0) + return null; + } + if ($pos.parentOffset == $pos.parent.content.size) + for (let d = $pos.depth - 1; d >= 0; d--) { + let index = $pos.indexAfter(d); + if ($pos.node(d).canReplaceWith(index, index, nodeType)) + return $pos.after(d + 1); + if (index < $pos.node(d).childCount) + return null; + } + return null; +} +function dropPoint(doc3, pos, slice) { + let $pos = doc3.resolve(pos); + if (!slice.content.size) + return pos; + let content = slice.content; + for (let i = 0; i < slice.openStart; i++) + content = content.firstChild.content; + for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) { + for (let d = $pos.depth; d >= 0; d--) { + let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1; + let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0); + let parent = $pos.node(d), fits = false; + if (pass == 1) { + fits = parent.canReplace(insertPos, insertPos, content); + } else { + let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type); + fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]); + } + if (fits) + return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1); + } + } + return null; +} +function replaceStep(doc3, from, to = from, slice = Slice.empty) { + if (from == to && !slice.size) + return null; + let $from = doc3.resolve(from), $to = doc3.resolve(to); + if (fitsTrivially($from, $to, slice)) + return new ReplaceStep(from, to, slice); + return new Fitter($from, $to, slice).fit(); +} +function fitsTrivially($from, $to, slice) { + return !slice.openStart && !slice.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice.content); +} +var Fitter = class { + constructor($from, $to, unplaced) { + this.$from = $from; + this.$to = $to; + this.unplaced = unplaced; + this.frontier = []; + this.placed = Fragment.empty; + for (let i = 0; i <= $from.depth; i++) { + let node = $from.node(i); + this.frontier.push({ + type: node.type, + match: node.contentMatchAt($from.indexAfter(i)) + }); + } + for (let i = $from.depth; i > 0; i--) + this.placed = Fragment.from($from.node(i).copy(this.placed)); + } + get depth() { + return this.frontier.length - 1; + } + fit() { + while (this.unplaced.size) { + let fit = this.findFittable(); + if (fit) + this.placeNodes(fit); + else + this.openMore() || this.dropNode(); + } + let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth; + let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline)); + if (!$to) + return null; + let content = this.placed, openStart = $from.depth, openEnd = $to.depth; + while (openStart && openEnd && content.childCount == 1) { + content = content.firstChild.content; + openStart--; + openEnd--; + } + let slice = new Slice(content, openStart, openEnd); + if (moveInline > -1) + return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize); + if (slice.size || $from.pos != this.$to.pos) + return new ReplaceStep($from.pos, $to.pos, slice); + return null; + } + // Find a position on the start spine of `this.unplaced` that has + // content that can be moved somewhere on the frontier. Returns two + // depths, one for the slice and one for the frontier. + findFittable() { + let startDepth = this.unplaced.openStart; + for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) { + let node = cur.firstChild; + if (cur.childCount > 1) + openEnd = 0; + if (node.type.spec.isolating && openEnd <= d) { + startDepth = d; + break; + } + cur = node.content; + } + for (let pass = 1; pass <= 2; pass++) { + for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) { + let fragment, parent = null; + if (sliceDepth) { + parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild; + fragment = parent.content; + } else { + fragment = this.unplaced.content; + } + let first2 = fragment.firstChild; + for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) { + let { type, match } = this.frontier[frontierDepth], wrap2, inject = null; + if (pass == 1 && (first2 ? match.matchType(first2.type) || (inject = match.fillBefore(Fragment.from(first2), false)) : parent && type.compatibleContent(parent.type))) + return { sliceDepth, frontierDepth, parent, inject }; + else if (pass == 2 && first2 && (wrap2 = match.findWrapping(first2.type))) + return { sliceDepth, frontierDepth, parent, wrap: wrap2 }; + if (parent && match.matchType(parent.type)) + break; + } + } + } + } + openMore() { + let { content, openStart, openEnd } = this.unplaced; + let inner = contentAt(content, openStart); + if (!inner.childCount || inner.firstChild.isLeaf) + return false; + this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0)); + return true; + } + dropNode() { + let { content, openStart, openEnd } = this.unplaced; + let inner = contentAt(content, openStart); + if (inner.childCount <= 1 && openStart > 0) { + let openAtEnd = content.size - openStart <= openStart + inner.size; + this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd); + } else { + this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd); + } + } + // Move content from the unplaced slice at `sliceDepth` to the + // frontier node at `frontierDepth`. Close that frontier node when + // applicable. + placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap2 }) { + while (this.depth > frontierDepth) + this.closeFrontierNode(); + if (wrap2) + for (let i = 0; i < wrap2.length; i++) + this.openFrontierNode(wrap2[i]); + let slice = this.unplaced, fragment = parent ? parent.content : slice.content; + let openStart = slice.openStart - sliceDepth; + let taken = 0, add = []; + let { match, type } = this.frontier[frontierDepth]; + if (inject) { + for (let i = 0; i < inject.childCount; i++) + add.push(inject.child(i)); + match = match.matchFragment(inject); + } + let openEndCount = fragment.size + sliceDepth - (slice.content.size - slice.openEnd); + while (taken < fragment.childCount) { + let next = fragment.child(taken), matches2 = match.matchType(next.type); + if (!matches2) + break; + taken++; + if (taken > 1 || openStart == 0 || next.content.size) { + match = matches2; + add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1)); + } + } + let toEnd = taken == fragment.childCount; + if (!toEnd) + openEndCount = -1; + this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add)); + this.frontier[frontierDepth].match = match; + if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1) + this.closeFrontierNode(); + for (let i = 0, cur = fragment; i < openEndCount; i++) { + let node = cur.lastChild; + this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) }); + cur = node.content; + } + this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1); + } + mustMoveInline() { + if (!this.$to.parent.isTextblock) + return -1; + let top = this.frontier[this.depth], level; + if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth) + return -1; + let { depth } = this.$to, after = this.$to.after(depth); + while (depth > 1 && after == this.$to.end(--depth)) + ++after; + return after; + } + findCloseLevel($to) { + scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) { + let { match, type } = this.frontier[i]; + let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1)); + let fit = contentAfterFits($to, i, type, match, dropInner); + if (!fit) + continue; + for (let d = i - 1; d >= 0; d--) { + let { match: match2, type: type2 } = this.frontier[d]; + let matches2 = contentAfterFits($to, d, type2, match2, true); + if (!matches2 || matches2.childCount) + continue scan; + } + return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to }; + } + } + close($to) { + let close2 = this.findCloseLevel($to); + if (!close2) + return null; + while (this.depth > close2.depth) + this.closeFrontierNode(); + if (close2.fit.childCount) + this.placed = addToFragment(this.placed, close2.depth, close2.fit); + $to = close2.move; + for (let d = close2.depth + 1; d <= $to.depth; d++) { + let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d)); + this.openFrontierNode(node.type, node.attrs, add); + } + return $to; + } + openFrontierNode(type, attrs = null, content) { + let top = this.frontier[this.depth]; + top.match = top.match.matchType(type); + this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content))); + this.frontier.push({ type, match: type.contentMatch }); + } + closeFrontierNode() { + let open = this.frontier.pop(); + let add = open.match.fillBefore(Fragment.empty, true); + if (add.childCount) + this.placed = addToFragment(this.placed, this.frontier.length, add); + } +}; +function dropFromFragment(fragment, depth, count) { + if (depth == 0) + return fragment.cutByIndex(count, fragment.childCount); + return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count))); +} +function addToFragment(fragment, depth, content) { + if (depth == 0) + return fragment.append(content); + return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))); +} +function contentAt(fragment, depth) { + for (let i = 0; i < depth; i++) + fragment = fragment.firstChild.content; + return fragment; +} +function closeNodeStart(node, openStart, openEnd) { + if (openStart <= 0) + return node; + let frag = node.content; + if (openStart > 1) + frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); + if (openStart > 0) { + frag = node.type.contentMatch.fillBefore(frag).append(frag); + if (openEnd <= 0) + frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); + } + return node.copy(frag); +} +function contentAfterFits($to, depth, type, match, open) { + let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth); + if (index == node.childCount && !type.compatibleContent(node.type)) + return null; + let fit = match.fillBefore(node.content, true, index); + return fit && !invalidMarks(type, node.content, index) ? fit : null; +} +function invalidMarks(type, fragment, start) { + for (let i = start; i < fragment.childCount; i++) + if (!type.allowsMarks(fragment.child(i).marks)) + return true; + return false; +} +function definesContent(type) { + return type.spec.defining || type.spec.definingForContent; +} +function replaceRange(tr, from, to, slice) { + if (!slice.size) + return tr.deleteRange(from, to); + let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to); + if (fitsTrivially($from, $to, slice)) + return tr.step(new ReplaceStep(from, to, slice)); + let targetDepths = coveredDepths($from, $to); + if (targetDepths[targetDepths.length - 1] == 0) + targetDepths.pop(); + let preferredTarget = -($from.depth + 1); + targetDepths.unshift(preferredTarget); + for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) { + let spec = $from.node(d).type.spec; + if (spec.defining || spec.definingAsContext || spec.isolating) + break; + if (targetDepths.indexOf(d) > -1) + preferredTarget = d; + else if ($from.before(d) == pos) + targetDepths.splice(1, 0, -d); + } + let preferredTargetIndex = targetDepths.indexOf(preferredTarget); + let leftNodes = [], preferredDepth = slice.openStart; + for (let content = slice.content, i = 0; ; i++) { + let node = content.firstChild; + leftNodes.push(node); + if (i == slice.openStart) + break; + content = node.content; + } + for (let d = preferredDepth - 1; d >= 0; d--) { + let leftNode = leftNodes[d], def = definesContent(leftNode.type); + if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1))) + preferredDepth = d; + else if (def || !leftNode.type.isTextblock) + break; + } + for (let j = slice.openStart; j >= 0; j--) { + let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1); + let insert = leftNodes[openDepth]; + if (!insert) + continue; + for (let i = 0; i < targetDepths.length; i++) { + let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true; + if (targetDepth < 0) { + expand = false; + targetDepth = -targetDepth; + } + let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1); + if (parent.canReplaceWith(index, index, insert.type, insert.marks)) + return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd)); + } + } + let startSteps = tr.steps.length; + for (let i = targetDepths.length - 1; i >= 0; i--) { + tr.replace(from, to, slice); + if (tr.steps.length > startSteps) + break; + let depth = targetDepths[i]; + if (depth < 0) + continue; + from = $from.before(depth); + to = $to.after(depth); + } +} +function closeFragment(fragment, depth, oldOpen, newOpen, parent) { + if (depth < oldOpen) { + let first2 = fragment.firstChild; + fragment = fragment.replaceChild(0, first2.copy(closeFragment(first2.content, depth + 1, oldOpen, newOpen, first2))); + } + if (depth > newOpen) { + let match = parent.contentMatchAt(0); + let start = match.fillBefore(fragment).append(fragment); + fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true)); + } + return fragment; +} +function replaceRangeWith(tr, from, to, node) { + if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) { + let point = insertPoint(tr.doc, from, node.type); + if (point != null) + from = to = point; + } + tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0)); +} +function deleteRange(tr, from, to) { + let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to); + let covered = coveredDepths($from, $to); + for (let i = 0; i < covered.length; i++) { + let depth = covered[i], last = i == covered.length - 1; + if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd) + return tr.delete($from.start(depth), $to.end(depth)); + if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) + return tr.delete($from.before(depth), $to.after(depth)); + } + for (let d = 1; d <= $from.depth && d <= $to.depth; d++) { + if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1))) + return tr.delete($from.before(d), to); + } + tr.delete(from, to); +} +function coveredDepths($from, $to) { + let result = [], minDepth = Math.min($from.depth, $to.depth); + for (let d = minDepth; d >= 0; d--) { + let start = $from.start(d); + if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating) + break; + if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1) + result.push(d); + } + return result; +} +var AttrStep = class _AttrStep extends Step { + /** + Construct an attribute step. + */ + constructor(pos, attr, value) { + super(); + this.pos = pos; + this.attr = attr; + this.value = value; + } + apply(doc3) { + let node = doc3.nodeAt(this.pos); + if (!node) + return StepResult.fail("No node at attribute step's position"); + let attrs = /* @__PURE__ */ Object.create(null); + for (let name in node.attrs) + attrs[name] = node.attrs[name]; + attrs[this.attr] = this.value; + let updated = node.type.create(attrs, null, node.marks); + return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); + } + getMap() { + return StepMap.empty; + } + invert(doc3) { + return new _AttrStep(this.pos, this.attr, doc3.nodeAt(this.pos).attrs[this.attr]); + } + map(mapping) { + let pos = mapping.mapResult(this.pos, 1); + return pos.deletedAfter ? null : new _AttrStep(pos.pos, this.attr, this.value); + } + toJSON() { + return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value }; + } + static fromJSON(schema, json) { + if (typeof json.pos != "number" || typeof json.attr != "string") + throw new RangeError("Invalid input for AttrStep.fromJSON"); + return new _AttrStep(json.pos, json.attr, json.value); + } +}; +Step.jsonID("attr", AttrStep); +var DocAttrStep = class _DocAttrStep extends Step { + /** + Construct an attribute step. + */ + constructor(attr, value) { + super(); + this.attr = attr; + this.value = value; + } + apply(doc3) { + let attrs = /* @__PURE__ */ Object.create(null); + for (let name in doc3.attrs) + attrs[name] = doc3.attrs[name]; + attrs[this.attr] = this.value; + let updated = doc3.type.create(attrs, doc3.content, doc3.marks); + return StepResult.ok(updated); + } + getMap() { + return StepMap.empty; + } + invert(doc3) { + return new _DocAttrStep(this.attr, doc3.attrs[this.attr]); + } + map(mapping) { + return this; + } + toJSON() { + return { stepType: "docAttr", attr: this.attr, value: this.value }; + } + static fromJSON(schema, json) { + if (typeof json.attr != "string") + throw new RangeError("Invalid input for DocAttrStep.fromJSON"); + return new _DocAttrStep(json.attr, json.value); + } +}; +Step.jsonID("docAttr", DocAttrStep); +var TransformError = class extends Error { +}; +TransformError = function TransformError2(message) { + let err = Error.call(this, message); + err.__proto__ = TransformError2.prototype; + return err; +}; +TransformError.prototype = Object.create(Error.prototype); +TransformError.prototype.constructor = TransformError; +TransformError.prototype.name = "TransformError"; +var Transform = class { + /** + Create a transform that starts with the given document. + */ + constructor(doc3) { + this.doc = doc3; + this.steps = []; + this.docs = []; + this.mapping = new Mapping(); + } + /** + The starting document. + */ + get before() { + return this.docs.length ? this.docs[0] : this.doc; + } + /** + Apply a new step in this transform, saving the result. Throws an + error when the step fails. + */ + step(step) { + let result = this.maybeStep(step); + if (result.failed) + throw new TransformError(result.failed); + return this; + } + /** + Try to apply a step in this transformation, ignoring it if it + fails. Returns the step result. + */ + maybeStep(step) { + let result = step.apply(this.doc); + if (!result.failed) + this.addStep(step, result.doc); + return result; + } + /** + True when the document has been changed (when there are any + steps). + */ + get docChanged() { + return this.steps.length > 0; + } + /** + Return a single range, in post-transform document positions, + that covers all content changed by this transform. Returns null + if no replacements are made. Note that this will ignore changes + that add/remove marks without replacing the underlying content. + */ + changedRange() { + let from = 1e9, to = -1e9; + for (let i = 0; i < this.mapping.maps.length; i++) { + let map = this.mapping.maps[i]; + if (i) { + from = map.map(from, 1); + to = map.map(to, -1); + } + map.forEach((_f, _t, fromB, toB) => { + from = Math.min(from, fromB); + to = Math.max(to, toB); + }); + } + return from == 1e9 ? null : { from, to }; + } + /** + @internal + */ + addStep(step, doc3) { + this.docs.push(this.doc); + this.steps.push(step); + this.mapping.appendMap(step.getMap()); + this.doc = doc3; + } + /** + Replace the part of the document between `from` and `to` with the + given `slice`. + */ + replace(from, to = from, slice = Slice.empty) { + let step = replaceStep(this.doc, from, to, slice); + if (step) + this.step(step); + return this; + } + /** + Replace the given range with the given content, which may be a + fragment, node, or array of nodes. + */ + replaceWith(from, to, content) { + return this.replace(from, to, new Slice(Fragment.from(content), 0, 0)); + } + /** + Delete the content between the given positions. + */ + delete(from, to) { + return this.replace(from, to, Slice.empty); + } + /** + Insert the given content at the given position. + */ + insert(pos, content) { + return this.replaceWith(pos, pos, content); + } + /** + Replace a range of the document with a given slice, using + `from`, `to`, and the slice's + [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather + than fixed start and end points. This method may grow the + replaced area or close open nodes in the slice in order to get a + fit that is more in line with WYSIWYG expectations, by dropping + fully covered parent nodes of the replaced region when they are + marked [non-defining as + context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an + open parent node from the slice that _is_ marked as [defining + its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent). + + This is the method, for example, to handle paste. The similar + [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more + primitive tool which will _not_ move the start and end of its given + range, and is useful in situations where you need more precise + control over what happens. + */ + replaceRange(from, to, slice) { + replaceRange(this, from, to, slice); + return this; + } + /** + Replace the given range with a node, but use `from` and `to` as + hints, rather than precise positions. When from and to are the same + and are at the start or end of a parent node in which the given + node doesn't fit, this method may _move_ them out towards a parent + that does allow the given node to be placed. When the given range + completely covers a parent node, this method may completely replace + that parent node. + */ + replaceRangeWith(from, to, node) { + replaceRangeWith(this, from, to, node); + return this; + } + /** + Delete the given range, expanding it to cover fully covered + parent nodes until a valid replace is found. + */ + deleteRange(from, to) { + deleteRange(this, from, to); + return this; + } + /** + Split the content in the given range off from its parent, if there + is sibling content before or after it, and move it up the tree to + the depth specified by `target`. You'll probably want to use + [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make + sure the lift is valid. + */ + lift(range, target) { + lift(this, range, target); + return this; + } + /** + Join the blocks around the given position. If depth is 2, their + last and first siblings are also joined, and so on. + */ + join(pos, depth = 1) { + join(this, pos, depth); + return this; + } + /** + Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers. + The wrappers are assumed to be valid in this position, and should + probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping). + */ + wrap(range, wrappers) { + wrap(this, range, wrappers); + return this; + } + /** + Set the type of all textblocks (partly) between `from` and `to` to + the given node type with the given attributes. + */ + setBlockType(from, to = from, type, attrs = null) { + setBlockType(this, from, to, type, attrs); + return this; + } + /** + Change the type, attributes, and/or marks of the node at `pos`. + When `type` isn't given, the existing node type is preserved, + */ + setNodeMarkup(pos, type, attrs = null, marks) { + setNodeMarkup(this, pos, type, attrs, marks); + return this; + } + /** + Set a single attribute on a given node to a new value. + The `pos` addresses the document content. Use `setDocAttribute` + to set attributes on the document itself. + */ + setNodeAttribute(pos, attr, value) { + this.step(new AttrStep(pos, attr, value)); + return this; + } + /** + Set a single attribute on the document to a new value. + */ + setDocAttribute(attr, value) { + this.step(new DocAttrStep(attr, value)); + return this; + } + /** + Add a mark to the node at position `pos`. + */ + addNodeMark(pos, mark) { + this.step(new AddNodeMarkStep(pos, mark)); + return this; + } + /** + Remove a mark (or all marks of the given type) from the node at + position `pos`. + */ + removeNodeMark(pos, mark) { + let node = this.doc.nodeAt(pos); + if (!node) + throw new RangeError("No node at position " + pos); + if (mark instanceof Mark) { + if (mark.isInSet(node.marks)) + this.step(new RemoveNodeMarkStep(pos, mark)); + } else { + let set = node.marks, found2, steps = []; + while (found2 = mark.isInSet(set)) { + steps.push(new RemoveNodeMarkStep(pos, found2)); + set = found2.removeFromSet(set); + } + for (let i = steps.length - 1; i >= 0; i--) + this.step(steps[i]); + } + return this; + } + /** + Split the node at the given position, and optionally, if `depth` is + greater than one, any number of nodes above that. By default, the + parts split off will inherit the node type of the original node. + This can be changed by passing an array of types and attributes to + use after the split (with the outermost nodes coming first). + */ + split(pos, depth = 1, typesAfter) { + split(this, pos, depth, typesAfter); + return this; + } + /** + Add the given mark to the inline content between `from` and `to`. + */ + addMark(from, to, mark) { + addMark(this, from, to, mark); + return this; + } + /** + Remove marks from inline nodes between `from` and `to`. When + `mark` is a single mark, remove precisely that mark. When it is + a mark type, remove all marks of that type. When it is null, + remove all marks of any type. + */ + removeMark(from, to, mark) { + removeMark(this, from, to, mark); + return this; + } + /** + Removes all marks and nodes from the content of the node at + `pos` that don't match the given new parent node type. Accepts + an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as + third argument. + */ + clearIncompatible(pos, parentType, match) { + clearIncompatible(this, pos, parentType, match); + return this; + } +}; + +// node_modules/prosemirror-state/dist/index.js +var classesById = /* @__PURE__ */ Object.create(null); +var Selection = class { + /** + Initialize a selection with the head and anchor and ranges. If no + ranges are given, constructs a single range across `$anchor` and + `$head`. + */ + constructor($anchor, $head, ranges) { + this.$anchor = $anchor; + this.$head = $head; + this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; + } + /** + The selection's anchor, as an unresolved position. + */ + get anchor() { + return this.$anchor.pos; + } + /** + The selection's head. + */ + get head() { + return this.$head.pos; + } + /** + The lower bound of the selection's main range. + */ + get from() { + return this.$from.pos; + } + /** + The upper bound of the selection's main range. + */ + get to() { + return this.$to.pos; + } + /** + The resolved lower bound of the selection's main range. + */ + get $from() { + return this.ranges[0].$from; + } + /** + The resolved upper bound of the selection's main range. + */ + get $to() { + return this.ranges[0].$to; + } + /** + Indicates whether the selection contains any content. + */ + get empty() { + let ranges = this.ranges; + for (let i = 0; i < ranges.length; i++) + if (ranges[i].$from.pos != ranges[i].$to.pos) + return false; + return true; + } + /** + Get the content of this selection as a slice. + */ + content() { + return this.$from.doc.slice(this.from, this.to, true); + } + /** + Replace the selection with a slice or, if no slice is given, + delete the selection. Will append to the given transaction. + */ + replace(tr, content = Slice.empty) { + let lastNode = content.content.lastChild, lastParent = null; + for (let i = 0; i < content.openEnd; i++) { + lastParent = lastNode; + lastNode = lastNode.lastChild; + } + let mapFrom = tr.steps.length, ranges = this.ranges; + for (let i = 0; i < ranges.length; i++) { + let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom); + tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content); + if (i == 0) + selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); + } + } + /** + Replace the selection with the given node, appending the changes + to the given transaction. + */ + replaceWith(tr, node) { + let mapFrom = tr.steps.length, ranges = this.ranges; + for (let i = 0; i < ranges.length; i++) { + let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom); + let from = mapping.map($from.pos), to = mapping.map($to.pos); + if (i) { + tr.deleteRange(from, to); + } else { + tr.replaceRangeWith(from, to, node); + selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1); + } + } + } + /** + Find a valid cursor or leaf node selection starting at the given + position and searching back if `dir` is negative, and forward if + positive. When `textOnly` is true, only consider cursor + selections. Will return null when no valid selection position is + found. + */ + static findFrom($pos, dir, textOnly = false) { + let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly); + if (inner) + return inner; + for (let depth = $pos.depth - 1; depth >= 0; depth--) { + let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly); + if (found2) + return found2; + } + return null; + } + /** + Find a valid cursor or leaf node selection near the given + position. Searches forward first by default, but if `bias` is + negative, it will search backwards first. + */ + static near($pos, bias = 1) { + return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0)); + } + /** + Find the cursor or leaf node selection closest to the start of + the given document. Will return an + [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position + exists. + */ + static atStart(doc3) { + return findSelectionIn(doc3, doc3, 0, 0, 1) || new AllSelection(doc3); + } + /** + Find the cursor or leaf node selection closest to the end of the + given document. + */ + static atEnd(doc3) { + return findSelectionIn(doc3, doc3, doc3.content.size, doc3.childCount, -1) || new AllSelection(doc3); + } + /** + Deserialize the JSON representation of a selection. Must be + implemented for custom classes (as a static class method). + */ + static fromJSON(doc3, json) { + if (!json || !json.type) + throw new RangeError("Invalid input for Selection.fromJSON"); + let cls = classesById[json.type]; + if (!cls) + throw new RangeError(`No selection type ${json.type} defined`); + return cls.fromJSON(doc3, json); + } + /** + To be able to deserialize selections from JSON, custom selection + classes must register themselves with an ID string, so that they + can be disambiguated. Try to pick something that's unlikely to + clash with classes from other modules. + */ + static jsonID(id, selectionClass) { + if (id in classesById) + throw new RangeError("Duplicate use of selection JSON ID " + id); + classesById[id] = selectionClass; + selectionClass.prototype.jsonID = id; + return selectionClass; + } + /** + Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection, + which is a value that can be mapped without having access to a + current document, and later resolved to a real selection for a + given document again. (This is used mostly by the history to + track and restore old selections.) The default implementation of + this method just converts the selection to a text selection and + returns the bookmark for that. + */ + getBookmark() { + return TextSelection.between(this.$anchor, this.$head).getBookmark(); + } +}; +Selection.prototype.visible = true; +var SelectionRange = class { + /** + Create a range. + */ + constructor($from, $to) { + this.$from = $from; + this.$to = $to; + } +}; +var warnedAboutTextSelection = false; +function checkTextSelection($pos) { + if (!warnedAboutTextSelection && !$pos.parent.inlineContent) { + warnedAboutTextSelection = true; + console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")"); + } +} +var TextSelection = class _TextSelection extends Selection { + /** + Construct a text selection between the given points. + */ + constructor($anchor, $head = $anchor) { + checkTextSelection($anchor); + checkTextSelection($head); + super($anchor, $head); + } + /** + Returns a resolved position if this is a cursor selection (an + empty text selection), and null otherwise. + */ + get $cursor() { + return this.$anchor.pos == this.$head.pos ? this.$head : null; + } + map(doc3, mapping) { + let $head = doc3.resolve(mapping.map(this.head)); + if (!$head.parent.inlineContent) + return Selection.near($head); + let $anchor = doc3.resolve(mapping.map(this.anchor)); + return new _TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head); + } + replace(tr, content = Slice.empty) { + super.replace(tr, content); + if (content == Slice.empty) { + let marks = this.$from.marksAcross(this.$to); + if (marks) + tr.ensureMarks(marks); + } + } + eq(other) { + return other instanceof _TextSelection && other.anchor == this.anchor && other.head == this.head; + } + getBookmark() { + return new TextBookmark(this.anchor, this.head); + } + toJSON() { + return { type: "text", anchor: this.anchor, head: this.head }; + } + /** + @internal + */ + static fromJSON(doc3, json) { + if (typeof json.anchor != "number" || typeof json.head != "number") + throw new RangeError("Invalid input for TextSelection.fromJSON"); + return new _TextSelection(doc3.resolve(json.anchor), doc3.resolve(json.head)); + } + /** + Create a text selection from non-resolved positions. + */ + static create(doc3, anchor, head = anchor) { + let $anchor = doc3.resolve(anchor); + return new this($anchor, head == anchor ? $anchor : doc3.resolve(head)); + } + /** + Return a text selection that spans the given positions or, if + they aren't text positions, find a text selection near them. + `bias` determines whether the method searches forward (default) + or backwards (negative number) first. Will fall back to calling + [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document + doesn't contain a valid text position. + */ + static between($anchor, $head, bias) { + let dPos = $anchor.pos - $head.pos; + if (!bias || dPos) + bias = dPos >= 0 ? 1 : -1; + if (!$head.parent.inlineContent) { + let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true); + if (found2) + $head = found2.$head; + else + return Selection.near($head, bias); + } + if (!$anchor.parent.inlineContent) { + if (dPos == 0) { + $anchor = $head; + } else { + $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor; + if ($anchor.pos < $head.pos != dPos < 0) + $anchor = $head; + } + } + return new _TextSelection($anchor, $head); + } +}; +Selection.jsonID("text", TextSelection); +var TextBookmark = class _TextBookmark { + constructor(anchor, head) { + this.anchor = anchor; + this.head = head; + } + map(mapping) { + return new _TextBookmark(mapping.map(this.anchor), mapping.map(this.head)); + } + resolve(doc3) { + return TextSelection.between(doc3.resolve(this.anchor), doc3.resolve(this.head)); + } +}; +var NodeSelection = class _NodeSelection extends Selection { + /** + Create a node selection. Does not verify the validity of its + argument. + */ + constructor($pos) { + let node = $pos.nodeAfter; + let $end = $pos.node(0).resolve($pos.pos + node.nodeSize); + super($pos, $end); + this.node = node; + } + map(doc3, mapping) { + let { deleted, pos } = mapping.mapResult(this.anchor); + let $pos = doc3.resolve(pos); + if (deleted) + return Selection.near($pos); + return new _NodeSelection($pos); + } + content() { + return new Slice(Fragment.from(this.node), 0, 0); + } + eq(other) { + return other instanceof _NodeSelection && other.anchor == this.anchor; + } + toJSON() { + return { type: "node", anchor: this.anchor }; + } + getBookmark() { + return new NodeBookmark(this.anchor); + } + /** + @internal + */ + static fromJSON(doc3, json) { + if (typeof json.anchor != "number") + throw new RangeError("Invalid input for NodeSelection.fromJSON"); + return new _NodeSelection(doc3.resolve(json.anchor)); + } + /** + Create a node selection from non-resolved positions. + */ + static create(doc3, from) { + return new _NodeSelection(doc3.resolve(from)); + } + /** + Determines whether the given node may be selected as a node + selection. + */ + static isSelectable(node) { + return !node.isText && node.type.spec.selectable !== false; + } +}; +NodeSelection.prototype.visible = false; +Selection.jsonID("node", NodeSelection); +var NodeBookmark = class _NodeBookmark { + constructor(anchor) { + this.anchor = anchor; + } + map(mapping) { + let { deleted, pos } = mapping.mapResult(this.anchor); + return deleted ? new TextBookmark(pos, pos) : new _NodeBookmark(pos); + } + resolve(doc3) { + let $pos = doc3.resolve(this.anchor), node = $pos.nodeAfter; + if (node && NodeSelection.isSelectable(node)) + return new NodeSelection($pos); + return Selection.near($pos); + } +}; +var AllSelection = class _AllSelection extends Selection { + /** + Create an all-selection over the given document. + */ + constructor(doc3) { + super(doc3.resolve(0), doc3.resolve(doc3.content.size)); + } + replace(tr, content = Slice.empty) { + if (content == Slice.empty) { + tr.delete(0, tr.doc.content.size); + let sel = Selection.atStart(tr.doc); + if (!sel.eq(tr.selection)) + tr.setSelection(sel); + } else { + super.replace(tr, content); + } + } + toJSON() { + return { type: "all" }; + } + /** + @internal + */ + static fromJSON(doc3) { + return new _AllSelection(doc3); + } + map(doc3) { + return new _AllSelection(doc3); + } + eq(other) { + return other instanceof _AllSelection; + } + getBookmark() { + return AllBookmark; + } +}; +Selection.jsonID("all", AllSelection); +var AllBookmark = { + map() { + return this; + }, + resolve(doc3) { + return new AllSelection(doc3); + } +}; +function findSelectionIn(doc3, node, pos, index, dir, text = false) { + if (node.inlineContent) + return TextSelection.create(doc3, pos); + for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) { + let child = node.child(i); + if (!child.isAtom) { + let inner = findSelectionIn(doc3, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text); + if (inner) + return inner; + } else if (!text && NodeSelection.isSelectable(child)) { + return NodeSelection.create(doc3, pos - (dir < 0 ? child.nodeSize : 0)); + } + pos += child.nodeSize * dir; + } + return null; +} +function selectionToInsertionEnd(tr, startLen, bias) { + let last = tr.steps.length - 1; + if (last < startLen) + return; + let step = tr.steps[last]; + if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) + return; + let map = tr.mapping.maps[last], end; + map.forEach((_from, _to, _newFrom, newTo) => { + if (end == null) + end = newTo; + }); + tr.setSelection(Selection.near(tr.doc.resolve(end), bias)); +} +var UPDATED_SEL = 1; +var UPDATED_MARKS = 2; +var UPDATED_SCROLL = 4; +var Transaction = class extends Transform { + /** + @internal + */ + constructor(state) { + super(state.doc); + this.curSelectionFor = 0; + this.updated = 0; + this.meta = /* @__PURE__ */ Object.create(null); + this.time = Date.now(); + this.curSelection = state.selection; + this.storedMarks = state.storedMarks; + } + /** + The transaction's current selection. This defaults to the editor + selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the + transaction, but can be overwritten with + [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection). + */ + get selection() { + if (this.curSelectionFor < this.steps.length) { + this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)); + this.curSelectionFor = this.steps.length; + } + return this.curSelection; + } + /** + Update the transaction's current selection. Will determine the + selection that the editor gets when the transaction is applied. + */ + setSelection(selection) { + if (selection.$from.doc != this.doc) + throw new RangeError("Selection passed to setSelection must point at the current document"); + this.curSelection = selection; + this.curSelectionFor = this.steps.length; + this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS; + this.storedMarks = null; + return this; + } + /** + Whether the selection was explicitly updated by this transaction. + */ + get selectionSet() { + return (this.updated & UPDATED_SEL) > 0; + } + /** + Set the current stored marks. + */ + setStoredMarks(marks) { + this.storedMarks = marks; + this.updated |= UPDATED_MARKS; + return this; + } + /** + Make sure the current stored marks or, if that is null, the marks + at the selection, match the given set of marks. Does nothing if + this is already the case. + */ + ensureMarks(marks) { + if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) + this.setStoredMarks(marks); + return this; + } + /** + Add a mark to the set of stored marks. + */ + addStoredMark(mark) { + return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks())); + } + /** + Remove a mark or mark type from the set of stored marks. + */ + removeStoredMark(mark) { + return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks())); + } + /** + Whether the stored marks were explicitly set for this transaction. + */ + get storedMarksSet() { + return (this.updated & UPDATED_MARKS) > 0; + } + /** + @internal + */ + addStep(step, doc3) { + super.addStep(step, doc3); + this.updated = this.updated & ~UPDATED_MARKS; + this.storedMarks = null; + } + /** + Update the timestamp for the transaction. + */ + setTime(time) { + this.time = time; + return this; + } + /** + Replace the current selection with the given slice. + */ + replaceSelection(slice) { + this.selection.replace(this, slice); + return this; + } + /** + Replace the selection with the given node. When `inheritMarks` is + true and the content is inline, it inherits the marks from the + place where it is inserted. + */ + replaceSelectionWith(node, inheritMarks = true) { + let selection = this.selection; + if (inheritMarks) + node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none)); + selection.replaceWith(this, node); + return this; + } + /** + Delete the selection. + */ + deleteSelection() { + this.selection.replace(this); + return this; + } + /** + Replace the given range, or the selection if no range is given, + with a text node containing the given string. + */ + insertText(text, from, to) { + let schema = this.doc.type.schema; + if (from == null) { + if (!text) + return this.deleteSelection(); + return this.replaceSelectionWith(schema.text(text), true); + } else { + if (to == null) + to = from; + if (!text) + return this.deleteRange(from, to); + let marks = this.storedMarks; + if (!marks) { + let $from = this.doc.resolve(from); + marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to)); + } + this.replaceRangeWith(from, to, schema.text(text, marks)); + if (!this.selection.empty && this.selection.to == from + text.length) + this.setSelection(Selection.near(this.selection.$to)); + return this; + } + } + /** + Store a metadata property in this transaction, keyed either by + name or by plugin. + */ + setMeta(key, value) { + this.meta[typeof key == "string" ? key : key.key] = value; + return this; + } + /** + Retrieve a metadata property for a given name or plugin. + */ + getMeta(key) { + return this.meta[typeof key == "string" ? key : key.key]; + } + /** + Returns true if this transaction doesn't contain any metadata, + and can thus safely be extended. + */ + get isGeneric() { + for (let _ in this.meta) + return false; + return true; + } + /** + Indicate that the editor should scroll the selection into view + when updated to the state produced by this transaction. + */ + scrollIntoView() { + this.updated |= UPDATED_SCROLL; + return this; + } + /** + True when this transaction has had `scrollIntoView` called on it. + */ + get scrolledIntoView() { + return (this.updated & UPDATED_SCROLL) > 0; + } +}; +function bind(f, self) { + return !self || !f ? f : f.bind(self); +} +var FieldDesc = class { + constructor(name, desc, self) { + this.name = name; + this.init = bind(desc.init, self); + this.apply = bind(desc.apply, self); + } +}; +var baseFields = [ + new FieldDesc("doc", { + init(config) { + return config.doc || config.schema.topNodeType.createAndFill(); + }, + apply(tr) { + return tr.doc; + } + }), + new FieldDesc("selection", { + init(config, instance) { + return config.selection || Selection.atStart(instance.doc); + }, + apply(tr) { + return tr.selection; + } + }), + new FieldDesc("storedMarks", { + init(config) { + return config.storedMarks || null; + }, + apply(tr, _marks, _old, state) { + return state.selection.$cursor ? tr.storedMarks : null; + } + }), + new FieldDesc("scrollToSelection", { + init() { + return 0; + }, + apply(tr, prev) { + return tr.scrolledIntoView ? prev + 1 : prev; + } + }) +]; +var Configuration = class { + constructor(schema, plugins) { + this.schema = schema; + this.plugins = []; + this.pluginsByKey = /* @__PURE__ */ Object.create(null); + this.fields = baseFields.slice(); + if (plugins) + plugins.forEach((plugin) => { + if (this.pluginsByKey[plugin.key]) + throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")"); + this.plugins.push(plugin); + this.pluginsByKey[plugin.key] = plugin; + if (plugin.spec.state) + this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); + }); + } +}; +var EditorState = class _EditorState { + /** + @internal + */ + constructor(config) { + this.config = config; + } + /** + The schema of the state's document. + */ + get schema() { + return this.config.schema; + } + /** + The plugins that are active in this state. + */ + get plugins() { + return this.config.plugins; + } + /** + Apply the given transaction to produce a new state. + */ + apply(tr) { + return this.applyTransaction(tr).state; + } + /** + @internal + */ + filterTransaction(tr, ignore = -1) { + for (let i = 0; i < this.config.plugins.length; i++) + if (i != ignore) { + let plugin = this.config.plugins[i]; + if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this)) + return false; + } + return true; + } + /** + Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that + returns the precise transactions that were applied (which might + be influenced by the [transaction + hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of + plugins) along with the new state. + */ + applyTransaction(rootTr) { + if (!this.filterTransaction(rootTr)) + return { state: this, transactions: [] }; + let trs = [rootTr], newState = this.applyInner(rootTr), seen = null; + for (; ; ) { + let haveNew = false; + for (let i = 0; i < this.config.plugins.length; i++) { + let plugin = this.config.plugins[i]; + if (plugin.spec.appendTransaction) { + let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this; + let tr = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState); + if (tr && newState.filterTransaction(tr, i)) { + tr.setMeta("appendedTransaction", rootTr); + if (!seen) { + seen = []; + for (let j = 0; j < this.config.plugins.length; j++) + seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 }); + } + trs.push(tr); + newState = newState.applyInner(tr); + haveNew = true; + } + if (seen) + seen[i] = { state: newState, n: trs.length }; + } + } + if (!haveNew) + return { state: newState, transactions: trs }; + } + } + /** + @internal + */ + applyInner(tr) { + if (!tr.before.eq(this.doc)) + throw new RangeError("Applying a mismatched transaction"); + let newInstance = new _EditorState(this.config), fields = this.config.fields; + for (let i = 0; i < fields.length; i++) { + let field = fields[i]; + newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance); + } + return newInstance; + } + /** + Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state. + */ + get tr() { + return new Transaction(this); + } + /** + Create a new state. + */ + static create(config) { + let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins); + let instance = new _EditorState($config); + for (let i = 0; i < $config.fields.length; i++) + instance[$config.fields[i].name] = $config.fields[i].init(config, instance); + return instance; + } + /** + Create a new state based on this one, but with an adjusted set + of active plugins. State fields that exist in both sets of + plugins are kept unchanged. Those that no longer exist are + dropped, and those that are new are initialized using their + [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new + configuration object.. + */ + reconfigure(config) { + let $config = new Configuration(this.schema, config.plugins); + let fields = $config.fields, instance = new _EditorState($config); + for (let i = 0; i < fields.length; i++) { + let name = fields[i].name; + instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance); + } + return instance; + } + /** + Serialize this state to JSON. If you want to serialize the state + of plugins, pass an object mapping property names to use in the + resulting JSON object to plugin objects. The argument may also be + a string or number, in which case it is ignored, to support the + way `JSON.stringify` calls `toString` methods. + */ + toJSON(pluginFields) { + let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() }; + if (this.storedMarks) + result.storedMarks = this.storedMarks.map((m) => m.toJSON()); + if (pluginFields && typeof pluginFields == "object") + for (let prop in pluginFields) { + if (prop == "doc" || prop == "selection") + throw new RangeError("The JSON fields `doc` and `selection` are reserved"); + let plugin = pluginFields[prop], state = plugin.spec.state; + if (state && state.toJSON) + result[prop] = state.toJSON.call(plugin, this[plugin.key]); + } + return result; + } + /** + Deserialize a JSON representation of a state. `config` should + have at least a `schema` field, and should contain array of + plugins to initialize the state with. `pluginFields` can be used + to deserialize the state of plugins, by associating plugin + instances with the property names they use in the JSON object. + */ + static fromJSON(config, json, pluginFields) { + if (!json) + throw new RangeError("Invalid input for EditorState.fromJSON"); + if (!config.schema) + throw new RangeError("Required config field 'schema' missing"); + let $config = new Configuration(config.schema, config.plugins); + let instance = new _EditorState($config); + $config.fields.forEach((field) => { + if (field.name == "doc") { + instance.doc = Node.fromJSON(config.schema, json.doc); + } else if (field.name == "selection") { + instance.selection = Selection.fromJSON(instance.doc, json.selection); + } else if (field.name == "storedMarks") { + if (json.storedMarks) + instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); + } else { + if (pluginFields) + for (let prop in pluginFields) { + let plugin = pluginFields[prop], state = plugin.spec.state; + if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) { + instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance); + return; + } + } + instance[field.name] = field.init(config, instance); + } + }); + return instance; + } +}; +function bindProps(obj, self, target) { + for (let prop in obj) { + let val = obj[prop]; + if (val instanceof Function) + val = val.bind(self); + else if (prop == "handleDOMEvents") + val = bindProps(val, self, {}); + target[prop] = val; + } + return target; +} +var Plugin = class { + /** + Create a plugin. + */ + constructor(spec) { + this.spec = spec; + this.props = {}; + if (spec.props) + bindProps(spec.props, this, this.props); + this.key = spec.key ? spec.key.key : createKey("plugin"); + } + /** + Extract the plugin's state field from an editor state. + */ + getState(state) { + return state[this.key]; + } +}; +var keys = /* @__PURE__ */ Object.create(null); +function createKey(name) { + if (name in keys) + return name + "$" + ++keys[name]; + keys[name] = 0; + return name + "$"; +} +var PluginKey = class { + /** + Create a plugin key. + */ + constructor(name = "key") { + this.key = createKey(name); + } + /** + Get the active plugin with this key, if any, from an editor + state. + */ + get(state) { + return state.config.pluginsByKey[this.key]; + } + /** + Get the plugin's state from an editor state. + */ + getState(state) { + return state[this.key]; + } +}; + +// node_modules/prosemirror-commands/dist/index.js +var deleteSelection = (state, dispatch) => { + if (state.selection.empty) + return false; + if (dispatch) + dispatch(state.tr.deleteSelection().scrollIntoView()); + return true; +}; +function atBlockStart(state, view) { + let { $cursor } = state.selection; + if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0)) + return null; + return $cursor; +} +var joinBackward = (state, dispatch, view) => { + let $cursor = atBlockStart(state, view); + if (!$cursor) + return false; + let $cut = findCutBefore($cursor); + if (!$cut) { + let range = $cursor.blockRange(), target = range && liftTarget(range); + if (target == null) + return false; + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; + } + let before = $cut.nodeBefore; + if (deleteBarrier(state, $cut, dispatch, -1)) + return true; + if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) { + for (let depth = $cursor.depth; ; depth--) { + let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty); + if (delStep && delStep.slice.size < delStep.to - delStep.from) { + if (dispatch) { + let tr = state.tr.step(delStep); + tr.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize)); + dispatch(tr.scrollIntoView()); + } + return true; + } + if (depth == 1 || $cursor.node(depth - 1).childCount > 1) + break; + } + } + if (before.isAtom && $cut.depth == $cursor.depth - 1) { + if (dispatch) + dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView()); + return true; + } + return false; +}; +var joinTextblockBackward = (state, dispatch, view) => { + let $cursor = atBlockStart(state, view); + if (!$cursor) + return false; + let $cut = findCutBefore($cursor); + return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; +}; +var joinTextblockForward = (state, dispatch, view) => { + let $cursor = atBlockEnd(state, view); + if (!$cursor) + return false; + let $cut = findCutAfter($cursor); + return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; +}; +function joinTextblocksAround(state, $cut, dispatch) { + let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1; + for (; !beforeText.isTextblock; beforePos--) { + if (beforeText.type.spec.isolating) + return false; + let child = beforeText.lastChild; + if (!child) + return false; + beforeText = child; + } + let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1; + for (; !afterText.isTextblock; afterPos++) { + if (afterText.type.spec.isolating) + return false; + let child = afterText.firstChild; + if (!child) + return false; + afterText = child; + } + let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty); + if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos) + return false; + if (dispatch) { + let tr = state.tr.step(step); + tr.setSelection(TextSelection.create(tr.doc, beforePos)); + dispatch(tr.scrollIntoView()); + } + return true; +} +function textblockAt(node, side, only = false) { + for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) { + if (scan.isTextblock) + return true; + if (only && scan.childCount != 1) + return false; + } + return false; +} +var selectNodeBackward = (state, dispatch, view) => { + let { $head, empty: empty2 } = state.selection, $cut = $head; + if (!empty2) + return false; + if ($head.parent.isTextblock) { + if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) + return false; + $cut = findCutBefore($head); + } + let node = $cut && $cut.nodeBefore; + if (!node || !NodeSelection.isSelectable(node)) + return false; + if (dispatch) + dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView()); + return true; +}; +function findCutBefore($pos) { + if (!$pos.parent.type.spec.isolating) + for (let i = $pos.depth - 1; i >= 0; i--) { + if ($pos.index(i) > 0) + return $pos.doc.resolve($pos.before(i + 1)); + if ($pos.node(i).type.spec.isolating) + break; + } + return null; +} +function atBlockEnd(state, view) { + let { $cursor } = state.selection; + if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size)) + return null; + return $cursor; +} +var joinForward = (state, dispatch, view) => { + let $cursor = atBlockEnd(state, view); + if (!$cursor) + return false; + let $cut = findCutAfter($cursor); + if (!$cut) + return false; + let after = $cut.nodeAfter; + if (deleteBarrier(state, $cut, dispatch, 1)) + return true; + if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) { + let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty); + if (delStep && delStep.slice.size < delStep.to - delStep.from) { + if (dispatch) { + let tr = state.tr.step(delStep); + tr.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1) : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos))); + dispatch(tr.scrollIntoView()); + } + return true; + } + } + if (after.isAtom && $cut.depth == $cursor.depth - 1) { + if (dispatch) + dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView()); + return true; + } + return false; +}; +var selectNodeForward = (state, dispatch, view) => { + let { $head, empty: empty2 } = state.selection, $cut = $head; + if (!empty2) + return false; + if ($head.parent.isTextblock) { + if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) + return false; + $cut = findCutAfter($head); + } + let node = $cut && $cut.nodeAfter; + if (!node || !NodeSelection.isSelectable(node)) + return false; + if (dispatch) + dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView()); + return true; +}; +function findCutAfter($pos) { + if (!$pos.parent.type.spec.isolating) + for (let i = $pos.depth - 1; i >= 0; i--) { + let parent = $pos.node(i); + if ($pos.index(i) + 1 < parent.childCount) + return $pos.doc.resolve($pos.after(i + 1)); + if (parent.type.spec.isolating) + break; + } + return null; +} +var joinUp = (state, dispatch) => { + let sel = state.selection, nodeSel = sel instanceof NodeSelection, point; + if (nodeSel) { + if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) + return false; + point = sel.from; + } else { + point = joinPoint(state.doc, sel.from, -1); + if (point == null) + return false; + } + if (dispatch) { + let tr = state.tr.join(point); + if (nodeSel) + tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize)); + dispatch(tr.scrollIntoView()); + } + return true; +}; +var joinDown = (state, dispatch) => { + let sel = state.selection, point; + if (sel instanceof NodeSelection) { + if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) + return false; + point = sel.to; + } else { + point = joinPoint(state.doc, sel.to, 1); + if (point == null) + return false; + } + if (dispatch) + dispatch(state.tr.join(point).scrollIntoView()); + return true; +}; +var lift2 = (state, dispatch) => { + let { $from, $to } = state.selection; + let range = $from.blockRange($to), target = range && liftTarget(range); + if (target == null) + return false; + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; +}; +var newlineInCode = (state, dispatch) => { + let { $head, $anchor } = state.selection; + if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) + return false; + if (dispatch) + dispatch(state.tr.insertText("\n").scrollIntoView()); + return true; +}; +function defaultBlockAt(match) { + for (let i = 0; i < match.edgeCount; i++) { + let { type } = match.edge(i); + if (type.isTextblock && !type.hasRequiredAttrs()) + return type; + } + return null; +} +var exitCode = (state, dispatch) => { + let { $head, $anchor } = state.selection; + if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) + return false; + let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after)); + if (!type || !above.canReplaceWith(after, after, type)) + return false; + if (dispatch) { + let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill()); + tr.setSelection(Selection.near(tr.doc.resolve(pos), 1)); + dispatch(tr.scrollIntoView()); + } + return true; +}; +var createParagraphNear = (state, dispatch) => { + let sel = state.selection, { $from, $to } = sel; + if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) + return false; + let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter())); + if (!type || !type.isTextblock) + return false; + if (dispatch) { + let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos; + let tr = state.tr.insert(side, type.createAndFill()); + tr.setSelection(TextSelection.create(tr.doc, side + 1)); + dispatch(tr.scrollIntoView()); + } + return true; +}; +var liftEmptyBlock = (state, dispatch) => { + let { $cursor } = state.selection; + if (!$cursor || $cursor.parent.content.size) + return false; + if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) { + let before = $cursor.before(); + if (canSplit(state.doc, before)) { + if (dispatch) + dispatch(state.tr.split(before).scrollIntoView()); + return true; + } + } + let range = $cursor.blockRange(), target = range && liftTarget(range); + if (target == null) + return false; + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; +}; +function splitBlockAs(splitNode) { + return (state, dispatch) => { + let { $from, $to } = state.selection; + if (state.selection instanceof NodeSelection && state.selection.node.isBlock) { + if (!$from.parentOffset || !canSplit(state.doc, $from.pos)) + return false; + if (dispatch) + dispatch(state.tr.split($from.pos).scrollIntoView()); + return true; + } + if (!$from.depth) + return false; + let types = []; + let splitDepth, deflt, atEnd = false, atStart = false; + for (let d = $from.depth; ; d--) { + let node = $from.node(d); + if (node.isBlock) { + atEnd = $from.end(d) == $from.pos + ($from.depth - d); + atStart = $from.start(d) == $from.pos - ($from.depth - d); + deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1))); + let splitType = splitNode && splitNode($to.parent, atEnd, $from); + types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null)); + splitDepth = d; + break; + } else { + if (d == 1) + return false; + types.unshift(null); + } + } + let tr = state.tr; + if (state.selection instanceof TextSelection || state.selection instanceof AllSelection) + tr.deleteSelection(); + let splitPos = tr.mapping.map($from.pos); + let can = canSplit(tr.doc, splitPos, types.length, types); + if (!can) { + types[0] = deflt ? { type: deflt } : null; + can = canSplit(tr.doc, splitPos, types.length, types); + } + if (!can) + return false; + tr.split(splitPos, types.length, types); + if (!atEnd && atStart && $from.node(splitDepth).type != deflt) { + let first2 = tr.mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first2); + if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt)) + tr.setNodeMarkup(tr.mapping.map($from.before(splitDepth)), deflt); + } + if (dispatch) + dispatch(tr.scrollIntoView()); + return true; + }; +} +var splitBlock = splitBlockAs(); +var selectParentNode = (state, dispatch) => { + let { $from, to } = state.selection, pos; + let same = $from.sharedDepth(to); + if (same == 0) + return false; + pos = $from.before(same); + if (dispatch) + dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); + return true; +}; +var selectAll = (state, dispatch) => { + if (dispatch) + dispatch(state.tr.setSelection(new AllSelection(state.doc))); + return true; +}; +function joinMaybeClear(state, $pos, dispatch) { + let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index(); + if (!before || !after || !before.type.compatibleContent(after.type)) + return false; + if (!before.content.size && $pos.parent.canReplace(index - 1, index)) { + if (dispatch) + dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); + return true; + } + if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos))) + return false; + if (dispatch) + dispatch(state.tr.join($pos.pos).scrollIntoView()); + return true; +} +function deleteBarrier(state, $cut, dispatch, dir) { + let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match; + let isolated = before.type.spec.isolating || after.type.spec.isolating; + if (!isolated && joinMaybeClear(state, $cut, dispatch)) + return true; + let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1); + if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) { + if (dispatch) { + let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty; + for (let i = conn.length - 1; i >= 0; i--) + wrap2 = Fragment.from(conn[i].create(null, wrap2)); + wrap2 = Fragment.from(before.copy(wrap2)); + let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true)); + let $joinAt = tr.doc.resolve(end + 2 * conn.length); + if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr.doc, $joinAt.pos)) + tr.join($joinAt.pos); + dispatch(tr.scrollIntoView()); + } + return true; + } + let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1); + let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range); + if (target != null && target >= $cut.depth) { + if (dispatch) + dispatch(state.tr.lift(range, target).scrollIntoView()); + return true; + } + if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) { + let at = before, wrap2 = []; + for (; ; ) { + wrap2.push(at); + if (at.isTextblock) + break; + at = at.lastChild; + } + let afterText = after, afterDepth = 1; + for (; !afterText.isTextblock; afterText = afterText.firstChild) + afterDepth++; + if (at.canReplace(at.childCount, at.childCount, afterText.content)) { + if (dispatch) { + let end = Fragment.empty; + for (let i = wrap2.length - 1; i >= 0; i--) + end = Fragment.from(wrap2[i].copy(end)); + let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true)); + dispatch(tr.scrollIntoView()); + } + return true; + } + } + return false; +} +function selectTextblockSide(side) { + return function(state, dispatch) { + let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to; + let depth = $pos.depth; + while ($pos.node(depth).isInline) { + if (!depth) + return false; + depth--; + } + if (!$pos.node(depth).isTextblock) + return false; + if (dispatch) + dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth)))); + return true; + }; +} +var selectTextblockStart = selectTextblockSide(-1); +var selectTextblockEnd = selectTextblockSide(1); +function wrapIn(nodeType, attrs = null) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs); + if (!wrapping) + return false; + if (dispatch) + dispatch(state.tr.wrap(range, wrapping).scrollIntoView()); + return true; + }; +} +function setBlockType2(nodeType, attrs = null) { + return function(state, dispatch) { + let applicable = false; + for (let i = 0; i < state.selection.ranges.length && !applicable; i++) { + let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i]; + state.doc.nodesBetween(from, to, (node, pos) => { + if (applicable) + return false; + if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) + return; + if (node.type == nodeType) { + applicable = true; + } else { + let $pos = state.doc.resolve(pos), index = $pos.index(); + applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType); + } + }); + } + if (!applicable) + return false; + if (dispatch) { + let tr = state.tr; + for (let i = 0; i < state.selection.ranges.length; i++) { + let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i]; + tr.setBlockType(from, to, nodeType, attrs); + } + dispatch(tr.scrollIntoView()); + } + return true; + }; +} +function chainCommands(...commands) { + return function(state, dispatch, view) { + for (let i = 0; i < commands.length; i++) + if (commands[i](state, dispatch, view)) + return true; + return false; + }; +} +var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward); +var del = chainCommands(deleteSelection, joinForward, selectNodeForward); +var pcBaseKeymap = { + "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock), + "Mod-Enter": exitCode, + "Backspace": backspace, + "Mod-Backspace": backspace, + "Shift-Backspace": backspace, + "Delete": del, + "Mod-Delete": del, + "Mod-a": selectAll +}; +var macBaseKeymap = { + "Ctrl-h": pcBaseKeymap["Backspace"], + "Alt-Backspace": pcBaseKeymap["Mod-Backspace"], + "Ctrl-d": pcBaseKeymap["Delete"], + "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"], + "Alt-Delete": pcBaseKeymap["Mod-Delete"], + "Alt-d": pcBaseKeymap["Mod-Delete"], + "Ctrl-a": selectTextblockStart, + "Ctrl-e": selectTextblockEnd +}; +for (let key in pcBaseKeymap) + macBaseKeymap[key] = pcBaseKeymap[key]; +var mac = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false; + +// node_modules/prosemirror-schema-list/dist/index.js +function wrapInList(listType, attrs = null) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to); + if (!range) + return false; + let tr = dispatch ? state.tr : null; + if (!wrapRangeInList(tr, range, listType, attrs)) + return false; + if (dispatch) + dispatch(tr.scrollIntoView()); + return true; + }; +} +function wrapRangeInList(tr, range, listType, attrs = null) { + let doJoin = false, outerRange = range, doc3 = range.$from.doc; + if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) { + if (range.$from.index(range.depth - 1) == 0) + return false; + let $insert = doc3.resolve(range.start - 2); + outerRange = new NodeRange($insert, $insert, range.depth); + if (range.endIndex < range.parent.childCount) + range = new NodeRange(range.$from, doc3.resolve(range.$to.end(range.depth)), range.depth); + doJoin = true; + } + let wrap2 = findWrapping(outerRange, listType, attrs, range); + if (!wrap2) + return false; + if (tr) + doWrapInList(tr, range, wrap2, doJoin, listType); + return true; +} +function doWrapInList(tr, range, wrappers, joinBefore, listType) { + let content = Fragment.empty; + for (let i = wrappers.length - 1; i >= 0; i--) + content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); + tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true)); + let found2 = 0; + for (let i = 0; i < wrappers.length; i++) + if (wrappers[i].type == listType) + found2 = i + 1; + let splitDepth = wrappers.length - found2; + let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent; + for (let i = range.startIndex, e = range.endIndex, first2 = true; i < e; i++, first2 = false) { + if (!first2 && canSplit(tr.doc, splitPos, splitDepth)) { + tr.split(splitPos, splitDepth); + splitPos += 2 * splitDepth; + } + splitPos += parent.child(i).nodeSize; + } + return tr; +} +function liftListItem(itemType) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); + if (!range) + return false; + if (!dispatch) + return true; + if ($from.node(range.depth - 1).type == itemType) + return liftToOuterList(state, dispatch, itemType, range); + else + return liftOutOfList(state, dispatch, range); + }; +} +function liftToOuterList(state, dispatch, itemType, range) { + let tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth); + if (end < endOfList) { + tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true)); + range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth); + } + const target = liftTarget(range); + if (target == null) + return false; + tr.lift(range, target); + let $after = tr.doc.resolve(tr.mapping.map(end, -1) - 1); + if (canJoin(tr.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type) + tr.join($after.pos); + dispatch(tr.scrollIntoView()); + return true; +} +function liftOutOfList(state, dispatch, range) { + let tr = state.tr, list = range.parent; + for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) { + pos -= list.child(i).nodeSize; + tr.delete(pos - 1, pos + 1); + } + let $start = tr.doc.resolve(range.start), item = $start.nodeAfter; + if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) + return false; + let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount; + let parent = $start.node(-1), indexBefore = $start.index(-1); + if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list)))) + return false; + let start = $start.pos, end = start + item.nodeSize; + tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1)); + dispatch(tr.scrollIntoView()); + return true; +} +function sinkListItem(itemType) { + return function(state, dispatch) { + let { $from, $to } = state.selection; + let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); + if (!range) + return false; + let startIndex = range.startIndex; + if (startIndex == 0) + return false; + let parent = range.parent, nodeBefore = parent.child(startIndex - 1); + if (nodeBefore.type != itemType) + return false; + if (dispatch) { + let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type; + let inner = Fragment.from(nestedBefore ? itemType.create() : null); + let slice = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0); + let before = range.start, after = range.end; + dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true)).scrollIntoView()); + } + return true; + }; +} + +// node_modules/prosemirror-view/dist/index.js +var domIndex = function(node) { + for (var index = 0; ; index++) { + node = node.previousSibling; + if (!node) + return index; + } +}; +var parentNode = function(node) { + let parent = node.assignedSlot || node.parentNode; + return parent && parent.nodeType == 11 ? parent.host : parent; +}; +var reusedRange = null; +var textRange = function(node, from, to) { + let range = reusedRange || (reusedRange = document.createRange()); + range.setEnd(node, to == null ? node.nodeValue.length : to); + range.setStart(node, from || 0); + return range; +}; +var clearReusedRange = function() { + reusedRange = null; +}; +var isEquivalentPosition = function(node, off, targetNode, targetOff) { + return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1)); +}; +var atomElements = /^(img|br|input|textarea|hr)$/i; +function scanFor(node, off, targetNode, targetOff, dir) { + var _a; + for (; ; ) { + if (node == targetNode && off == targetOff) + return true; + if (off == (dir < 0 ? 0 : nodeSize(node))) { + let parent = node.parentNode; + if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") + return false; + off = domIndex(node) + (dir < 0 ? 0 : 1); + node = parent; + } else if (node.nodeType == 1) { + let child = node.childNodes[off + (dir < 0 ? -1 : 0)]; + if (child.nodeType == 1 && child.contentEditable == "false") { + if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection) + off += dir; + else + return false; + } else { + node = child; + off = dir < 0 ? nodeSize(node) : 0; + } + } else { + return false; + } + } +} +function nodeSize(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; +} +function textNodeBefore$1(node, offset) { + for (; ; ) { + if (node.nodeType == 3 && offset) + return node; + if (node.nodeType == 1 && offset > 0) { + if (node.contentEditable == "false") + return null; + node = node.childNodes[offset - 1]; + offset = nodeSize(node); + } else if (node.parentNode && !hasBlockDesc(node)) { + offset = domIndex(node); + node = node.parentNode; + } else { + return null; + } + } +} +function textNodeAfter$1(node, offset) { + for (; ; ) { + if (node.nodeType == 3 && offset < node.nodeValue.length) + return node; + if (node.nodeType == 1 && offset < node.childNodes.length) { + if (node.contentEditable == "false") + return null; + node = node.childNodes[offset]; + offset = 0; + } else if (node.parentNode && !hasBlockDesc(node)) { + offset = domIndex(node) + 1; + node = node.parentNode; + } else { + return null; + } + } +} +function isOnEdge(node, offset, parent) { + for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) { + if (node == parent) + return true; + let index = domIndex(node); + node = node.parentNode; + if (!node) + return false; + atStart = atStart && index == 0; + atEnd = atEnd && index == nodeSize(node); + } +} +function hasBlockDesc(dom) { + let desc; + for (let cur = dom; cur; cur = cur.parentNode) + if (desc = cur.pmViewDesc) + break; + return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom); +} +var selectionCollapsed = function(domSel) { + return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset); +}; +function keyEvent(keyCode, key) { + let event = document.createEvent("Event"); + event.initEvent("keydown", true, true); + event.keyCode = keyCode; + event.key = event.code = key; + return event; +} +function deepActiveElement(doc3) { + let elt = doc3.activeElement; + while (elt && elt.shadowRoot) + elt = elt.shadowRoot.activeElement; + return elt; +} +function caretFromPoint(doc3, x, y) { + if (doc3.caretPositionFromPoint) { + try { + let pos = doc3.caretPositionFromPoint(x, y); + if (pos) + return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) }; + } catch (_) { + } + } + if (doc3.caretRangeFromPoint) { + let range = doc3.caretRangeFromPoint(x, y); + if (range) + return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) }; + } +} +var nav = typeof navigator != "undefined" ? navigator : null; +var doc2 = typeof document != "undefined" ? document : null; +var agent = nav && nav.userAgent || ""; +var ie_edge = /Edge\/(\d+)/.exec(agent); +var ie_upto10 = /MSIE \d/.exec(agent); +var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent); +var ie = !!(ie_upto10 || ie_11up || ie_edge); +var ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0; +var gecko = !ie && /gecko\/(\d+)/i.test(agent); +gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1]; +var _chrome = !ie && /Chrome\/(\d+)/.exec(agent); +var chrome = !!_chrome; +var chrome_version = _chrome ? +_chrome[1] : 0; +var safari = !ie && !!nav && /Apple Computer/.test(nav.vendor); +var ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2); +var mac2 = ios || (nav ? /Mac/.test(nav.platform) : false); +var windows = nav ? /Win/.test(nav.platform) : false; +var android = /Android \d/.test(agent); +var webkit = !!doc2 && "webkitFontSmoothing" in doc2.documentElement.style; +var webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0; +function windowRect(doc3) { + let vp = doc3.defaultView && doc3.defaultView.visualViewport; + if (vp) + return { + left: 0, + right: vp.width, + top: 0, + bottom: vp.height + }; + return { + left: 0, + right: doc3.documentElement.clientWidth, + top: 0, + bottom: doc3.documentElement.clientHeight + }; +} +function getSide(value, side) { + return typeof value == "number" ? value : value[side]; +} +function clientRect(node) { + let rect = node.getBoundingClientRect(); + let scaleX = rect.width / node.offsetWidth || 1; + let scaleY = rect.height / node.offsetHeight || 1; + return { + left: rect.left, + right: rect.left + node.clientWidth * scaleX, + top: rect.top, + bottom: rect.top + node.clientHeight * scaleY + }; +} +function scrollRectIntoView(view, rect, startDOM) { + let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5; + let doc3 = view.dom.ownerDocument; + for (let parent = startDOM || view.dom; ; ) { + if (!parent) + break; + if (parent.nodeType != 1) { + parent = parentNode(parent); + continue; + } + let elt = parent; + let atTop = elt == doc3.body; + let bounding = atTop ? windowRect(doc3) : clientRect(elt); + let moveX = 0, moveY = 0; + if (rect.top < bounding.top + getSide(scrollThreshold, "top")) + moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top")); + else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) + moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom"); + if (rect.left < bounding.left + getSide(scrollThreshold, "left")) + moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left")); + else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) + moveX = rect.right - bounding.right + getSide(scrollMargin, "right"); + if (moveX || moveY) { + if (atTop) { + doc3.defaultView.scrollBy(moveX, moveY); + } else { + let startX = elt.scrollLeft, startY = elt.scrollTop; + if (moveY) + elt.scrollTop += moveY; + if (moveX) + elt.scrollLeft += moveX; + let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY; + rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY }; + } + } + let pos = atTop ? "fixed" : getComputedStyle(parent).position; + if (/^(fixed|sticky)$/.test(pos)) + break; + parent = pos == "absolute" ? parent.offsetParent : parentNode(parent); + } +} +function storeScrollPos(view) { + let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top); + let refDOM, refTop; + for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) { + let dom = view.root.elementFromPoint(x, y); + if (!dom || dom == view.dom || !view.dom.contains(dom)) + continue; + let localRect = dom.getBoundingClientRect(); + if (localRect.top >= startY - 20) { + refDOM = dom; + refTop = localRect.top; + break; + } + } + return { refDOM, refTop, stack: scrollStack(view.dom) }; +} +function scrollStack(dom) { + let stack = [], doc3 = dom.ownerDocument; + for (let cur = dom; cur; cur = parentNode(cur)) { + stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft }); + if (dom == doc3) + break; + } + return stack; +} +function resetScrollPos({ refDOM, refTop, stack }) { + let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0; + restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop); +} +function restoreScrollStack(stack, dTop) { + for (let i = 0; i < stack.length; i++) { + let { dom, top, left } = stack[i]; + if (dom.scrollTop != top + dTop) + dom.scrollTop = top + dTop; + if (dom.scrollLeft != left) + dom.scrollLeft = left; + } +} +var preventScrollSupported = null; +function focusPreventScroll(dom) { + if (dom.setActive) + return dom.setActive(); + if (preventScrollSupported) + return dom.focus(preventScrollSupported); + let stored = scrollStack(dom); + dom.focus(preventScrollSupported == null ? { + get preventScroll() { + preventScrollSupported = { preventScroll: true }; + return true; + } + } : void 0); + if (!preventScrollSupported) { + preventScrollSupported = false; + restoreScrollStack(stored, 0); + } +} +function findOffsetInNode(node, coords) { + let closest, dxClosest = 2e8, coordsClosest, offset = 0; + let rowBot = coords.top, rowTop = coords.top; + let firstBelow, coordsBelow; + for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) { + let rects; + if (child.nodeType == 1) + rects = child.getClientRects(); + else if (child.nodeType == 3) + rects = textRange(child).getClientRects(); + else + continue; + for (let i = 0; i < rects.length; i++) { + let rect = rects[i]; + if (rect.top <= rowBot && rect.bottom >= rowTop) { + rowBot = Math.max(rect.bottom, rowBot); + rowTop = Math.min(rect.top, rowTop); + let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0; + if (dx < dxClosest) { + closest = child; + dxClosest = dx; + coordsClosest = dx && closest.nodeType == 3 ? { + left: rect.right < coords.left ? rect.right : rect.left, + top: coords.top + } : coords; + if (child.nodeType == 1 && dx) + offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); + continue; + } + } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) { + firstBelow = child; + coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top }; + } + if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom)) + offset = childIndex + 1; + } + } + if (!closest && firstBelow) { + closest = firstBelow; + coordsClosest = coordsBelow; + dxClosest = 0; + } + if (closest && closest.nodeType == 3) + return findOffsetInText(closest, coordsClosest); + if (!closest || dxClosest && closest.nodeType == 1) + return { node, offset }; + return findOffsetInNode(closest, coordsClosest); +} +function findOffsetInText(node, coords) { + let len = node.nodeValue.length; + let range = document.createRange(), result; + for (let i = 0; i < len; i++) { + range.setEnd(node, i + 1); + range.setStart(node, i); + let rect = singleRect(range, 1); + if (rect.top == rect.bottom) + continue; + if (inRect(coords, rect)) { + result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) }; + break; + } + } + range.detach(); + return result || { node, offset: 0 }; +} +function inRect(coords, rect) { + return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1; +} +function targetKludge(dom, coords) { + let parent = dom.parentNode; + if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) + return parent; + return dom; +} +function posFromElement(view, elt, coords) { + let { node, offset } = findOffsetInNode(elt, coords), bias = -1; + if (node.nodeType == 1 && !node.firstChild) { + let rect = node.getBoundingClientRect(); + bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1; + } + return view.docView.posFromDOM(node, offset, bias); +} +function posFromCaret(view, node, offset, coords) { + let outsideBlock = -1; + for (let cur = node, sawBlock = false; ; ) { + if (cur == view.dom) + break; + let desc = view.docView.nearestDesc(cur, true), rect; + if (!desc) + return null; + if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles + ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) { + if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) { + if (!sawBlock && rect.left > coords.left || rect.top > coords.top) + outsideBlock = desc.posBefore; + else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top) + outsideBlock = desc.posAfter; + sawBlock = true; + } + if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) { + let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2; + return before ? desc.posBefore : desc.posAfter; + } + } + cur = desc.dom.parentNode; + } + return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1); +} +function elementFromPoint(element, coords, box) { + let len = element.childNodes.length; + if (len && box.top < box.bottom) { + for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI; ; ) { + let child = element.childNodes[i]; + if (child.nodeType == 1) { + let rects = child.getClientRects(); + for (let j = 0; j < rects.length; j++) { + let rect = rects[j]; + if (inRect(coords, rect)) + return elementFromPoint(child, coords, rect); + } + } + if ((i = (i + 1) % len) == startI) + break; + } + } + return element; +} +function posAtCoords(view, coords) { + let doc3 = view.dom.ownerDocument, node, offset = 0; + let caret = caretFromPoint(doc3, coords.left, coords.top); + if (caret) + ({ node, offset } = caret); + let elt = (view.root.elementFromPoint ? view.root : doc3).elementFromPoint(coords.left, coords.top); + let pos; + if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) { + let box = view.dom.getBoundingClientRect(); + if (!inRect(coords, box)) + return null; + elt = elementFromPoint(view.dom, coords, box); + if (!elt) + return null; + } + if (safari) { + for (let p = elt; node && p; p = parentNode(p)) + if (p.draggable) + node = void 0; + } + elt = targetKludge(elt, coords); + if (node) { + if (gecko && node.nodeType == 1) { + offset = Math.min(offset, node.childNodes.length); + if (offset < node.childNodes.length) { + let next = node.childNodes[offset], box; + if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top) + offset++; + } + } + let prev; + if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top) + offset--; + if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom) + pos = view.state.doc.content.size; + else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR") + pos = posFromCaret(view, node, offset, coords); + } + if (pos == null) + pos = posFromElement(view, elt, coords); + let desc = view.docView.nearestDesc(elt, true); + return { pos, inside: desc ? desc.posAtStart - desc.border : -1 }; +} +function nonZero(rect) { + return rect.top < rect.bottom || rect.left < rect.right; +} +function singleRect(target, bias) { + let rects = target.getClientRects(); + if (rects.length) { + let first2 = rects[bias < 0 ? 0 : rects.length - 1]; + if (nonZero(first2)) + return first2; + } + return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect(); +} +var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; +function coordsAtPos(view, pos, side) { + let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1); + let supportEmptyRange = webkit || gecko; + if (node.nodeType == 3) { + if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) { + let rect = singleRect(textRange(node, offset, offset), side); + if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) { + let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1); + if (rectBefore.top == rect.top) { + let rectAfter = singleRect(textRange(node, offset, offset + 1), -1); + if (rectAfter.top != rect.top) + return flattenV(rectAfter, rectAfter.left < rectBefore.left); + } + } + return rect; + } else { + let from = offset, to = offset, takeSide = side < 0 ? 1 : -1; + if (side < 0 && !offset) { + to++; + takeSide = -1; + } else if (side >= 0 && offset == node.nodeValue.length) { + from--; + takeSide = 1; + } else if (side < 0) { + from--; + } else { + to++; + } + return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0); + } + } + let $dom = view.state.doc.resolve(pos - (atom || 0)); + if (!$dom.parent.inlineContent) { + if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { + let before = node.childNodes[offset - 1]; + if (before.nodeType == 1) + return flattenH(before.getBoundingClientRect(), false); + } + if (atom == null && offset < nodeSize(node)) { + let after = node.childNodes[offset]; + if (after.nodeType == 1) + return flattenH(after.getBoundingClientRect(), true); + } + return flattenH(node.getBoundingClientRect(), side >= 0); + } + if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { + let before = node.childNodes[offset - 1]; + let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null; + if (target) + return flattenV(singleRect(target, 1), false); + } + if (atom == null && offset < nodeSize(node)) { + let after = node.childNodes[offset]; + while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords) + after = after.nextSibling; + let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null; + if (target) + return flattenV(singleRect(target, -1), true); + } + return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0); +} +function flattenV(rect, left) { + if (rect.width == 0) + return rect; + let x = left ? rect.left : rect.right; + return { top: rect.top, bottom: rect.bottom, left: x, right: x }; +} +function flattenH(rect, top) { + if (rect.height == 0) + return rect; + let y = top ? rect.top : rect.bottom; + return { top: y, bottom: y, left: rect.left, right: rect.right }; +} +function withFlushedState(view, state, f) { + let viewState = view.state, active = view.root.activeElement; + if (viewState != state) + view.updateState(state); + if (active != view.dom) + view.focus(); + try { + return f(); + } finally { + if (viewState != state) + view.updateState(viewState); + if (active != view.dom && active) + active.focus(); + } +} +function endOfTextblockVertical(view, state, dir) { + let sel = state.selection; + let $pos = dir == "up" ? sel.$from : sel.$to; + return withFlushedState(view, state, () => { + let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1); + for (; ; ) { + let nearest = view.docView.nearestDesc(dom, true); + if (!nearest) + break; + if (nearest.node.isBlock) { + dom = nearest.contentDOM || nearest.dom; + break; + } + dom = nearest.dom.parentNode; + } + let coords = coordsAtPos(view, $pos.pos, 1); + for (let child = dom.firstChild; child; child = child.nextSibling) { + let boxes; + if (child.nodeType == 1) + boxes = child.getClientRects(); + else if (child.nodeType == 3) + boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); + else + continue; + for (let i = 0; i < boxes.length; i++) { + let box = boxes[i]; + if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2)) + return false; + } + } + return true; + }); +} +var maybeRTL = /[\u0590-\u08ac]/; +function endOfTextblockHorizontal(view, state, dir) { + let { $head } = state.selection; + if (!$head.parent.isTextblock) + return false; + let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size; + let sel = view.domSelection(); + if (!sel) + return $head.pos == $head.start() || $head.pos == $head.end(); + if (!maybeRTL.test($head.parent.textContent) || !sel.modify) + return dir == "left" || dir == "backward" ? atStart : atEnd; + return withFlushedState(view, state, () => { + let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange(); + let oldBidiLevel = sel.caretBidiLevel; + sel.modify("move", dir, "character"); + let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom; + let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange(); + let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff; + try { + sel.collapse(anchorNode, anchorOffset); + if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend) + sel.extend(oldNode, oldOff); + } catch (_) { + } + if (oldBidiLevel != null) + sel.caretBidiLevel = oldBidiLevel; + return result; + }); +} +var cachedState = null; +var cachedDir = null; +var cachedResult = false; +function endOfTextblock(view, state, dir) { + if (cachedState == state && cachedDir == dir) + return cachedResult; + cachedState = state; + cachedDir = dir; + return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir); +} +var NOT_DIRTY = 0; +var CHILD_DIRTY = 1; +var CONTENT_DIRTY = 2; +var NODE_DIRTY = 3; +var ViewDesc = class { + constructor(parent, children, dom, contentDOM) { + this.parent = parent; + this.children = children; + this.dom = dom; + this.contentDOM = contentDOM; + this.dirty = NOT_DIRTY; + dom.pmViewDesc = this; + } + // Used to check whether a given description corresponds to a + // widget/mark/node. + matchesWidget(widget) { + return false; + } + matchesMark(mark) { + return false; + } + matchesNode(node, outerDeco, innerDeco) { + return false; + } + matchesHack(nodeName) { + return false; + } + // When parsing in-editor content (in domchange.js), we allow + // descriptions to determine the parse rules that should be used to + // parse them. + parseRule() { + return null; + } + // Used by the editor's event handler to ignore events that come + // from certain descs. + stopEvent(event) { + return false; + } + // The size of the content represented by this desc. + get size() { + let size = 0; + for (let i = 0; i < this.children.length; i++) + size += this.children[i].size; + return size; + } + // For block nodes, this represents the space taken up by their + // start/end tokens. + get border() { + return 0; + } + destroy() { + this.parent = void 0; + if (this.dom.pmViewDesc == this) + this.dom.pmViewDesc = void 0; + for (let i = 0; i < this.children.length; i++) + this.children[i].destroy(); + } + posBeforeChild(child) { + for (let i = 0, pos = this.posAtStart; ; i++) { + let cur = this.children[i]; + if (cur == child) + return pos; + pos += cur.size; + } + } + get posBefore() { + return this.parent.posBeforeChild(this); + } + get posAtStart() { + return this.parent ? this.parent.posBeforeChild(this) + this.border : 0; + } + get posAfter() { + return this.posBefore + this.size; + } + get posAtEnd() { + return this.posAtStart + this.size - 2 * this.border; + } + localPosFromDOM(dom, offset, bias) { + if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) { + if (bias < 0) { + let domBefore, desc; + if (dom == this.contentDOM) { + domBefore = dom.childNodes[offset - 1]; + } else { + while (dom.parentNode != this.contentDOM) + dom = dom.parentNode; + domBefore = dom.previousSibling; + } + while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) + domBefore = domBefore.previousSibling; + return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart; + } else { + let domAfter, desc; + if (dom == this.contentDOM) { + domAfter = dom.childNodes[offset]; + } else { + while (dom.parentNode != this.contentDOM) + dom = dom.parentNode; + domAfter = dom.nextSibling; + } + while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) + domAfter = domAfter.nextSibling; + return domAfter ? this.posBeforeChild(desc) : this.posAtEnd; + } + } + let atEnd; + if (dom == this.dom && this.contentDOM) { + atEnd = offset > domIndex(this.contentDOM); + } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) { + atEnd = dom.compareDocumentPosition(this.contentDOM) & 2; + } else if (this.dom.firstChild) { + if (offset == 0) + for (let search = dom; ; search = search.parentNode) { + if (search == this.dom) { + atEnd = false; + break; + } + if (search.previousSibling) + break; + } + if (atEnd == null && offset == dom.childNodes.length) + for (let search = dom; ; search = search.parentNode) { + if (search == this.dom) { + atEnd = true; + break; + } + if (search.nextSibling) + break; + } + } + return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart; + } + nearestDesc(dom, onlyNodes = false) { + for (let first2 = true, cur = dom; cur; cur = cur.parentNode) { + let desc = this.getDesc(cur), nodeDOM; + if (desc && (!onlyNodes || desc.node)) { + if (first2 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom)) + first2 = false; + else + return desc; + } + } + } + getDesc(dom) { + let desc = dom.pmViewDesc; + for (let cur = desc; cur; cur = cur.parent) + if (cur == this) + return desc; + } + posFromDOM(dom, offset, bias) { + for (let scan = dom; scan; scan = scan.parentNode) { + let desc = this.getDesc(scan); + if (desc) + return desc.localPosFromDOM(dom, offset, bias); + } + return -1; + } + // Find the desc for the node after the given pos, if any. (When a + // parent node overrode rendering, there might not be one.) + descAt(pos) { + for (let i = 0, offset = 0; i < this.children.length; i++) { + let child = this.children[i], end = offset + child.size; + if (offset == pos && end != offset) { + while (!child.border && child.children.length) { + for (let i2 = 0; i2 < child.children.length; i2++) { + let inner = child.children[i2]; + if (inner.size) { + child = inner; + break; + } + } + } + return child; + } + if (pos < end) + return child.descAt(pos - offset - child.border); + offset = end; + } + } + domFromPos(pos, side) { + if (!this.contentDOM) + return { node: this.dom, offset: 0, atom: pos + 1 }; + let i = 0, offset = 0; + for (let curPos = 0; i < this.children.length; i++) { + let child = this.children[i], end = curPos + child.size; + if (end > pos || child instanceof TrailingHackViewDesc) { + offset = pos - curPos; + break; + } + curPos = end; + } + if (offset) + return this.children[i].domFromPos(offset - this.children[i].border, side); + for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) { + } + if (side <= 0) { + let prev, enter2 = true; + for (; ; i--, enter2 = false) { + prev = i ? this.children[i - 1] : null; + if (!prev || prev.dom.parentNode == this.contentDOM) + break; + } + if (prev && side && enter2 && !prev.border && !prev.domAtom) + return prev.domFromPos(prev.size, side); + return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 }; + } else { + let next, enter2 = true; + for (; ; i++, enter2 = false) { + next = i < this.children.length ? this.children[i] : null; + if (!next || next.dom.parentNode == this.contentDOM) + break; + } + if (next && enter2 && !next.border && !next.domAtom) + return next.domFromPos(0, side); + return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length }; + } + } + // Used to find a DOM range in a single parent for a given changed + // range. + parseRange(from, to, base2 = 0) { + if (this.children.length == 0) + return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length }; + let fromOffset = -1, toOffset = -1; + for (let offset = base2, i = 0; ; i++) { + let child = this.children[i], end = offset + child.size; + if (fromOffset == -1 && from <= end) { + let childBase = offset + child.border; + if (from >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM)) + return child.parseRange(from, to, childBase); + from = offset; + for (let j = i; j > 0; j--) { + let prev = this.children[j - 1]; + if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) { + fromOffset = domIndex(prev.dom) + 1; + break; + } + from -= prev.size; + } + if (fromOffset == -1) + fromOffset = 0; + } + if (fromOffset > -1 && (end > to || i == this.children.length - 1)) { + to = end; + for (let j = i + 1; j < this.children.length; j++) { + let next = this.children[j]; + if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) { + toOffset = domIndex(next.dom); + break; + } + to += next.size; + } + if (toOffset == -1) + toOffset = this.contentDOM.childNodes.length; + break; + } + offset = end; + } + return { node: this.contentDOM, from, to, fromOffset, toOffset }; + } + emptyChildAt(side) { + if (this.border || !this.contentDOM || !this.children.length) + return false; + let child = this.children[side < 0 ? 0 : this.children.length - 1]; + return child.size == 0 || child.emptyChildAt(side); + } + domAfterPos(pos) { + let { node, offset } = this.domFromPos(pos, 0); + if (node.nodeType != 1 || offset == node.childNodes.length) + throw new RangeError("No node after pos " + pos); + return node.childNodes[offset]; + } + // View descs are responsible for setting any selection that falls + // entirely inside of them, so that custom implementations can do + // custom things with the selection. Note that this falls apart when + // a selection starts in such a node and ends in another, in which + // case we just use whatever domFromPos produces as a best effort. + setSelection(anchor, head, view, force = false) { + let from = Math.min(anchor, head), to = Math.max(anchor, head); + for (let i = 0, offset = 0; i < this.children.length; i++) { + let child = this.children[i], end = offset + child.size; + if (from > offset && to < end) + return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force); + offset = end; + } + let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1); + let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1); + let domSel = view.root.getSelection(); + let selRange = view.domSelectionRange(); + let brKludge = false; + if ((gecko || safari) && anchor == head) { + let { node, offset } = anchorDOM; + if (node.nodeType == 3) { + brKludge = !!(offset && node.nodeValue[offset - 1] == "\n"); + if (brKludge && offset == node.nodeValue.length) { + for (let scan = node, after; scan; scan = scan.parentNode) { + if (after = scan.nextSibling) { + if (after.nodeName == "BR") + anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 }; + break; + } + let desc = scan.pmViewDesc; + if (desc && desc.node && desc.node.isBlock) + break; + } + } + } else { + let prev = node.childNodes[offset - 1]; + brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false"); + } + } + if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) { + let after = selRange.focusNode.childNodes[selRange.focusOffset]; + if (after && after.contentEditable == "false") + force = true; + } + if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset)) + return; + let domSelExtended = false; + if ((domSel.extend || anchor == head) && !(brKludge && gecko)) { + domSel.collapse(anchorDOM.node, anchorDOM.offset); + try { + if (anchor != head) + domSel.extend(headDOM.node, headDOM.offset); + domSelExtended = true; + } catch (_) { + } + } + if (!domSelExtended) { + if (anchor > head) { + let tmp = anchorDOM; + anchorDOM = headDOM; + headDOM = tmp; + } + let range = document.createRange(); + range.setEnd(headDOM.node, headDOM.offset); + range.setStart(anchorDOM.node, anchorDOM.offset); + domSel.removeAllRanges(); + domSel.addRange(range); + } + } + ignoreMutation(mutation) { + return !this.contentDOM && mutation.type != "selection"; + } + get contentLost() { + return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM); + } + // Remove a subtree of the element tree that has been touched + // by a DOM change, so that the next update will redraw it. + markDirty(from, to) { + for (let offset = 0, i = 0; i < this.children.length; i++) { + let child = this.children[i], end = offset + child.size; + if (offset == end ? from <= end && to >= offset : from < end && to > offset) { + let startInside = offset + child.border, endInside = end - child.border; + if (from >= startInside && to <= endInside) { + this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY; + if (from == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM)) + child.dirty = NODE_DIRTY; + else + child.markDirty(from - startInside, to - startInside); + return; + } else { + child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY; + } + } + offset = end; + } + this.dirty = CONTENT_DIRTY; + } + markParentsDirty() { + let level = 1; + for (let node = this.parent; node; node = node.parent, level++) { + let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY; + if (node.dirty < dirty) + node.dirty = dirty; + } + } + get domAtom() { + return false; + } + get ignoreForCoords() { + return false; + } + get ignoreForSelection() { + return false; + } + isText(text) { + return false; + } +}; +var WidgetViewDesc = class extends ViewDesc { + constructor(parent, widget, view, pos) { + let self, dom = widget.type.toDOM; + if (typeof dom == "function") + dom = dom(view, () => { + if (!self) + return pos; + if (self.parent) + return self.parent.posBeforeChild(self); + }); + if (!widget.type.spec.raw) { + if (dom.nodeType != 1) { + let wrap2 = document.createElement("span"); + wrap2.appendChild(dom); + dom = wrap2; + } + dom.contentEditable = "false"; + dom.classList.add("ProseMirror-widget"); + } + super(parent, [], dom, null); + this.widget = widget; + this.widget = widget; + self = this; + } + matchesWidget(widget) { + return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type); + } + parseRule() { + return { ignore: true }; + } + stopEvent(event) { + let stop = this.widget.spec.stopEvent; + return stop ? stop(event) : false; + } + ignoreMutation(mutation) { + return mutation.type != "selection" || this.widget.spec.ignoreSelection; + } + destroy() { + this.widget.type.destroy(this.dom); + super.destroy(); + } + get domAtom() { + return true; + } + get ignoreForSelection() { + return !!this.widget.type.spec.relaxedSide; + } + get side() { + return this.widget.type.side; + } +}; +var CompositionViewDesc = class extends ViewDesc { + constructor(parent, dom, textDOM, text) { + super(parent, [], dom, null); + this.textDOM = textDOM; + this.text = text; + } + get size() { + return this.text.length; + } + localPosFromDOM(dom, offset) { + if (dom != this.textDOM) + return this.posAtStart + (offset ? this.size : 0); + return this.posAtStart + offset; + } + domFromPos(pos) { + return { node: this.textDOM, offset: pos }; + } + ignoreMutation(mut) { + return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue; + } +}; +var MarkViewDesc = class _MarkViewDesc extends ViewDesc { + constructor(parent, mark, dom, contentDOM, spec) { + super(parent, [], dom, contentDOM); + this.mark = mark; + this.spec = spec; + } + static create(parent, mark, inline, view) { + let custom = view.nodeViews[mark.type.name]; + let spec = custom && custom(mark, view, inline); + if (!spec || !spec.dom) + spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs); + return new _MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec); + } + parseRule() { + if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView) + return null; + return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM }; + } + matchesMark(mark) { + return this.dirty != NODE_DIRTY && this.mark.eq(mark); + } + markDirty(from, to) { + super.markDirty(from, to); + if (this.dirty != NOT_DIRTY) { + let parent = this.parent; + while (!parent.node) + parent = parent.parent; + if (parent.dirty < this.dirty) + parent.dirty = this.dirty; + this.dirty = NOT_DIRTY; + } + } + slice(from, to, view) { + let copy2 = _MarkViewDesc.create(this.parent, this.mark, true, view); + let nodes = this.children, size = this.size; + if (to < size) + nodes = replaceNodes(nodes, to, size, view); + if (from > 0) + nodes = replaceNodes(nodes, 0, from, view); + for (let i = 0; i < nodes.length; i++) + nodes[i].parent = copy2; + copy2.children = nodes; + return copy2; + } + ignoreMutation(mutation) { + return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); + } + destroy() { + if (this.spec.destroy) + this.spec.destroy(); + super.destroy(); + } +}; +var NodeViewDesc = class _NodeViewDesc extends ViewDesc { + constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) { + super(parent, [], dom, contentDOM); + this.node = node; + this.outerDeco = outerDeco; + this.innerDeco = innerDeco; + this.nodeDOM = nodeDOM; + } + // By default, a node is rendered using the `toDOM` method from the + // node type spec. But client code can use the `nodeViews` spec to + // supply a custom node view, which can influence various aspects of + // the way the node works. + // + // (Using subclassing for this was intentionally decided against, + // since it'd require exposing a whole slew of finicky + // implementation details to the user code that they probably will + // never need.) + static create(parent, node, outerDeco, innerDeco, view, pos) { + let custom = view.nodeViews[node.type.name], descObj; + let spec = custom && custom(node, view, () => { + if (!descObj) + return pos; + if (descObj.parent) + return descObj.parent.posBeforeChild(descObj); + }, outerDeco, innerDeco); + let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM; + if (node.isText) { + if (!dom) + dom = document.createTextNode(node.text); + else if (dom.nodeType != 3) + throw new RangeError("Text must be rendered as a DOM text node"); + } else if (!dom) { + let spec2 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs); + ({ dom, contentDOM } = spec2); + } + if (!contentDOM && !node.isText && dom.nodeName != "BR") { + if (!dom.hasAttribute("contenteditable")) + dom.contentEditable = "false"; + if (node.type.spec.draggable) + dom.draggable = true; + } + let nodeDOM = dom; + dom = applyOuterDeco(dom, outerDeco, node); + if (spec) + return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1); + else if (node.isText) + return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view); + else + return new _NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1); + } + parseRule() { + if (this.node.type.spec.reparseInView) + return null; + let rule = { node: this.node.type.name, attrs: this.node.attrs }; + if (this.node.type.whitespace == "pre") + rule.preserveWhitespace = "full"; + if (!this.contentDOM) { + rule.getContent = () => this.node.content; + } else if (!this.contentLost) { + rule.contentElement = this.contentDOM; + } else { + for (let i = this.children.length - 1; i >= 0; i--) { + let child = this.children[i]; + if (this.dom.contains(child.dom.parentNode)) { + rule.contentElement = child.dom.parentNode; + break; + } + } + if (!rule.contentElement) + rule.getContent = () => Fragment.empty; + } + return rule; + } + matchesNode(node, outerDeco, innerDeco) { + return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco); + } + get size() { + return this.node.nodeSize; + } + get border() { + return this.node.isLeaf ? 0 : 1; + } + // Syncs `this.children` to match `this.node.content` and the local + // decorations, possibly introducing nesting for marks. Then, in a + // separate step, syncs the DOM inside `this.contentDOM` to + // `this.children`. + updateChildren(view, pos) { + let inline = this.node.inlineContent, off = pos; + let composition = view.composing ? this.localCompositionInfo(view, pos) : null; + let localComposition = composition && composition.pos > -1 ? composition : null; + let compositionInChild = composition && composition.pos < 0; + let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view); + iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => { + if (widget.spec.marks) + updater.syncToMarks(widget.spec.marks, inline, view, i); + else if (widget.type.side >= 0 && !insideNode) + updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i); + updater.placeWidget(widget, view, off); + }, (child, outerDeco, innerDeco, i) => { + updater.syncToMarks(child.marks, inline, view, i); + let compIndex; + if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ; + else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ; + else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ; + else { + updater.addNode(child, outerDeco, innerDeco, view, off); + } + off += child.nodeSize; + }); + updater.syncToMarks([], inline, view, 0); + if (this.node.isTextblock) + updater.addTextblockHacks(); + updater.destroyRest(); + if (updater.changed || this.dirty == CONTENT_DIRTY) { + if (localComposition) + this.protectLocalComposition(view, localComposition); + renderDescs(this.contentDOM, this.children, view); + if (ios) + iosHacks(this.dom); + } + } + localCompositionInfo(view, pos) { + let { from, to } = view.state.selection; + if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size) + return null; + let textNode = view.input.compositionNode; + if (!textNode || !this.dom.contains(textNode.parentNode)) + return null; + if (this.node.inlineContent) { + let text = textNode.nodeValue; + let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos); + return textPos < 0 ? null : { node: textNode, pos: textPos, text }; + } else { + return { node: textNode, pos: -1, text: "" }; + } + } + protectLocalComposition(view, { node, pos, text }) { + if (this.getDesc(node)) + return; + let topNode = node; + for (; ; topNode = topNode.parentNode) { + if (topNode.parentNode == this.contentDOM) + break; + while (topNode.previousSibling) + topNode.parentNode.removeChild(topNode.previousSibling); + while (topNode.nextSibling) + topNode.parentNode.removeChild(topNode.nextSibling); + if (topNode.pmViewDesc) + topNode.pmViewDesc = void 0; + } + let desc = new CompositionViewDesc(this, topNode, node, text); + view.input.compositionNodes.push(desc); + this.children = replaceNodes(this.children, pos, pos + text.length, view, desc); + } + // If this desc must be updated to match the given node decoration, + // do so and return true. + update(node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node)) + return false; + this.updateInner(node, outerDeco, innerDeco, view); + return true; + } + updateInner(node, outerDeco, innerDeco, view) { + this.updateOuterDeco(outerDeco); + this.node = node; + this.innerDeco = innerDeco; + if (this.contentDOM) + this.updateChildren(view, this.posAtStart); + this.dirty = NOT_DIRTY; + } + updateOuterDeco(outerDeco) { + if (sameOuterDeco(outerDeco, this.outerDeco)) + return; + let needsWrap = this.nodeDOM.nodeType != 1; + let oldDOM = this.dom; + this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap)); + if (this.dom != oldDOM) { + oldDOM.pmViewDesc = void 0; + this.dom.pmViewDesc = this; + } + this.outerDeco = outerDeco; + } + // Mark this node as being the selected node. + selectNode() { + if (this.nodeDOM.nodeType == 1) { + this.nodeDOM.classList.add("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) + this.nodeDOM.draggable = true; + } + } + // Remove selected node marking from this node. + deselectNode() { + if (this.nodeDOM.nodeType == 1) { + this.nodeDOM.classList.remove("ProseMirror-selectednode"); + if (this.contentDOM || !this.node.type.spec.draggable) + this.nodeDOM.removeAttribute("draggable"); + } + } + get domAtom() { + return this.node.isAtom; + } +}; +function docViewDesc(doc3, outerDeco, innerDeco, dom, view) { + applyOuterDeco(dom, outerDeco, doc3); + let docView = new NodeViewDesc(void 0, doc3, outerDeco, innerDeco, dom, dom, dom, view, 0); + if (docView.contentDOM) + docView.updateChildren(view, 0); + return docView; +} +var TextViewDesc = class _TextViewDesc extends NodeViewDesc { + constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) { + super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0); + } + parseRule() { + let skip = this.nodeDOM.parentNode; + while (skip && skip != this.dom && !skip.pmIsDeco) + skip = skip.parentNode; + return { skip: skip || true }; + } + update(node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node)) + return false; + this.updateOuterDeco(outerDeco); + if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) { + this.nodeDOM.nodeValue = node.text; + if (view.trackWrites == this.nodeDOM) + view.trackWrites = null; + } + this.node = node; + this.dirty = NOT_DIRTY; + return true; + } + inParent() { + let parentDOM = this.parent.contentDOM; + for (let n = this.nodeDOM; n; n = n.parentNode) + if (n == parentDOM) + return true; + return false; + } + domFromPos(pos) { + return { node: this.nodeDOM, offset: pos }; + } + localPosFromDOM(dom, offset, bias) { + if (dom == this.nodeDOM) + return this.posAtStart + Math.min(offset, this.node.text.length); + return super.localPosFromDOM(dom, offset, bias); + } + ignoreMutation(mutation) { + return mutation.type != "characterData" && mutation.type != "selection"; + } + slice(from, to, view) { + let node = this.node.cut(from, to), dom = document.createTextNode(node.text); + return new _TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view); + } + markDirty(from, to) { + super.markDirty(from, to); + if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length)) + this.dirty = NODE_DIRTY; + } + get domAtom() { + return false; + } + isText(text) { + return this.node.text == text; + } +}; +var TrailingHackViewDesc = class extends ViewDesc { + parseRule() { + return { ignore: true }; + } + matchesHack(nodeName) { + return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; + } + get domAtom() { + return true; + } + get ignoreForCoords() { + return this.dom.nodeName == "IMG"; + } +}; +var CustomNodeViewDesc = class extends NodeViewDesc { + constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) { + super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos); + this.spec = spec; + } + // A custom `update` method gets to decide whether the update goes + // through. If it does, and there's a `contentDOM` node, our logic + // updates the children. + update(node, outerDeco, innerDeco, view) { + if (this.dirty == NODE_DIRTY) + return false; + if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) { + let result = this.spec.update(node, outerDeco, innerDeco); + if (result) + this.updateInner(node, outerDeco, innerDeco, view); + return result; + } else if (!this.contentDOM && !node.isLeaf) { + return false; + } else { + return super.update(node, outerDeco, innerDeco, view); + } + } + selectNode() { + this.spec.selectNode ? this.spec.selectNode() : super.selectNode(); + } + deselectNode() { + this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode(); + } + setSelection(anchor, head, view, force) { + this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force); + } + destroy() { + if (this.spec.destroy) + this.spec.destroy(); + super.destroy(); + } + stopEvent(event) { + return this.spec.stopEvent ? this.spec.stopEvent(event) : false; + } + ignoreMutation(mutation) { + return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); + } +}; +function renderDescs(parentDOM, descs, view) { + let dom = parentDOM.firstChild, written = false; + for (let i = 0; i < descs.length; i++) { + let desc = descs[i], childDOM = desc.dom; + if (childDOM.parentNode == parentDOM) { + while (childDOM != dom) { + dom = rm(dom); + written = true; + } + dom = dom.nextSibling; + } else { + written = true; + parentDOM.insertBefore(childDOM, dom); + } + if (desc instanceof MarkViewDesc) { + let pos = dom ? dom.previousSibling : parentDOM.lastChild; + renderDescs(desc.contentDOM, desc.children, view); + dom = pos ? pos.nextSibling : parentDOM.firstChild; + } + } + while (dom) { + dom = rm(dom); + written = true; + } + if (written && view.trackWrites == parentDOM) + view.trackWrites = null; +} +var OuterDecoLevel = function(nodeName) { + if (nodeName) + this.nodeName = nodeName; +}; +OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null); +var noDeco = [new OuterDecoLevel()]; +function computeOuterDeco(outerDeco, node, needsWrap) { + if (outerDeco.length == 0) + return noDeco; + let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top]; + for (let i = 0; i < outerDeco.length; i++) { + let attrs = outerDeco[i].type.attrs; + if (!attrs) + continue; + if (attrs.nodeName) + result.push(top = new OuterDecoLevel(attrs.nodeName)); + for (let name in attrs) { + let val = attrs[name]; + if (val == null) + continue; + if (needsWrap && result.length == 1) + result.push(top = new OuterDecoLevel(node.isInline ? "span" : "div")); + if (name == "class") + top.class = (top.class ? top.class + " " : "") + val; + else if (name == "style") + top.style = (top.style ? top.style + ";" : "") + val; + else if (name != "nodeName") + top[name] = val; + } + } + return result; +} +function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) { + if (prevComputed == noDeco && curComputed == noDeco) + return nodeDOM; + let curDOM = nodeDOM; + for (let i = 0; i < curComputed.length; i++) { + let deco = curComputed[i], prev = prevComputed[i]; + if (i) { + let parent; + if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) { + curDOM = parent; + } else { + parent = document.createElement(deco.nodeName); + parent.pmIsDeco = true; + parent.appendChild(curDOM); + prev = noDeco[0]; + curDOM = parent; + } + } + patchAttributes(curDOM, prev || noDeco[0], deco); + } + return curDOM; +} +function patchAttributes(dom, prev, cur) { + for (let name in prev) + if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) + dom.removeAttribute(name); + for (let name in cur) + if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name]) + dom.setAttribute(name, cur[name]); + if (prev.class != cur.class) { + let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : []; + let curList = cur.class ? cur.class.split(" ").filter(Boolean) : []; + for (let i = 0; i < prevList.length; i++) + if (curList.indexOf(prevList[i]) == -1) + dom.classList.remove(prevList[i]); + for (let i = 0; i < curList.length; i++) + if (prevList.indexOf(curList[i]) == -1) + dom.classList.add(curList[i]); + if (dom.classList.length == 0) + dom.removeAttribute("class"); + } + if (prev.style != cur.style) { + if (prev.style) { + let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m; + while (m = prop.exec(prev.style)) + dom.style.removeProperty(m[1]); + } + if (cur.style) + dom.style.cssText += cur.style; + } +} +function applyOuterDeco(dom, deco, node) { + return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1)); +} +function sameOuterDeco(a, b) { + if (a.length != b.length) + return false; + for (let i = 0; i < a.length; i++) + if (!a[i].type.eq(b[i].type)) + return false; + return true; +} +function rm(dom) { + let next = dom.nextSibling; + dom.parentNode.removeChild(dom); + return next; +} +var ViewTreeUpdater = class { + constructor(top, lock, view) { + this.lock = lock; + this.view = view; + this.index = 0; + this.stack = []; + this.changed = false; + this.top = top; + this.preMatch = preMatch(top.node.content, top); + } + // Destroy and remove the children between the given indices in + // `this.top`. + destroyBetween(start, end) { + if (start == end) + return; + for (let i = start; i < end; i++) + this.top.children[i].destroy(); + this.top.children.splice(start, end - start); + this.changed = true; + } + // Destroy all remaining children in `this.top`. + destroyRest() { + this.destroyBetween(this.index, this.top.children.length); + } + // Sync the current stack of mark descs with the given array of + // marks, reusing existing mark descs when possible. + syncToMarks(marks, inline, view, parentIndex) { + let keep = 0, depth = this.stack.length >> 1; + let maxKeep = Math.min(depth, marks.length); + while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) + keep++; + while (keep < depth) { + this.destroyRest(); + this.top.dirty = NOT_DIRTY; + this.index = this.stack.pop(); + this.top = this.stack.pop(); + depth--; + } + while (depth < marks.length) { + this.stack.push(this.top, this.index + 1); + let found2 = -1, scanTo = this.top.children.length; + if (parentIndex < this.preMatch.index) + scanTo = Math.min(this.index + 3, scanTo); + for (let i = this.index; i < scanTo; i++) { + let next = this.top.children[i]; + if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) { + found2 = i; + break; + } + } + if (found2 > -1) { + if (found2 > this.index) { + this.changed = true; + this.destroyBetween(this.index, found2); + } + this.top = this.top.children[this.index]; + } else { + let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view); + this.top.children.splice(this.index, 0, markDesc); + this.top = markDesc; + this.changed = true; + } + this.index = 0; + depth++; + } + } + // Try to find a node desc matching the given data. Skip over it and + // return true when successful. + findNodeMatch(node, outerDeco, innerDeco, index) { + let found2 = -1, targetDesc; + if (index >= this.preMatch.index && (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) { + found2 = this.top.children.indexOf(targetDesc, this.index); + } else { + for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) { + let child = this.top.children[i]; + if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) { + found2 = i; + break; + } + } + } + if (found2 < 0) + return false; + this.destroyBetween(this.index, found2); + this.index++; + return true; + } + updateNodeAt(node, outerDeco, innerDeco, index, view) { + let child = this.top.children[index]; + if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM) + child.dirty = CONTENT_DIRTY; + if (!child.update(node, outerDeco, innerDeco, view)) + return false; + this.destroyBetween(this.index, index); + this.index++; + return true; + } + findIndexWithChild(domNode) { + for (; ; ) { + let parent = domNode.parentNode; + if (!parent) + return -1; + if (parent == this.top.contentDOM) { + let desc = domNode.pmViewDesc; + if (desc) + for (let i = this.index; i < this.top.children.length; i++) { + if (this.top.children[i] == desc) + return i; + } + return -1; + } + domNode = parent; + } + } + // Try to update the next node, if any, to the given data. Checks + // pre-matches to avoid overwriting nodes that could still be used. + updateNextNode(node, outerDeco, innerDeco, view, index, pos) { + for (let i = this.index; i < this.top.children.length; i++) { + let next = this.top.children[i]; + if (next instanceof NodeViewDesc) { + let preMatch2 = this.preMatch.matched.get(next); + if (preMatch2 != null && preMatch2 != index) + return false; + let nextDOM = next.dom, updated; + let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco)); + if (!locked && next.update(node, outerDeco, innerDeco, view)) { + this.destroyBetween(this.index, i); + if (next.dom != nextDOM) + this.changed = true; + this.index++; + return true; + } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) { + this.destroyBetween(this.index, i); + this.top.children[this.index] = updated; + if (updated.contentDOM) { + updated.dirty = CONTENT_DIRTY; + updated.updateChildren(view, pos + 1); + updated.dirty = NOT_DIRTY; + } + this.changed = true; + this.index++; + return true; + } + break; + } + } + return false; + } + // When a node with content is replaced by a different node with + // identical content, move over its children. + recreateWrapper(next, node, outerDeco, innerDeco, view, pos) { + if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco)) + return null; + let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); + if (wrapper.contentDOM) { + wrapper.children = next.children; + next.children = []; + for (let ch of wrapper.children) + ch.parent = wrapper; + } + next.destroy(); + return wrapper; + } + // Insert the node as a newly created node desc. + addNode(node, outerDeco, innerDeco, view, pos) { + let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); + if (desc.contentDOM) + desc.updateChildren(view, pos + 1); + this.top.children.splice(this.index++, 0, desc); + this.changed = true; + } + placeWidget(widget, view, pos) { + let next = this.index < this.top.children.length ? this.top.children[this.index] : null; + if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) { + this.index++; + } else { + let desc = new WidgetViewDesc(this.top, widget, view, pos); + this.top.children.splice(this.index++, 0, desc); + this.changed = true; + } + } + // Make sure a textblock looks and behaves correctly in + // contentEditable. + addTextblockHacks() { + let lastChild = this.top.children[this.index - 1], parent = this.top; + while (lastChild instanceof MarkViewDesc) { + parent = lastChild; + lastChild = parent.children[parent.children.length - 1]; + } + if (!lastChild || // Empty textblock + !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) { + if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false") + this.addHackNode("IMG", parent); + this.addHackNode("BR", this.top); + } + } + addHackNode(nodeName, parent) { + if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) { + this.index++; + } else { + let dom = document.createElement(nodeName); + if (nodeName == "IMG") { + dom.className = "ProseMirror-separator"; + dom.alt = ""; + } + if (nodeName == "BR") + dom.className = "ProseMirror-trailingBreak"; + let hack = new TrailingHackViewDesc(this.top, [], dom, null); + if (parent != this.top) + parent.children.push(hack); + else + parent.children.splice(this.index++, 0, hack); + this.changed = true; + } + } + isLocked(node) { + return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode)); + } +}; +function preMatch(frag, parentDesc) { + let curDesc = parentDesc, descI = curDesc.children.length; + let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches2 = []; + outer: while (fI > 0) { + let desc; + for (; ; ) { + if (descI) { + let next = curDesc.children[descI - 1]; + if (next instanceof MarkViewDesc) { + curDesc = next; + descI = next.children.length; + } else { + desc = next; + descI--; + break; + } + } else if (curDesc == parentDesc) { + break outer; + } else { + descI = curDesc.parent.children.indexOf(curDesc); + curDesc = curDesc.parent; + } + } + let node = desc.node; + if (!node) + continue; + if (node != frag.child(fI - 1)) + break; + --fI; + matched.set(desc, fI); + matches2.push(desc); + } + return { index: fI, matched, matches: matches2.reverse() }; +} +function compareSide(a, b) { + return a.type.side - b.type.side; +} +function iterDeco(parent, deco, onWidget, onNode) { + let locals = deco.locals(parent), offset = 0; + if (locals.length == 0) { + for (let i = 0; i < parent.childCount; i++) { + let child = parent.child(i); + onNode(child, locals, deco.forChild(offset, child), i); + offset += child.nodeSize; + } + return; + } + let decoIndex = 0, active = [], restNode = null; + for (let parentIndex = 0; ; ) { + let widget, widgets; + while (decoIndex < locals.length && locals[decoIndex].to == offset) { + let next = locals[decoIndex++]; + if (next.widget) { + if (!widget) + widget = next; + else + (widgets || (widgets = [widget])).push(next); + } + } + if (widget) { + if (widgets) { + widgets.sort(compareSide); + for (let i = 0; i < widgets.length; i++) + onWidget(widgets[i], parentIndex, !!restNode); + } else { + onWidget(widget, parentIndex, !!restNode); + } + } + let child, index; + if (restNode) { + index = -1; + child = restNode; + restNode = null; + } else if (parentIndex < parent.childCount) { + index = parentIndex; + child = parent.child(parentIndex++); + } else { + break; + } + for (let i = 0; i < active.length; i++) + if (active[i].to <= offset) + active.splice(i--, 1); + while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset) + active.push(locals[decoIndex++]); + let end = offset + child.nodeSize; + if (child.isText) { + let cutAt = end; + if (decoIndex < locals.length && locals[decoIndex].from < cutAt) + cutAt = locals[decoIndex].from; + for (let i = 0; i < active.length; i++) + if (active[i].to < cutAt) + cutAt = active[i].to; + if (cutAt < end) { + restNode = child.cut(cutAt - offset); + child = child.cut(0, cutAt - offset); + end = cutAt; + index = -1; + } + } else { + while (decoIndex < locals.length && locals[decoIndex].to < end) + decoIndex++; + } + let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice(); + onNode(child, outerDeco, deco.forChild(offset, child), index); + offset = end; + } +} +function iosHacks(dom) { + if (dom.nodeName == "UL" || dom.nodeName == "OL") { + let oldCSS = dom.style.cssText; + dom.style.cssText = oldCSS + "; list-style: square !important"; + window.getComputedStyle(dom).listStyle; + dom.style.cssText = oldCSS; + } +} +function findTextInFragment(frag, text, from, to) { + for (let i = 0, pos = 0; i < frag.childCount && pos <= to; ) { + let child = frag.child(i++), childStart = pos; + pos += child.nodeSize; + if (!child.isText) + continue; + let str = child.text; + while (i < frag.childCount) { + let next = frag.child(i++); + pos += next.nodeSize; + if (!next.isText) + break; + str += next.text; + } + if (pos >= from) { + if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text) + return to - text.length; + let found2 = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1; + if (found2 >= 0 && found2 + text.length + childStart >= from) + return childStart + found2; + if (from == to && str.length >= to + text.length - childStart && str.slice(to - childStart, to - childStart + text.length) == text) + return to; + } + } + return -1; +} +function replaceNodes(nodes, from, to, view, replacement) { + let result = []; + for (let i = 0, off = 0; i < nodes.length; i++) { + let child = nodes[i], start = off, end = off += child.size; + if (start >= to || end <= from) { + result.push(child); + } else { + if (start < from) + result.push(child.slice(0, from - start, view)); + if (replacement) { + result.push(replacement); + replacement = void 0; + } + if (end > to) + result.push(child.slice(to - start, child.size, view)); + } + } + return result; +} +function selectionFromDOM(view, origin = null) { + let domSel = view.domSelectionRange(), doc3 = view.state.doc; + if (!domSel.focusNode) + return null; + let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; + let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1); + if (head < 0) + return null; + let $head = doc3.resolve(head), anchor, selection; + if (selectionCollapsed(domSel)) { + anchor = head; + while (nearestDesc && !nearestDesc.node) + nearestDesc = nearestDesc.parent; + let nearestDescNode = nearestDesc.node; + if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) { + let pos = nearestDesc.posBefore; + selection = new NodeSelection(head == pos ? $head : doc3.resolve(pos)); + } + } else { + if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) { + let min = head, max = head; + for (let i = 0; i < domSel.rangeCount; i++) { + let range = domSel.getRangeAt(i); + min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1)); + max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1)); + } + if (min < 0) + return null; + [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max]; + $head = doc3.resolve(head); + } else { + anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1); + } + if (anchor < 0) + return null; + } + let $anchor = doc3.resolve(anchor); + if (!selection) { + let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1; + selection = selectionBetween(view, $anchor, $head, bias); + } + return selection; +} +function editorOwnsSelection(view) { + return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom); +} +function selectionToDOM(view, force = false) { + let sel = view.state.selection; + syncNodeSelection(view, sel); + if (!editorOwnsSelection(view)) + return; + if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) { + let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection; + if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) { + view.input.mouseDown.delayedSelectionSync = true; + view.domObserver.setCurSelection(); + return; + } + } + view.domObserver.disconnectSelection(); + if (view.cursorWrapper) { + selectCursorWrapper(view); + } else { + let { anchor, head } = sel, resetEditableFrom, resetEditableTo; + if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) { + if (!sel.$from.parent.inlineContent) + resetEditableFrom = temporarilyEditableNear(view, sel.from); + if (!sel.empty && !sel.$from.parent.inlineContent) + resetEditableTo = temporarilyEditableNear(view, sel.to); + } + view.docView.setSelection(anchor, head, view, force); + if (brokenSelectBetweenUneditable) { + if (resetEditableFrom) + resetEditable(resetEditableFrom); + if (resetEditableTo) + resetEditable(resetEditableTo); + } + if (sel.visible) { + view.dom.classList.remove("ProseMirror-hideselection"); + } else { + view.dom.classList.add("ProseMirror-hideselection"); + if ("onselectionchange" in document) + removeClassOnSelectionChange(view); + } + } + view.domObserver.setCurSelection(); + view.domObserver.connectSelection(); +} +var brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63; +function temporarilyEditableNear(view, pos) { + let { node, offset } = view.docView.domFromPos(pos, 0); + let after = offset < node.childNodes.length ? node.childNodes[offset] : null; + let before = offset ? node.childNodes[offset - 1] : null; + if (safari && after && after.contentEditable == "false") + return setEditable(after); + if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) { + if (after) + return setEditable(after); + else if (before) + return setEditable(before); + } +} +function setEditable(element) { + element.contentEditable = "true"; + if (safari && element.draggable) { + element.draggable = false; + element.wasDraggable = true; + } + return element; +} +function resetEditable(element) { + element.contentEditable = "false"; + if (element.wasDraggable) { + element.draggable = true; + element.wasDraggable = null; + } +} +function removeClassOnSelectionChange(view) { + let doc3 = view.dom.ownerDocument; + doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard); + let domSel = view.domSelectionRange(); + let node = domSel.anchorNode, offset = domSel.anchorOffset; + doc3.addEventListener("selectionchange", view.input.hideSelectionGuard = () => { + if (domSel.anchorNode != node || domSel.anchorOffset != offset) { + doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard); + setTimeout(() => { + if (!editorOwnsSelection(view) || view.state.selection.visible) + view.dom.classList.remove("ProseMirror-hideselection"); + }, 20); + } + }); +} +function selectCursorWrapper(view) { + let domSel = view.domSelection(); + if (!domSel) + return; + let node = view.cursorWrapper.dom, img = node.nodeName == "IMG"; + if (img) + domSel.collapse(node.parentNode, domIndex(node) + 1); + else + domSel.collapse(node, 0); + if (!img && !view.state.selection.visible && ie && ie_version <= 11) { + node.disabled = true; + node.disabled = false; + } +} +function syncNodeSelection(view, sel) { + if (sel instanceof NodeSelection) { + let desc = view.docView.descAt(sel.from); + if (desc != view.lastSelectedViewDesc) { + clearNodeSelection(view); + if (desc) + desc.selectNode(); + view.lastSelectedViewDesc = desc; + } + } else { + clearNodeSelection(view); + } +} +function clearNodeSelection(view) { + if (view.lastSelectedViewDesc) { + if (view.lastSelectedViewDesc.parent) + view.lastSelectedViewDesc.deselectNode(); + view.lastSelectedViewDesc = void 0; + } +} +function selectionBetween(view, $anchor, $head, bias) { + return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias); +} +function hasFocusAndSelection(view) { + if (view.editable && !view.hasFocus()) + return false; + return hasSelection(view); +} +function hasSelection(view) { + let sel = view.domSelectionRange(); + if (!sel.anchorNode) + return false; + try { + return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode)); + } catch (_) { + return false; + } +} +function anchorInRightPlace(view) { + let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0); + let domSel = view.domSelectionRange(); + return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset); +} +function moveSelectionBlock(state, dir) { + let { $anchor, $head } = state.selection; + let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head); + let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null; + return $start && Selection.findFrom($start, dir); +} +function apply(view, sel) { + view.dispatch(view.state.tr.setSelection(sel).scrollIntoView()); + return true; +} +function selectHorizontally(view, dir, mods) { + let sel = view.state.selection; + if (sel instanceof TextSelection) { + if (mods.indexOf("s") > -1) { + let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter; + if (!node || node.isText || !node.isLeaf) + return false; + let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1)); + return apply(view, new TextSelection(sel.$anchor, $newHead)); + } else if (!sel.empty) { + return false; + } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) { + let next = moveSelectionBlock(view.state, dir); + if (next && next instanceof NodeSelection) + return apply(view, next); + return false; + } else if (!(mac2 && mods.indexOf("m") > -1)) { + let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; + if (!node || node.isText) + return false; + let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos; + if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) + return false; + if (NodeSelection.isSelectable(node)) { + return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head)); + } else if (webkit) { + return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize))); + } else { + return false; + } + } + } else if (sel instanceof NodeSelection && sel.node.isInline) { + return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from)); + } else { + let next = moveSelectionBlock(view.state, dir); + if (next) + return apply(view, next); + return false; + } +} +function nodeLen(node) { + return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; +} +function isIgnorable(dom, dir) { + let desc = dom.pmViewDesc; + return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR"); +} +function skipIgnoredNodes(view, dir) { + return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view); +} +function skipIgnoredNodesBefore(view) { + let sel = view.domSelectionRange(); + let node = sel.focusNode, offset = sel.focusOffset; + if (!node) + return; + let moveNode, moveOffset, force = false; + if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1)) + force = true; + for (; ; ) { + if (offset > 0) { + if (node.nodeType != 1) { + break; + } else { + let before = node.childNodes[offset - 1]; + if (isIgnorable(before, -1)) { + moveNode = node; + moveOffset = --offset; + } else if (before.nodeType == 3) { + node = before; + offset = node.nodeValue.length; + } else + break; + } + } else if (isBlockNode(node)) { + break; + } else { + let prev = node.previousSibling; + while (prev && isIgnorable(prev, -1)) { + moveNode = node.parentNode; + moveOffset = domIndex(prev); + prev = prev.previousSibling; + } + if (!prev) { + node = node.parentNode; + if (node == view.dom) + break; + offset = 0; + } else { + node = prev; + offset = nodeLen(node); + } + } + } + if (force) + setSelFocus(view, node, offset); + else if (moveNode) + setSelFocus(view, moveNode, moveOffset); +} +function skipIgnoredNodesAfter(view) { + let sel = view.domSelectionRange(); + let node = sel.focusNode, offset = sel.focusOffset; + if (!node) + return; + let len = nodeLen(node); + let moveNode, moveOffset; + for (; ; ) { + if (offset < len) { + if (node.nodeType != 1) + break; + let after = node.childNodes[offset]; + if (isIgnorable(after, 1)) { + moveNode = node; + moveOffset = ++offset; + } else + break; + } else if (isBlockNode(node)) { + break; + } else { + let next = node.nextSibling; + while (next && isIgnorable(next, 1)) { + moveNode = next.parentNode; + moveOffset = domIndex(next) + 1; + next = next.nextSibling; + } + if (!next) { + node = node.parentNode; + if (node == view.dom) + break; + offset = len = 0; + } else { + node = next; + offset = 0; + len = nodeLen(node); + } + } + } + if (moveNode) + setSelFocus(view, moveNode, moveOffset); +} +function isBlockNode(dom) { + let desc = dom.pmViewDesc; + return desc && desc.node && desc.node.isBlock; +} +function textNodeAfter(node, offset) { + while (node && offset == node.childNodes.length && !hasBlockDesc(node)) { + offset = domIndex(node) + 1; + node = node.parentNode; + } + while (node && offset < node.childNodes.length) { + let next = node.childNodes[offset]; + if (next.nodeType == 3) + return next; + if (next.nodeType == 1 && next.contentEditable == "false") + break; + node = next; + offset = 0; + } +} +function textNodeBefore(node, offset) { + while (node && !offset && !hasBlockDesc(node)) { + offset = domIndex(node); + node = node.parentNode; + } + while (node && offset) { + let next = node.childNodes[offset - 1]; + if (next.nodeType == 3) + return next; + if (next.nodeType == 1 && next.contentEditable == "false") + break; + node = next; + offset = node.childNodes.length; + } +} +function setSelFocus(view, node, offset) { + if (node.nodeType != 3) { + let before, after; + if (after = textNodeAfter(node, offset)) { + node = after; + offset = 0; + } else if (before = textNodeBefore(node, offset)) { + node = before; + offset = before.nodeValue.length; + } + } + let sel = view.domSelection(); + if (!sel) + return; + if (selectionCollapsed(sel)) { + let range = document.createRange(); + range.setEnd(node, offset); + range.setStart(node, offset); + sel.removeAllRanges(); + sel.addRange(range); + } else if (sel.extend) { + sel.extend(node, offset); + } + view.domObserver.setCurSelection(); + let { state } = view; + setTimeout(() => { + if (view.state == state) + selectionToDOM(view); + }, 50); +} +function findDirection(view, pos) { + let $pos = view.state.doc.resolve(pos); + if (!(chrome || windows) && $pos.parent.inlineContent) { + let coords = view.coordsAtPos(pos); + if (pos > $pos.start()) { + let before = view.coordsAtPos(pos - 1); + let mid = (before.top + before.bottom) / 2; + if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1) + return before.left < coords.left ? "ltr" : "rtl"; + } + if (pos < $pos.end()) { + let after = view.coordsAtPos(pos + 1); + let mid = (after.top + after.bottom) / 2; + if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1) + return after.left > coords.left ? "ltr" : "rtl"; + } + } + let computed = getComputedStyle(view.dom).direction; + return computed == "rtl" ? "rtl" : "ltr"; +} +function selectVertically(view, dir, mods) { + let sel = view.state.selection; + if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) + return false; + if (mac2 && mods.indexOf("m") > -1) + return false; + let { $from, $to } = sel; + if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { + let next = moveSelectionBlock(view.state, dir); + if (next && next instanceof NodeSelection) + return apply(view, next); + } + if (!$from.parent.inlineContent) { + let side = dir < 0 ? $from : $to; + let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir); + return beyond ? apply(view, beyond) : false; + } + return false; +} +function stopNativeHorizontalDelete(view, dir) { + if (!(view.state.selection instanceof TextSelection)) + return true; + let { $head, $anchor, empty: empty2 } = view.state.selection; + if (!$head.sameParent($anchor)) + return true; + if (!empty2) + return false; + if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) + return true; + let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter); + if (nextNode && !nextNode.isText) { + let tr = view.state.tr; + if (dir < 0) + tr.delete($head.pos - nextNode.nodeSize, $head.pos); + else + tr.delete($head.pos, $head.pos + nextNode.nodeSize); + view.dispatch(tr); + return true; + } + return false; +} +function switchEditable(view, node, state) { + view.domObserver.stop(); + node.contentEditable = state; + view.domObserver.start(); +} +function safariDownArrowBug(view) { + if (!safari || view.state.selection.$head.parentOffset > 0) + return false; + let { focusNode, focusOffset } = view.domSelectionRange(); + if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") { + let child = focusNode.firstChild; + switchEditable(view, child, "true"); + setTimeout(() => switchEditable(view, child, "false"), 20); + } + return false; +} +function getMods(event) { + let result = ""; + if (event.ctrlKey) + result += "c"; + if (event.metaKey) + result += "m"; + if (event.altKey) + result += "a"; + if (event.shiftKey) + result += "s"; + return result; +} +function captureKeyDown(view, event) { + let code = event.keyCode, mods = getMods(event); + if (code == 8 || mac2 && code == 72 && mods == "c") { + return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1); + } else if (code == 46 && !event.shiftKey || mac2 && code == 68 && mods == "c") { + return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1); + } else if (code == 13 || code == 27) { + return true; + } else if (code == 37 || mac2 && code == 66 && mods == "c") { + let dir = code == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1; + return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); + } else if (code == 39 || mac2 && code == 70 && mods == "c") { + let dir = code == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1; + return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); + } else if (code == 38 || mac2 && code == 80 && mods == "c") { + return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1); + } else if (code == 40 || mac2 && code == 78 && mods == "c") { + return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1); + } else if (mods == (mac2 ? "m" : "c") && (code == 66 || code == 73 || code == 89 || code == 90)) { + return true; + } + return false; +} +function serializeForClipboard(view, slice) { + view.someProp("transformCopied", (f) => { + slice = f(slice, view); + }); + let context = [], { content, openStart, openEnd } = slice; + while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) { + openStart--; + openEnd--; + let node = content.firstChild; + context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null); + content = node.content; + } + let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); + let doc3 = detachedDoc(), wrap2 = doc3.createElement("div"); + wrap2.appendChild(serializer.serializeFragment(content, { document: doc3 })); + let firstChild = wrap2.firstChild, needsWrap, wrappers = 0; + while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { + for (let i = needsWrap.length - 1; i >= 0; i--) { + let wrapper = doc3.createElement(needsWrap[i]); + while (wrap2.firstChild) + wrapper.appendChild(wrap2.firstChild); + wrap2.appendChild(wrapper); + wrappers++; + } + firstChild = wrap2.firstChild; + } + if (firstChild && firstChild.nodeType == 1) + firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`); + let text = view.someProp("clipboardTextSerializer", (f) => f(slice, view)) || slice.content.textBetween(0, slice.content.size, "\n\n"); + return { dom: wrap2, text, slice }; +} +function parseFromClipboard(view, text, html, plainText, $context) { + let inCode = $context.parent.type.spec.code; + let dom, slice; + if (!html && !text) + return null; + let asText = !!text && (plainText || inCode || !html); + if (asText) { + view.someProp("transformPastedText", (f) => { + text = f(text, inCode || plainText, view); + }); + if (inCode) { + slice = new Slice(Fragment.from(view.state.schema.text(text.replace(/\r\n?/g, "\n"))), 0, 0); + view.someProp("transformPasted", (f) => { + slice = f(slice, view, true); + }); + return slice; + } + let parsed = view.someProp("clipboardTextParser", (f) => f(text, $context, plainText, view)); + if (parsed) { + slice = parsed; + } else { + let marks = $context.marks(); + let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema); + dom = document.createElement("div"); + text.split(/(?:\r\n?|\n)+/).forEach((block) => { + let p = dom.appendChild(document.createElement("p")); + if (block) + p.appendChild(serializer.serializeNode(schema.text(block, marks))); + }); + } + } else { + view.someProp("transformPastedHTML", (f) => { + html = f(html, view); + }); + dom = readHTML(html); + if (webkit) + restoreReplacedSpaces(dom); + } + let contextNode = dom && dom.querySelector("[data-pm-slice]"); + let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || ""); + if (sliceData && sliceData[3]) + for (let i = +sliceData[3]; i > 0; i--) { + let child = dom.firstChild; + while (child && child.nodeType != 1) + child = child.nextSibling; + if (!child) + break; + dom = child; + } + if (!slice) { + let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema); + slice = parser.parseSlice(dom, { + preserveWhitespace: !!(asText || sliceData), + context: $context, + ruleFromNode(dom2) { + if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName)) + return { ignore: true }; + return null; + } + }); + } + if (sliceData) { + slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]); + } else { + slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true); + if (slice.openStart || slice.openEnd) { + let openStart = 0, openEnd = 0; + for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { + } + for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { + } + slice = closeSlice(slice, openStart, openEnd); + } + } + view.someProp("transformPasted", (f) => { + slice = f(slice, view, asText); + }); + return slice; +} +var inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i; +function normalizeSiblings(fragment, $context) { + if (fragment.childCount < 2) + return fragment; + for (let d = $context.depth; d >= 0; d--) { + let parent = $context.node(d); + let match = parent.contentMatchAt($context.index(d)); + let lastWrap, result = []; + fragment.forEach((node) => { + if (!result) + return; + let wrap2 = match.findWrapping(node.type), inLast; + if (!wrap2) + return result = null; + if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result[result.length - 1], 0)) { + result[result.length - 1] = inLast; + } else { + if (result.length) + result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); + let wrapped = withWrappers(node, wrap2); + result.push(wrapped); + match = match.matchType(wrapped.type); + lastWrap = wrap2; + } + }); + if (result) + return Fragment.from(result); + } + return fragment; +} +function withWrappers(node, wrap2, from = 0) { + for (let i = wrap2.length - 1; i >= from; i--) + node = wrap2[i].create(null, Fragment.from(node)); + return node; +} +function addToSibling(wrap2, lastWrap, node, sibling, depth) { + if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) { + let inner = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1); + if (inner) + return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)); + let match = sibling.contentMatchAt(sibling.childCount); + if (match.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1])) + return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1)))); + } +} +function closeRight(node, depth) { + if (depth == 0) + return node; + let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1)); + let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true); + return node.copy(fragment.append(fill)); +} +function closeRange(fragment, side, from, to, depth, openEnd) { + let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content; + if (fragment.childCount > 1) + openEnd = 0; + if (depth < to - 1) + inner = closeRange(inner, side, from, to, depth + 1, openEnd); + if (depth >= from) + inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); + return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner)); +} +function closeSlice(slice, openStart, openEnd) { + if (openStart < slice.openStart) + slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd); + if (openEnd < slice.openEnd) + slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd); + return slice; +} +var wrapMap = { + thead: ["table"], + tbody: ["table"], + tfoot: ["table"], + caption: ["table"], + colgroup: ["table"], + col: ["table", "colgroup"], + tr: ["table", "tbody"], + td: ["table", "tbody", "tr"], + th: ["table", "tbody", "tr"] +}; +var _detachedDoc = null; +function detachedDoc() { + return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title")); +} +var _policy = null; +function maybeWrapTrusted(html) { + let trustedTypes = window.trustedTypes; + if (!trustedTypes) + return html; + if (!_policy) + _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s }); + return _policy.createHTML(html); +} +function readHTML(html) { + let metas = /^(\s*]*>)*/.exec(html); + if (metas) + html = html.slice(metas[0].length); + let elt = detachedDoc().createElement("div"); + let firstTag = /<([a-z][^>\s]+)/i.exec(html), wrap2; + if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()]) + html = wrap2.map((n) => "<" + n + ">").join("") + html + wrap2.map((n) => "").reverse().join(""); + elt.innerHTML = maybeWrapTrusted(html); + if (wrap2) + for (let i = 0; i < wrap2.length; i++) + elt = elt.querySelector(wrap2[i]) || elt; + return elt; +} +function restoreReplacedSpaces(dom) { + let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space"); + for (let i = 0; i < nodes.length; i++) { + let node = nodes[i]; + if (node.childNodes.length == 1 && node.textContent == " " && node.parentNode) + node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node); + } +} +function addContext(slice, context) { + if (!slice.size) + return slice; + let schema = slice.content.firstChild.type.schema, array; + try { + array = JSON.parse(context); + } catch (e) { + return slice; + } + let { content, openStart, openEnd } = slice; + for (let i = array.length - 2; i >= 0; i -= 2) { + let type = schema.nodes[array[i]]; + if (!type || type.hasRequiredAttrs()) + break; + content = Fragment.from(type.create(array[i + 1], content)); + openStart++; + openEnd++; + } + return new Slice(content, openStart, openEnd); +} +var handlers = {}; +var editHandlers = {}; +var passiveHandlers = { touchstart: true, touchmove: true }; +var InputState = class { + constructor() { + this.shiftKey = false; + this.mouseDown = null; + this.lastKeyCode = null; + this.lastKeyCodeTime = 0; + this.lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 }; + this.lastSelectionOrigin = null; + this.lastSelectionTime = 0; + this.lastIOSEnter = 0; + this.lastIOSEnterFallbackTimeout = -1; + this.lastFocus = 0; + this.lastTouch = 0; + this.lastChromeDelete = 0; + this.composing = false; + this.compositionNode = null; + this.composingTimeout = -1; + this.compositionNodes = []; + this.compositionEndedAt = -2e8; + this.compositionID = 1; + this.badSafariComposition = false; + this.compositionPendingChanges = 0; + this.domChangeCount = 0; + this.eventHandlers = /* @__PURE__ */ Object.create(null); + this.hideSelectionGuard = null; + } +}; +function initInput(view) { + for (let event in handlers) { + let handler = handlers[event]; + view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => { + if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers))) + handler(view, event2); + }, passiveHandlers[event] ? { passive: true } : void 0); + } + if (safari) + view.dom.addEventListener("input", () => null); + ensureListeners(view); +} +function setSelectionOrigin(view, origin) { + view.input.lastSelectionOrigin = origin; + view.input.lastSelectionTime = Date.now(); +} +function destroyInput(view) { + view.domObserver.stop(); + for (let type in view.input.eventHandlers) + view.dom.removeEventListener(type, view.input.eventHandlers[type]); + clearTimeout(view.input.composingTimeout); + clearTimeout(view.input.lastIOSEnterFallbackTimeout); +} +function ensureListeners(view) { + view.someProp("handleDOMEvents", (currentHandlers) => { + for (let type in currentHandlers) + if (!view.input.eventHandlers[type]) + view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event)); + }); +} +function runCustomHandler(view, event) { + return view.someProp("handleDOMEvents", (handlers2) => { + let handler = handlers2[event.type]; + return handler ? handler(view, event) || event.defaultPrevented : false; + }); +} +function eventBelongsToView(view, event) { + if (!event.bubbles) + return true; + if (event.defaultPrevented) + return false; + for (let node = event.target; node != view.dom; node = node.parentNode) + if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event)) + return false; + return true; +} +function dispatchEvent(view, event) { + if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers))) + handlers[event.type](view, event); +} +editHandlers.keydown = (view, _event) => { + let event = _event; + view.input.shiftKey = event.keyCode == 16 || event.shiftKey; + if (inOrNearComposition(view, event)) + return; + view.input.lastKeyCode = event.keyCode; + view.input.lastKeyCodeTime = Date.now(); + if (android && chrome && event.keyCode == 13) + return; + if (event.keyCode != 229) + view.domObserver.forceFlush(); + if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) { + let now = Date.now(); + view.input.lastIOSEnter = now; + view.input.lastIOSEnterFallbackTimeout = setTimeout(() => { + if (view.input.lastIOSEnter == now) { + view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))); + view.input.lastIOSEnter = 0; + } + }, 200); + } else if (view.someProp("handleKeyDown", (f) => f(view, event)) || captureKeyDown(view, event)) { + event.preventDefault(); + } else { + setSelectionOrigin(view, "key"); + } +}; +editHandlers.keyup = (view, event) => { + if (event.keyCode == 16) + view.input.shiftKey = false; +}; +editHandlers.keypress = (view, _event) => { + let event = _event; + if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac2 && event.metaKey) + return; + if (view.someProp("handleKeyPress", (f) => f(view, event))) { + event.preventDefault(); + return; + } + let sel = view.state.selection; + if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { + let text = String.fromCharCode(event.charCode); + let deflt = () => view.state.tr.insertText(text).scrollIntoView(); + if (!/[\r\n]/.test(text) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text, deflt))) + view.dispatch(deflt()); + event.preventDefault(); + } +}; +function eventCoords(event) { + return { left: event.clientX, top: event.clientY }; +} +function isNear(event, click) { + let dx = click.x - event.clientX, dy = click.y - event.clientY; + return dx * dx + dy * dy < 100; +} +function runHandlerOnContext(view, propName, pos, inside, event) { + if (inside == -1) + return false; + let $pos = view.state.doc.resolve(inside); + for (let i = $pos.depth + 1; i > 0; i--) { + if (view.someProp(propName, (f) => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f(view, pos, $pos.node(i), $pos.before(i), event, false))) + return true; + } + return false; +} +function updateSelection(view, selection, origin) { + if (!view.focused) + view.focus(); + if (view.state.selection.eq(selection)) + return; + let tr = view.state.tr.setSelection(selection); + if (origin == "pointer") + tr.setMeta("pointer", true); + view.dispatch(tr); +} +function selectClickedLeaf(view, inside) { + if (inside == -1) + return false; + let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter; + if (node && node.isAtom && NodeSelection.isSelectable(node)) { + updateSelection(view, new NodeSelection($pos), "pointer"); + return true; + } + return false; +} +function selectClickedNode(view, inside) { + if (inside == -1) + return false; + let sel = view.state.selection, selectedNode, selectAt; + if (sel instanceof NodeSelection) + selectedNode = sel.node; + let $pos = view.state.doc.resolve(inside); + for (let i = $pos.depth + 1; i > 0; i--) { + let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + if (NodeSelection.isSelectable(node)) { + if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) + selectAt = $pos.before(sel.$from.depth); + else + selectAt = $pos.before(i); + break; + } + } + if (selectAt != null) { + updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer"); + return true; + } else { + return false; + } +} +function handleSingleClick(view, pos, inside, event, selectNode) { + return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside)); +} +function handleDoubleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event)); +} +function handleTripleClick(view, pos, inside, event) { + return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event); +} +function defaultTripleClick(view, inside, event) { + if (event.button != 0) + return false; + let doc3 = view.state.doc; + if (inside == -1) { + if (doc3.inlineContent) { + updateSelection(view, TextSelection.create(doc3, 0, doc3.content.size), "pointer"); + return true; + } + return false; + } + let $pos = doc3.resolve(inside); + for (let i = $pos.depth + 1; i > 0; i--) { + let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); + let nodePos = $pos.before(i); + if (node.inlineContent) + updateSelection(view, TextSelection.create(doc3, nodePos + 1, nodePos + 1 + node.content.size), "pointer"); + else if (NodeSelection.isSelectable(node)) + updateSelection(view, NodeSelection.create(doc3, nodePos), "pointer"); + else + continue; + return true; + } +} +function forceDOMFlush(view) { + return endComposition(view); +} +var selectNodeModifier = mac2 ? "metaKey" : "ctrlKey"; +handlers.mousedown = (view, _event) => { + let event = _event; + view.input.shiftKey = event.shiftKey; + let flushed = forceDOMFlush(view); + let now = Date.now(), type = "singleClick"; + if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) { + if (view.input.lastClick.type == "singleClick") + type = "doubleClick"; + else if (view.input.lastClick.type == "doubleClick") + type = "tripleClick"; + } + view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button }; + let pos = view.posAtCoords(eventCoords(event)); + if (!pos) + return; + if (type == "singleClick") { + if (view.input.mouseDown) + view.input.mouseDown.done(); + view.input.mouseDown = new MouseDown(view, pos, event, !!flushed); + } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) { + event.preventDefault(); + } else { + setSelectionOrigin(view, "pointer"); + } +}; +var MouseDown = class { + constructor(view, pos, event, flushed) { + this.view = view; + this.pos = pos; + this.event = event; + this.flushed = flushed; + this.delayedSelectionSync = false; + this.mightDrag = null; + this.startDoc = view.state.doc; + this.selectNode = !!event[selectNodeModifier]; + this.allowDefault = event.shiftKey; + let targetNode, targetPos; + if (pos.inside > -1) { + targetNode = view.state.doc.nodeAt(pos.inside); + targetPos = pos.inside; + } else { + let $pos = view.state.doc.resolve(pos.pos); + targetNode = $pos.parent; + targetPos = $pos.depth ? $pos.before() : 0; + } + const target = flushed ? null : event.target; + const targetDesc = target ? view.docView.nearestDesc(target, true) : null; + this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null; + let { selection } = view.state; + if (event.button == 0 && targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos) + this.mightDrag = { + node: targetNode, + pos: targetPos, + addAttr: !!(this.target && !this.target.draggable), + setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable")) + }; + if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) + this.target.draggable = true; + if (this.mightDrag.setUneditable) + setTimeout(() => { + if (this.view.input.mouseDown == this) + this.target.setAttribute("contentEditable", "false"); + }, 20); + this.view.domObserver.start(); + } + view.root.addEventListener("mouseup", this.up = this.up.bind(this)); + view.root.addEventListener("mousemove", this.move = this.move.bind(this)); + setSelectionOrigin(view, "pointer"); + } + done() { + this.view.root.removeEventListener("mouseup", this.up); + this.view.root.removeEventListener("mousemove", this.move); + if (this.mightDrag && this.target) { + this.view.domObserver.stop(); + if (this.mightDrag.addAttr) + this.target.removeAttribute("draggable"); + if (this.mightDrag.setUneditable) + this.target.removeAttribute("contentEditable"); + this.view.domObserver.start(); + } + if (this.delayedSelectionSync) + setTimeout(() => selectionToDOM(this.view)); + this.view.input.mouseDown = null; + } + up(event) { + this.done(); + if (!this.view.dom.contains(event.target)) + return; + let pos = this.pos; + if (this.view.state.doc != this.startDoc) + pos = this.view.posAtCoords(eventCoords(event)); + this.updateAllowDefault(event); + if (this.allowDefault || !pos) { + setSelectionOrigin(this.view, "pointer"); + } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) { + event.preventDefault(); + } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements + safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a + // cursor, but still report that the node is selected + // when asked through getSelection. You'll then get a + // situation where clicking at the point where that + // (hidden) cursor is doesn't change the selection, and + // thus doesn't get a reaction from ProseMirror. This + // works around that. + chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) { + updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer"); + event.preventDefault(); + } else { + setSelectionOrigin(this.view, "pointer"); + } + } + move(event) { + this.updateAllowDefault(event); + setSelectionOrigin(this.view, "pointer"); + if (event.buttons == 0) + this.done(); + } + updateAllowDefault(event) { + if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4)) + this.allowDefault = true; + } +}; +handlers.touchstart = (view) => { + view.input.lastTouch = Date.now(); + forceDOMFlush(view); + setSelectionOrigin(view, "pointer"); +}; +handlers.touchmove = (view) => { + view.input.lastTouch = Date.now(); + setSelectionOrigin(view, "pointer"); +}; +handlers.contextmenu = (view) => forceDOMFlush(view); +function inOrNearComposition(view, event) { + if (view.composing) + return true; + if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) { + view.input.compositionEndedAt = -2e8; + return true; + } + return false; +} +var timeoutComposition = android ? 5e3 : -1; +editHandlers.compositionstart = editHandlers.compositionupdate = (view) => { + if (!view.composing) { + view.domObserver.flush(); + let { state } = view, $pos = state.selection.$to; + if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows && selectionBeforeUneditable(view))) { + view.markCursor = view.state.storedMarks || $pos.marks(); + endComposition(view, true); + view.markCursor = null; + } else { + endComposition(view, !state.selection.empty); + if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) { + let sel = view.domSelectionRange(); + for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0; ) { + let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1]; + if (!before) + break; + if (before.nodeType == 3) { + let sel2 = view.domSelection(); + if (sel2) + sel2.collapse(before, before.nodeValue.length); + break; + } else { + node = before; + offset = -1; + } + } + } + } + view.input.composing = true; + } + scheduleComposeEnd(view, timeoutComposition); +}; +function selectionBeforeUneditable(view) { + let { focusNode, focusOffset } = view.domSelectionRange(); + if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length) + return false; + let next = focusNode.childNodes[focusOffset]; + return next.nodeType == 1 && next.contentEditable == "false"; +} +editHandlers.compositionend = (view, event) => { + if (view.composing) { + view.input.composing = false; + view.input.compositionEndedAt = event.timeStamp; + view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0; + view.input.compositionNode = null; + if (view.input.badSafariComposition) + view.domObserver.forceFlush(); + else if (view.input.compositionPendingChanges) + Promise.resolve().then(() => view.domObserver.flush()); + view.input.compositionID++; + scheduleComposeEnd(view, 20); + } +}; +function scheduleComposeEnd(view, delay) { + clearTimeout(view.input.composingTimeout); + if (delay > -1) + view.input.composingTimeout = setTimeout(() => endComposition(view), delay); +} +function clearComposition(view) { + if (view.composing) { + view.input.composing = false; + view.input.compositionEndedAt = timestampFromCustomEvent(); + } + while (view.input.compositionNodes.length > 0) + view.input.compositionNodes.pop().markParentsDirty(); +} +function findCompositionNode(view) { + let sel = view.domSelectionRange(); + if (!sel.focusNode) + return null; + let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset); + let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset); + if (textBefore && textAfter && textBefore != textAfter) { + let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode; + if (textBefore == lastChanged || textAfter == lastChanged) + return lastChanged; + if (!descAfter || !descAfter.isText(textAfter.nodeValue)) { + return textAfter; + } else if (view.input.compositionNode == textAfter) { + let descBefore = textBefore.pmViewDesc; + if (!(!descBefore || !descBefore.isText(textBefore.nodeValue))) + return textAfter; + } + } + return textBefore || textAfter; +} +function timestampFromCustomEvent() { + let event = document.createEvent("Event"); + event.initEvent("event", true, true); + return event.timeStamp; +} +function endComposition(view, restarting = false) { + if (android && view.domObserver.flushingSoon >= 0) + return; + view.domObserver.forceFlush(); + clearComposition(view); + if (restarting || view.docView && view.docView.dirty) { + let sel = selectionFromDOM(view), cur = view.state.selection; + if (sel && !sel.eq(cur)) + view.dispatch(view.state.tr.setSelection(sel)); + else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent) + view.dispatch(view.state.tr.deleteSelection()); + else + view.updateState(view.state); + return true; + } + return false; +} +function captureCopy(view, dom) { + if (!view.dom.parentNode) + return; + let wrap2 = view.dom.parentNode.appendChild(document.createElement("div")); + wrap2.appendChild(dom); + wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px"; + let sel = getSelection(), range = document.createRange(); + range.selectNodeContents(dom); + view.dom.blur(); + sel.removeAllRanges(); + sel.addRange(range); + setTimeout(() => { + if (wrap2.parentNode) + wrap2.parentNode.removeChild(wrap2); + view.focus(); + }, 50); +} +var brokenClipboardAPI = ie && ie_version < 15 || ios && webkit_version < 604; +handlers.copy = editHandlers.cut = (view, _event) => { + let event = _event; + let sel = view.state.selection, cut2 = event.type == "cut"; + if (sel.empty) + return; + let data = brokenClipboardAPI ? null : event.clipboardData; + let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice); + if (data) { + event.preventDefault(); + data.clearData(); + data.setData("text/html", dom.innerHTML); + data.setData("text/plain", text); + } else { + captureCopy(view, dom); + } + if (cut2) + view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut")); +}; +function sliceSingleNode(slice) { + return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null; +} +function capturePaste(view, event) { + if (!view.dom.parentNode) + return; + let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code; + let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div")); + if (!plainText) + target.contentEditable = "true"; + target.style.cssText = "position: fixed; left: -10000px; top: 10px"; + target.focus(); + let plain = view.input.shiftKey && view.input.lastKeyCode != 45; + setTimeout(() => { + view.focus(); + if (target.parentNode) + target.parentNode.removeChild(target); + if (plainText) + doPaste(view, target.value, null, plain, event); + else + doPaste(view, target.textContent, target.innerHTML, plain, event); + }, 50); +} +function doPaste(view, text, html, preferPlain, event) { + let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from); + if (view.someProp("handlePaste", (f) => f(view, event, slice || Slice.empty))) + return true; + if (!slice) + return false; + let singleNode = sliceSingleNode(slice); + let tr = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice); + view.dispatch(tr.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); + return true; +} +function getText(clipboardData) { + let text = clipboardData.getData("text/plain") || clipboardData.getData("Text"); + if (text) + return text; + let uris = clipboardData.getData("text/uri-list"); + return uris ? uris.replace(/\r?\n/g, " ") : ""; +} +editHandlers.paste = (view, _event) => { + let event = _event; + if (view.composing && !android) + return; + let data = brokenClipboardAPI ? null : event.clipboardData; + let plain = view.input.shiftKey && view.input.lastKeyCode != 45; + if (data && doPaste(view, getText(data), data.getData("text/html"), plain, event)) + event.preventDefault(); + else + capturePaste(view, event); +}; +var Dragging = class { + constructor(slice, move, node) { + this.slice = slice; + this.move = move; + this.node = node; + } +}; +var dragCopyModifier = mac2 ? "altKey" : "ctrlKey"; +function dragMoves(view, event) { + let moves = view.someProp("dragCopies", (test) => !test(event)); + return moves != null ? moves : !event[dragCopyModifier]; +} +handlers.dragstart = (view, _event) => { + let event = _event; + let mouseDown = view.input.mouseDown; + if (mouseDown) + mouseDown.done(); + if (!event.dataTransfer) + return; + let sel = view.state.selection; + let pos = sel.empty ? null : view.posAtCoords(eventCoords(event)); + let node; + if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ; + else if (mouseDown && mouseDown.mightDrag) { + node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos); + } else if (event.target && event.target.nodeType == 1) { + let desc = view.docView.nearestDesc(event.target, true); + if (desc && desc.node.type.spec.draggable && desc != view.docView) + node = NodeSelection.create(view.state.doc, desc.posBefore); + } + let draggedSlice = (node || view.state.selection).content(); + let { dom, text, slice } = serializeForClipboard(view, draggedSlice); + if (!event.dataTransfer.files.length || !chrome || chrome_version > 120) + event.dataTransfer.clearData(); + event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML); + event.dataTransfer.effectAllowed = "copyMove"; + if (!brokenClipboardAPI) + event.dataTransfer.setData("text/plain", text); + view.dragging = new Dragging(slice, dragMoves(view, event), node); +}; +handlers.dragend = (view) => { + let dragging = view.dragging; + window.setTimeout(() => { + if (view.dragging == dragging) + view.dragging = null; + }, 50); +}; +editHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault(); +editHandlers.drop = (view, event) => { + try { + handleDrop(view, event, view.dragging); + } finally { + view.dragging = null; + } +}; +function handleDrop(view, event, dragging) { + if (!event.dataTransfer) + return; + let eventPos = view.posAtCoords(eventCoords(event)); + if (!eventPos) + return; + let $mouse = view.state.doc.resolve(eventPos.pos); + let slice = dragging && dragging.slice; + if (slice) { + view.someProp("transformPasted", (f) => { + slice = f(slice, view, false); + }); + } else { + slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse); + } + let move = !!(dragging && dragMoves(view, event)); + if (view.someProp("handleDrop", (f) => f(view, event, slice || Slice.empty, move))) { + event.preventDefault(); + return; + } + if (!slice) + return; + event.preventDefault(); + let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos; + if (insertPos == null) + insertPos = $mouse.pos; + let tr = view.state.tr; + if (move) { + let { node } = dragging; + if (node) + node.replace(tr); + else + tr.deleteSelection(); + } + let pos = tr.mapping.map(insertPos); + let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1; + let beforeInsert = tr.doc; + if (isNode) + tr.replaceRangeWith(pos, pos, slice.content.firstChild); + else + tr.replaceRange(pos, pos, slice); + if (tr.doc.eq(beforeInsert)) + return; + let $pos = tr.doc.resolve(pos); + if (isNode && NodeSelection.isSelectable(slice.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) { + tr.setSelection(new NodeSelection($pos)); + } else { + let end = tr.mapping.map(insertPos); + tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo); + tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end))); + } + view.focus(); + view.dispatch(tr.setMeta("uiEvent", "drop")); +} +handlers.focus = (view) => { + view.input.lastFocus = Date.now(); + if (!view.focused) { + view.domObserver.stop(); + view.dom.classList.add("ProseMirror-focused"); + view.domObserver.start(); + view.focused = true; + setTimeout(() => { + if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange())) + selectionToDOM(view); + }, 20); + } +}; +handlers.blur = (view, _event) => { + let event = _event; + if (view.focused) { + view.domObserver.stop(); + view.dom.classList.remove("ProseMirror-focused"); + view.domObserver.start(); + if (event.relatedTarget && view.dom.contains(event.relatedTarget)) + view.domObserver.currentSelection.clear(); + view.focused = false; + } +}; +handlers.beforeinput = (view, _event) => { + let event = _event; + if (chrome && android && event.inputType == "deleteContentBackward") { + view.domObserver.flushSoon(); + let { domChangeCount } = view.input; + setTimeout(() => { + if (view.input.domChangeCount != domChangeCount) + return; + view.dom.blur(); + view.focus(); + if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) + return; + let { $cursor } = view.state.selection; + if ($cursor && $cursor.pos > 0) + view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); + }, 50); + } +}; +for (let prop in editHandlers) + handlers[prop] = editHandlers[prop]; +function compareObjs(a, b) { + if (a == b) + return true; + for (let p in a) + if (a[p] !== b[p]) + return false; + for (let p in b) + if (!(p in a)) + return false; + return true; +} +var WidgetType = class _WidgetType { + constructor(toDOM, spec) { + this.toDOM = toDOM; + this.spec = spec || noSpec; + this.side = this.spec.side || 0; + } + map(mapping, span, offset, oldOffset) { + let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); + return deleted ? null : new Decoration(pos - offset, pos - offset, this); + } + valid() { + return true; + } + eq(other) { + return this == other || other instanceof _WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)); + } + destroy(node) { + if (this.spec.destroy) + this.spec.destroy(node); + } +}; +var InlineType = class _InlineType { + constructor(attrs, spec) { + this.attrs = attrs; + this.spec = spec || noSpec; + } + map(mapping, span, offset, oldOffset) { + let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset; + let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset; + return from >= to ? null : new Decoration(from, to, this); + } + valid(_, span) { + return span.from < span.to; + } + eq(other) { + return this == other || other instanceof _InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); + } + static is(span) { + return span.type instanceof _InlineType; + } + destroy() { + } +}; +var NodeType2 = class _NodeType { + constructor(attrs, spec) { + this.attrs = attrs; + this.spec = spec || noSpec; + } + map(mapping, span, offset, oldOffset) { + let from = mapping.mapResult(span.from + oldOffset, 1); + if (from.deleted) + return null; + let to = mapping.mapResult(span.to + oldOffset, -1); + if (to.deleted || to.pos <= from.pos) + return null; + return new Decoration(from.pos - offset, to.pos - offset, this); + } + valid(node, span) { + let { index, offset } = node.content.findIndex(span.from), child; + return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to; + } + eq(other) { + return this == other || other instanceof _NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); + } + destroy() { + } +}; +var Decoration = class _Decoration { + /** + @internal + */ + constructor(from, to, type) { + this.from = from; + this.to = to; + this.type = type; + } + /** + @internal + */ + copy(from, to) { + return new _Decoration(from, to, this.type); + } + /** + @internal + */ + eq(other, offset = 0) { + return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to; + } + /** + @internal + */ + map(mapping, offset, oldOffset) { + return this.type.map(mapping, this, offset, oldOffset); + } + /** + Creates a widget decoration, which is a DOM node that's shown in + the document at the given position. It is recommended that you + delay rendering the widget by passing a function that will be + called when the widget is actually drawn in a view, but you can + also directly pass a DOM node. `getPos` can be used to find the + widget's current document position. + */ + static widget(pos, toDOM, spec) { + return new _Decoration(pos, pos, new WidgetType(toDOM, spec)); + } + /** + Creates an inline decoration, which adds the given attributes to + each inline node between `from` and `to`. + */ + static inline(from, to, attrs, spec) { + return new _Decoration(from, to, new InlineType(attrs, spec)); + } + /** + Creates a node decoration. `from` and `to` should point precisely + before and after a node in the document. That node, and only that + node, will receive the given attributes. + */ + static node(from, to, attrs, spec) { + return new _Decoration(from, to, new NodeType2(attrs, spec)); + } + /** + The spec provided when creating this decoration. Can be useful + if you've stored extra information in that object. + */ + get spec() { + return this.type.spec; + } + /** + @internal + */ + get inline() { + return this.type instanceof InlineType; + } + /** + @internal + */ + get widget() { + return this.type instanceof WidgetType; + } +}; +var none = []; +var noSpec = {}; +var DecorationSet = class _DecorationSet { + /** + @internal + */ + constructor(local, children) { + this.local = local.length ? local : none; + this.children = children.length ? children : none; + } + /** + Create a set of decorations, using the structure of the given + document. This will consume (modify) the `decorations` array, so + you must make a copy if you want need to preserve that. + */ + static create(doc3, decorations) { + return decorations.length ? buildTree(decorations, doc3, 0, noSpec) : empty; + } + /** + Find all decorations in this set which touch the given range + (including decorations that start or end directly at the + boundaries) and match the given predicate on their spec. When + `start` and `end` are omitted, all decorations in the set are + considered. When `predicate` isn't given, all decorations are + assumed to match. + */ + find(start, end, predicate) { + let result = []; + this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate); + return result; + } + findInner(start, end, result, offset, predicate) { + for (let i = 0; i < this.local.length; i++) { + let span = this.local[i]; + if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) + result.push(span.copy(span.from + offset, span.to + offset)); + } + for (let i = 0; i < this.children.length; i += 3) { + if (this.children[i] < end && this.children[i + 1] > start) { + let childOff = this.children[i] + 1; + this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate); + } + } + } + /** + Map the set of decorations in response to a change in the + document. + */ + map(mapping, doc3, options) { + if (this == empty || mapping.maps.length == 0) + return this; + return this.mapInner(mapping, doc3, 0, 0, options || noSpec); + } + /** + @internal + */ + mapInner(mapping, node, offset, oldOffset, options) { + let newLocal; + for (let i = 0; i < this.local.length; i++) { + let mapped = this.local[i].map(mapping, offset, oldOffset); + if (mapped && mapped.type.valid(node, mapped)) + (newLocal || (newLocal = [])).push(mapped); + else if (options.onRemove) + options.onRemove(this.local[i].spec); + } + if (this.children.length) + return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options); + else + return newLocal ? new _DecorationSet(newLocal.sort(byPos), none) : empty; + } + /** + Add the given array of decorations to the ones in the set, + producing a new set. Consumes the `decorations` array. Needs + access to the current document to create the appropriate tree + structure. + */ + add(doc3, decorations) { + if (!decorations.length) + return this; + if (this == empty) + return _DecorationSet.create(doc3, decorations); + return this.addInner(doc3, decorations, 0); + } + addInner(doc3, decorations, offset) { + let children, childIndex = 0; + doc3.forEach((childNode, childOffset) => { + let baseOffset = childOffset + offset, found2; + if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset))) + return; + if (!children) + children = this.children.slice(); + while (childIndex < children.length && children[childIndex] < childOffset) + childIndex += 3; + if (children[childIndex] == childOffset) + children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1); + else + children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec)); + childIndex += 3; + }); + let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset); + for (let i = 0; i < local.length; i++) + if (!local[i].type.valid(doc3, local[i])) + local.splice(i--, 1); + return new _DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children); + } + /** + Create a new set that contains the decorations in this set, minus + the ones in the given array. + */ + remove(decorations) { + if (decorations.length == 0 || this == empty) + return this; + return this.removeInner(decorations, 0); + } + removeInner(decorations, offset) { + let children = this.children, local = this.local; + for (let i = 0; i < children.length; i += 3) { + let found2; + let from = children[i] + offset, to = children[i + 1] + offset; + for (let j = 0, span; j < decorations.length; j++) + if (span = decorations[j]) { + if (span.from > from && span.to < to) { + decorations[j] = null; + (found2 || (found2 = [])).push(span); + } + } + if (!found2) + continue; + if (children == this.children) + children = this.children.slice(); + let removed = children[i + 2].removeInner(found2, from + 1); + if (removed != empty) { + children[i + 2] = removed; + } else { + children.splice(i, 3); + i -= 3; + } + } + if (local.length) { + for (let i = 0, span; i < decorations.length; i++) + if (span = decorations[i]) { + for (let j = 0; j < local.length; j++) + if (local[j].eq(span, offset)) { + if (local == this.local) + local = this.local.slice(); + local.splice(j--, 1); + } + } + } + if (children == this.children && local == this.local) + return this; + return local.length || children.length ? new _DecorationSet(local, children) : empty; + } + forChild(offset, node) { + if (this == empty) + return this; + if (node.isLeaf) + return _DecorationSet.empty; + let child, local; + for (let i = 0; i < this.children.length; i += 3) + if (this.children[i] >= offset) { + if (this.children[i] == offset) + child = this.children[i + 2]; + break; + } + let start = offset + 1, end = start + node.content.size; + for (let i = 0; i < this.local.length; i++) { + let dec = this.local[i]; + if (dec.from < end && dec.to > start && dec.type instanceof InlineType) { + let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start; + if (from < to) + (local || (local = [])).push(dec.copy(from, to)); + } + } + if (local) { + let localSet = new _DecorationSet(local.sort(byPos), none); + return child ? new DecorationGroup([localSet, child]) : localSet; + } + return child || empty; + } + /** + @internal + */ + eq(other) { + if (this == other) + return true; + if (!(other instanceof _DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length) + return false; + for (let i = 0; i < this.local.length; i++) + if (!this.local[i].eq(other.local[i])) + return false; + for (let i = 0; i < this.children.length; i += 3) + if (this.children[i] != other.children[i] || this.children[i + 1] != other.children[i + 1] || !this.children[i + 2].eq(other.children[i + 2])) + return false; + return true; + } + /** + @internal + */ + locals(node) { + return removeOverlap(this.localsInner(node)); + } + /** + @internal + */ + localsInner(node) { + if (this == empty) + return none; + if (node.inlineContent || !this.local.some(InlineType.is)) + return this.local; + let result = []; + for (let i = 0; i < this.local.length; i++) { + if (!(this.local[i].type instanceof InlineType)) + result.push(this.local[i]); + } + return result; + } + forEachSet(f) { + f(this); + } +}; +DecorationSet.empty = new DecorationSet([], []); +DecorationSet.removeOverlap = removeOverlap; +var empty = DecorationSet.empty; +var DecorationGroup = class _DecorationGroup { + constructor(members) { + this.members = members; + } + map(mapping, doc3) { + const mappedDecos = this.members.map((member) => member.map(mapping, doc3, noSpec)); + return _DecorationGroup.from(mappedDecos); + } + forChild(offset, child) { + if (child.isLeaf) + return DecorationSet.empty; + let found2 = []; + for (let i = 0; i < this.members.length; i++) { + let result = this.members[i].forChild(offset, child); + if (result == empty) + continue; + if (result instanceof _DecorationGroup) + found2 = found2.concat(result.members); + else + found2.push(result); + } + return _DecorationGroup.from(found2); + } + eq(other) { + if (!(other instanceof _DecorationGroup) || other.members.length != this.members.length) + return false; + for (let i = 0; i < this.members.length; i++) + if (!this.members[i].eq(other.members[i])) + return false; + return true; + } + locals(node) { + let result, sorted = true; + for (let i = 0; i < this.members.length; i++) { + let locals = this.members[i].localsInner(node); + if (!locals.length) + continue; + if (!result) { + result = locals; + } else { + if (sorted) { + result = result.slice(); + sorted = false; + } + for (let j = 0; j < locals.length; j++) + result.push(locals[j]); + } + } + return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none; + } + // Create a group for the given array of decoration sets, or return + // a single set when possible. + static from(members) { + switch (members.length) { + case 0: + return empty; + case 1: + return members[0]; + default: + return new _DecorationGroup(members.every((m) => m instanceof DecorationSet) ? members : members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), [])); + } + } + forEachSet(f) { + for (let i = 0; i < this.members.length; i++) + this.members[i].forEachSet(f); + } +}; +function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) { + let children = oldChildren.slice(); + for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) { + let moved = 0; + mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => { + let dSize = newEnd - newStart - (oldEnd - oldStart); + for (let i2 = 0; i2 < children.length; i2 += 3) { + let end = children[i2 + 1]; + if (end < 0 || oldStart > end + baseOffset - moved) + continue; + let start = children[i2] + baseOffset - moved; + if (oldEnd >= start) { + children[i2 + 1] = oldStart <= start ? -2 : -1; + } else if (oldStart >= baseOffset && dSize) { + children[i2] += dSize; + children[i2 + 1] += dSize; + } + } + moved += dSize; + }); + baseOffset = mapping.maps[i].map(baseOffset, -1); + } + let mustRebuild = false; + for (let i = 0; i < children.length; i += 3) + if (children[i + 1] < 0) { + if (children[i + 1] == -2) { + mustRebuild = true; + children[i + 1] = -1; + continue; + } + let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset; + if (fromLocal < 0 || fromLocal >= node.content.size) { + mustRebuild = true; + continue; + } + let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset; + let { index, offset: childOffset } = node.content.findIndex(fromLocal); + let childNode = node.maybeChild(index); + if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { + let mapped = children[i + 2].mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options); + if (mapped != empty) { + children[i] = fromLocal; + children[i + 1] = toLocal; + children[i + 2] = mapped; + } else { + children[i + 1] = -2; + mustRebuild = true; + } + } else { + mustRebuild = true; + } + } + if (mustRebuild) { + let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options); + let built = buildTree(decorations, node, 0, options); + newLocal = built.local; + for (let i = 0; i < children.length; i += 3) + if (children[i + 1] < 0) { + children.splice(i, 3); + i -= 3; + } + for (let i = 0, j = 0; i < built.children.length; i += 3) { + let from = built.children[i]; + while (j < children.length && children[j] < from) + j += 3; + children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]); + } + } + return new DecorationSet(newLocal.sort(byPos), children); +} +function moveSpans(spans, offset) { + if (!offset || !spans.length) + return spans; + let result = []; + for (let i = 0; i < spans.length; i++) { + let span = spans[i]; + result.push(new Decoration(span.from + offset, span.to + offset, span.type)); + } + return result; +} +function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) { + function gather(set, oldOffset2) { + for (let i = 0; i < set.local.length; i++) { + let mapped = set.local[i].map(mapping, offset, oldOffset2); + if (mapped) + decorations.push(mapped); + else if (options.onRemove) + options.onRemove(set.local[i].spec); + } + for (let i = 0; i < set.children.length; i += 3) + gather(set.children[i + 2], set.children[i] + oldOffset2 + 1); + } + for (let i = 0; i < children.length; i += 3) + if (children[i + 1] == -1) + gather(children[i + 2], oldChildren[i] + oldOffset + 1); + return decorations; +} +function takeSpansForNode(spans, node, offset) { + if (node.isLeaf) + return null; + let end = offset + node.nodeSize, found2 = null; + for (let i = 0, span; i < spans.length; i++) { + if ((span = spans[i]) && span.from > offset && span.to < end) { + (found2 || (found2 = [])).push(span); + spans[i] = null; + } + } + return found2; +} +function withoutNulls(array) { + let result = []; + for (let i = 0; i < array.length; i++) + if (array[i] != null) + result.push(array[i]); + return result; +} +function buildTree(spans, node, offset, options) { + let children = [], hasNulls = false; + node.forEach((childNode, localStart) => { + let found2 = takeSpansForNode(spans, childNode, localStart + offset); + if (found2) { + hasNulls = true; + let subtree = buildTree(found2, childNode, offset + localStart + 1, options); + if (subtree != empty) + children.push(localStart, localStart + childNode.nodeSize, subtree); + } + }); + let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos); + for (let i = 0; i < locals.length; i++) + if (!locals[i].type.valid(node, locals[i])) { + if (options.onRemove) + options.onRemove(locals[i].spec); + locals.splice(i--, 1); + } + return locals.length || children.length ? new DecorationSet(locals, children) : empty; +} +function byPos(a, b) { + return a.from - b.from || a.to - b.to; +} +function removeOverlap(spans) { + let working = spans; + for (let i = 0; i < working.length - 1; i++) { + let span = working[i]; + if (span.from != span.to) + for (let j = i + 1; j < working.length; j++) { + let next = working[j]; + if (next.from == span.from) { + if (next.to != span.to) { + if (working == spans) + working = spans.slice(); + working[j] = next.copy(next.from, span.to); + insertAhead(working, j + 1, next.copy(span.to, next.to)); + } + continue; + } else { + if (next.from < span.to) { + if (working == spans) + working = spans.slice(); + working[i] = span.copy(span.from, next.from); + insertAhead(working, j, span.copy(next.from, span.to)); + } + break; + } + } + } + return working; +} +function insertAhead(array, i, deco) { + while (i < array.length && byPos(deco, array[i]) > 0) + i++; + array.splice(i, 0, deco); +} +function viewDecorations(view) { + let found2 = []; + view.someProp("decorations", (f) => { + let result = f(view.state); + if (result && result != empty) + found2.push(result); + }); + if (view.cursorWrapper) + found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); + return DecorationGroup.from(found2); +} +var observeOptions = { + childList: true, + characterData: true, + characterDataOldValue: true, + attributes: true, + attributeOldValue: true, + subtree: true +}; +var useCharData = ie && ie_version <= 11; +var SelectionState = class { + constructor() { + this.anchorNode = null; + this.anchorOffset = 0; + this.focusNode = null; + this.focusOffset = 0; + } + set(sel) { + this.anchorNode = sel.anchorNode; + this.anchorOffset = sel.anchorOffset; + this.focusNode = sel.focusNode; + this.focusOffset = sel.focusOffset; + } + clear() { + this.anchorNode = this.focusNode = null; + } + eq(sel) { + return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset; + } +}; +var DOMObserver = class { + constructor(view, handleDOMChange) { + this.view = view; + this.handleDOMChange = handleDOMChange; + this.queue = []; + this.flushingSoon = -1; + this.observer = null; + this.currentSelection = new SelectionState(); + this.onCharData = null; + this.suppressingSelectionUpdates = false; + this.lastChangedTextNode = null; + this.observer = window.MutationObserver && new window.MutationObserver((mutations) => { + for (let i = 0; i < mutations.length; i++) + this.queue.push(mutations[i]); + if (ie && ie_version <= 11 && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) { + this.flushSoon(); + } else if (safari && view.composing && mutations.some((m) => m.type == "childList" && m.target.nodeName == "TR")) { + view.input.badSafariComposition = true; + this.flushSoon(); + } else { + this.flush(); + } + }); + if (useCharData) { + this.onCharData = (e) => { + this.queue.push({ target: e.target, type: "characterData", oldValue: e.prevValue }); + this.flushSoon(); + }; + } + this.onSelectionChange = this.onSelectionChange.bind(this); + } + flushSoon() { + if (this.flushingSoon < 0) + this.flushingSoon = window.setTimeout(() => { + this.flushingSoon = -1; + this.flush(); + }, 20); + } + forceFlush() { + if (this.flushingSoon > -1) { + window.clearTimeout(this.flushingSoon); + this.flushingSoon = -1; + this.flush(); + } + } + start() { + if (this.observer) { + this.observer.takeRecords(); + this.observer.observe(this.view.dom, observeOptions); + } + if (this.onCharData) + this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData); + this.connectSelection(); + } + stop() { + if (this.observer) { + let take = this.observer.takeRecords(); + if (take.length) { + for (let i = 0; i < take.length; i++) + this.queue.push(take[i]); + window.setTimeout(() => this.flush(), 20); + } + this.observer.disconnect(); + } + if (this.onCharData) + this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); + this.disconnectSelection(); + } + connectSelection() { + this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); + } + disconnectSelection() { + this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); + } + suppressSelectionUpdates() { + this.suppressingSelectionUpdates = true; + setTimeout(() => this.suppressingSelectionUpdates = false, 50); + } + onSelectionChange() { + if (!hasFocusAndSelection(this.view)) + return; + if (this.suppressingSelectionUpdates) + return selectionToDOM(this.view); + if (ie && ie_version <= 11 && !this.view.state.selection.empty) { + let sel = this.view.domSelectionRange(); + if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) + return this.flushSoon(); + } + this.flush(); + } + setCurSelection() { + this.currentSelection.set(this.view.domSelectionRange()); + } + ignoreSelectionChange(sel) { + if (!sel.focusNode) + return true; + let ancestors = /* @__PURE__ */ new Set(), container; + for (let scan = sel.focusNode; scan; scan = parentNode(scan)) + ancestors.add(scan); + for (let scan = sel.anchorNode; scan; scan = parentNode(scan)) + if (ancestors.has(scan)) { + container = scan; + break; + } + let desc = container && this.view.docView.nearestDesc(container); + if (desc && desc.ignoreMutation({ + type: "selection", + target: container.nodeType == 3 ? container.parentNode : container + })) { + this.setCurSelection(); + return true; + } + } + pendingRecords() { + if (this.observer) + for (let mut of this.observer.takeRecords()) + this.queue.push(mut); + return this.queue; + } + flush() { + let { view } = this; + if (!view.docView || this.flushingSoon > -1) + return; + let mutations = this.pendingRecords(); + if (mutations.length) + this.queue = []; + let sel = view.domSelectionRange(); + let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel); + let from = -1, to = -1, typeOver = false, added = []; + if (view.editable) { + for (let i = 0; i < mutations.length; i++) { + let result = this.registerMutation(mutations[i], added); + if (result) { + from = from < 0 ? result.from : Math.min(result.from, from); + to = to < 0 ? result.to : Math.max(result.to, to); + if (result.typeOver) + typeOver = true; + } + } + } + if (added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) { + for (let node of added) + if (node.nodeName == "BR" && node.parentNode) { + let after = node.nextSibling; + if (after && after.nodeType == 1 && after.contentEditable == "false") + node.parentNode.removeChild(node); + } + } else if (gecko && added.length) { + let brs = added.filter((n) => n.nodeName == "BR"); + if (brs.length == 2) { + let [a, b] = brs; + if (a.parentNode && a.parentNode.parentNode == b.parentNode) + b.remove(); + else + a.remove(); + } else { + let { focusNode } = this.currentSelection; + for (let br of brs) { + let parent = br.parentNode; + if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent)) + br.remove(); + } + } + } + let readSel = null; + if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) { + view.input.lastFocus = 0; + selectionToDOM(view); + this.currentSelection.set(sel); + view.scrollToSelection(); + } else if (from > -1 || newSel) { + if (from > -1) { + view.docView.markDirty(from, to); + checkCSS(view); + } + if (view.input.badSafariComposition) { + view.input.badSafariComposition = false; + fixUpBadSafariComposition(view, added); + } + this.handleDOMChange(from, to, typeOver, added); + if (view.docView && view.docView.dirty) + view.updateState(view.state); + else if (!this.currentSelection.eq(sel)) + selectionToDOM(view); + this.currentSelection.set(sel); + } + } + registerMutation(mut, added) { + if (added.indexOf(mut.target) > -1) + return null; + let desc = this.view.docView.nearestDesc(mut.target); + if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles + mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style"))) + return null; + if (!desc || desc.ignoreMutation(mut)) + return null; + if (mut.type == "childList") { + for (let i = 0; i < mut.addedNodes.length; i++) { + let node = mut.addedNodes[i]; + added.push(node); + if (node.nodeType == 3) + this.lastChangedTextNode = node; + } + if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target)) + return { from: desc.posBefore, to: desc.posAfter }; + let prev = mut.previousSibling, next = mut.nextSibling; + if (ie && ie_version <= 11 && mut.addedNodes.length) { + for (let i = 0; i < mut.addedNodes.length; i++) { + let { previousSibling, nextSibling } = mut.addedNodes[i]; + if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) + prev = previousSibling; + if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) + next = nextSibling; + } + } + let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0; + let from = desc.localPosFromDOM(mut.target, fromOffset, -1); + let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length; + let to = desc.localPosFromDOM(mut.target, toOffset, 1); + return { from, to }; + } else if (mut.type == "attributes") { + return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border }; + } else { + this.lastChangedTextNode = mut.target; + return { + from: desc.posAtStart, + to: desc.posAtEnd, + // An event was generated for a text change that didn't change + // any text. Mark the dom change to fall back to assuming the + // selection was typed over with an identical value if it can't + // find another change. + typeOver: mut.target.nodeValue == mut.oldValue + }; + } + } +}; +var cssChecked = /* @__PURE__ */ new WeakMap(); +var cssCheckWarned = false; +function checkCSS(view) { + if (cssChecked.has(view)) + return; + cssChecked.set(view, null); + if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) { + view.requiresGeckoHackNode = gecko; + if (cssCheckWarned) + return; + console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."); + cssCheckWarned = true; + } +} +function rangeToSelectionRange(view, range) { + let anchorNode = range.startContainer, anchorOffset = range.startOffset; + let focusNode = range.endContainer, focusOffset = range.endOffset; + let currentAnchor = view.domAtPos(view.state.selection.anchor); + if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset)) + [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; + return { anchorNode, anchorOffset, focusNode, focusOffset }; +} +function safariShadowSelectionRange(view, selection) { + if (selection.getComposedRanges) { + let range = selection.getComposedRanges(view.root)[0]; + if (range) + return rangeToSelectionRange(view, range); + } + let found2; + function read(event) { + event.preventDefault(); + event.stopImmediatePropagation(); + found2 = event.getTargetRanges()[0]; + } + view.dom.addEventListener("beforeinput", read, true); + document.execCommand("indent"); + view.dom.removeEventListener("beforeinput", read, true); + return found2 ? rangeToSelectionRange(view, found2) : null; +} +function blockParent(view, node) { + for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) { + let desc = view.docView.nearestDesc(p, true); + if (desc && desc.node.isBlock) + return p; + } + return null; +} +function fixUpBadSafariComposition(view, addedNodes) { + var _a; + let { focusNode, focusOffset } = view.domSelectionRange(); + for (let node of addedNodes) { + if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == "TR") { + let nextCell = node.nextSibling; + while (nextCell && (nextCell.nodeName != "TD" && nextCell.nodeName != "TH")) + nextCell = nextCell.nextSibling; + if (nextCell) { + let parent = nextCell; + for (; ; ) { + let first2 = parent.firstChild; + if (!first2 || first2.nodeType != 1 || first2.contentEditable == "false" || /^(BR|IMG)$/.test(first2.nodeName)) + break; + parent = first2; + } + parent.insertBefore(node, parent.firstChild); + if (focusNode == node) + view.domSelection().collapse(node, focusOffset); + } else { + node.parentNode.removeChild(node); + } + } + } +} +function parseBetween(view, from_, to_) { + let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_); + let domSel = view.domSelectionRange(); + let find; + let anchor = domSel.anchorNode; + if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) { + find = [{ node: anchor, offset: domSel.anchorOffset }]; + if (!selectionCollapsed(domSel)) + find.push({ node: domSel.focusNode, offset: domSel.focusOffset }); + } + if (chrome && view.input.lastKeyCode === 8) { + for (let off = toOffset; off > fromOffset; off--) { + let node = parent.childNodes[off - 1], desc = node.pmViewDesc; + if (node.nodeName == "BR" && !desc) { + toOffset = off; + break; + } + if (!desc || desc.size) + break; + } + } + let startDoc = view.state.doc; + let parser = view.someProp("domParser") || DOMParser.fromSchema(view.state.schema); + let $from = startDoc.resolve(from); + let sel = null, doc3 = parser.parse(parent, { + topNode: $from.parent, + topMatch: $from.parent.contentMatchAt($from.index()), + topOpen: true, + from: fromOffset, + to: toOffset, + preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true, + findPositions: find, + ruleFromNode, + context: $from + }); + if (find && find[0].pos != null) { + let anchor2 = find[0].pos, head = find[1] && find[1].pos; + if (head == null) + head = anchor2; + sel = { anchor: anchor2 + from, head: head + from }; + } + return { doc: doc3, sel, from, to }; +} +function ruleFromNode(dom) { + let desc = dom.pmViewDesc; + if (desc) { + return desc.parseRule(); + } else if (dom.nodeName == "BR" && dom.parentNode) { + if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) { + let skip = document.createElement("div"); + skip.appendChild(document.createElement("li")); + return { skip }; + } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) { + return { ignore: true }; + } + } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) { + return { ignore: true }; + } + return null; +} +var isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i; +function readDOMChange(view, from, to, typeOver, addedNodes) { + let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0); + view.input.compositionPendingChanges = 0; + if (from < 0) { + let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null; + let newSel = selectionFromDOM(view, origin); + if (newSel && !view.state.selection.eq(newSel)) { + if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) + return; + let tr = view.state.tr.setSelection(newSel); + if (origin == "pointer") + tr.setMeta("pointer", true); + else if (origin == "key") + tr.scrollIntoView(); + if (compositionID) + tr.setMeta("composition", compositionID); + view.dispatch(tr); + } + return; + } + let $before = view.state.doc.resolve(from); + let shared = $before.sharedDepth(to); + from = $before.before(shared + 1); + to = view.state.doc.resolve(to).after(shared + 1); + let sel = view.state.selection; + let parse = parseBetween(view, from, to); + let doc3 = view.state.doc, compare = doc3.slice(parse.from, parse.to); + let preferredPos, preferredSide; + if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) { + preferredPos = view.state.selection.to; + preferredSide = "end"; + } else { + preferredPos = view.state.selection.from; + preferredSide = "start"; + } + view.input.lastKeyCode = null; + let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide); + if (change) + view.input.domChangeCount++; + if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { + view.input.lastIOSEnter = 0; + return; + } + if (!change) { + if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) { + change = { start: sel.from, endA: sel.to, endB: sel.to }; + } else { + if (parse.sel) { + let sel2 = resolveSelection(view, view.state.doc, parse.sel); + if (sel2 && !sel2.eq(view.state.selection)) { + let tr = view.state.tr.setSelection(sel2); + if (compositionID) + tr.setMeta("composition", compositionID); + view.dispatch(tr); + } + } + return; + } + } + if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) { + if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse.from) { + change.start = view.state.selection.from; + } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse.to) { + change.endB += view.state.selection.to - change.endA; + change.endA = view.state.selection.to; + } + } + if (ie && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse.from && parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == "  ") { + change.start--; + change.endA--; + change.endB--; + } + let $from = parse.doc.resolveNoCache(change.start - parse.from); + let $to = parse.doc.resolveNoCache(change.endB - parse.from); + let $fromA = doc3.resolve(change.start); + let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA; + if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { + view.input.lastIOSEnter = 0; + return; + } + if (view.state.selection.anchor > change.start && looksLikeBackspace(doc3, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) { + if (android && chrome) + view.domObserver.suppressSelectionUpdates(); + return; + } + if (chrome && change.endB == change.start) + view.input.lastChromeDelete = Date.now(); + if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) { + change.endB -= 2; + $to = parse.doc.resolveNoCache(change.endB - parse.from); + setTimeout(() => { + view.someProp("handleKeyDown", function(f) { + return f(view, keyEvent(13, "Enter")); + }); + }, 20); + } + let chFrom = change.start, chTo = change.endA; + let mkTr = (base2) => { + let tr = base2 || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); + if (parse.sel) { + let sel2 = resolveSelection(view, tr.doc, parse.sel); + if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr.mapping.map(chTo) - 1) || ie && sel2.empty && sel2.head == chFrom)) + tr.setSelection(sel2); + } + if (compositionID) + tr.setMeta("composition", compositionID); + return tr.scrollIntoView(); + }; + let markChange; + if (inlineChange) { + if ($from.pos == $to.pos) { + if (ie && ie_version <= 11 && $from.parentOffset == 0) { + view.domObserver.suppressSelectionUpdates(); + setTimeout(() => selectionToDOM(view), 20); + } + let tr = mkTr(view.state.tr.delete(chFrom, chTo)); + let marks = doc3.resolve(change.start).marksAcross(doc3.resolve(change.endA)); + if (marks) + tr.ensureMarks(marks); + view.dispatch(tr); + } else if ( + // Adding or removing a mark + change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start()))) + ) { + let tr = mkTr(view.state.tr); + if (markChange.type == "add") + tr.addMark(chFrom, chTo, markChange.mark); + else + tr.removeMark(chFrom, chTo, markChange.mark); + view.dispatch(tr); + } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) { + let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset); + let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo)); + if (!view.someProp("handleTextInput", (f) => f(view, chFrom, chTo, text, deflt))) + view.dispatch(deflt()); + } else { + view.dispatch(mkTr()); + } + } else { + view.dispatch(mkTr()); + } +} +function resolveSelection(view, doc3, parsedSel) { + if (Math.max(parsedSel.anchor, parsedSel.head) > doc3.content.size) + return null; + return selectionBetween(view, doc3.resolve(parsedSel.anchor), doc3.resolve(parsedSel.head)); +} +function isMarkChange(cur, prev) { + let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks; + let added = curMarks, removed = prevMarks, type, mark, update; + for (let i = 0; i < prevMarks.length; i++) + added = prevMarks[i].removeFromSet(added); + for (let i = 0; i < curMarks.length; i++) + removed = curMarks[i].removeFromSet(removed); + if (added.length == 1 && removed.length == 0) { + mark = added[0]; + type = "add"; + update = (node) => node.mark(mark.addToSet(node.marks)); + } else if (added.length == 0 && removed.length == 1) { + mark = removed[0]; + type = "remove"; + update = (node) => node.mark(mark.removeFromSet(node.marks)); + } else { + return null; + } + let updated = []; + for (let i = 0; i < prev.childCount; i++) + updated.push(update(prev.child(i))); + if (Fragment.from(updated).eq(cur)) + return { mark, type }; +} +function looksLikeBackspace(old, start, end, $newStart, $newEnd) { + if ( + // The content must have shrunk + end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into + skipClosingAndOpening($newStart, true, false) < $newEnd.pos + ) + return false; + let $start = old.resolve(start); + if (!$newStart.parent.isTextblock) { + let after = $start.nodeAfter; + return after != null && end == start + after.nodeSize; + } + if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) + return false; + let $next = old.resolve(skipClosingAndOpening($start, true, true)); + if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end) + return false; + return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content); +} +function skipClosingAndOpening($pos, fromEnd, mayOpen) { + let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos; + while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) { + depth--; + end++; + fromEnd = false; + } + if (mayOpen) { + let next = $pos.node(depth).maybeChild($pos.indexAfter(depth)); + while (next && !next.isLeaf) { + next = next.firstChild; + end++; + } + } + return end; +} +function findDiff(a, b, pos, preferredPos, preferredSide) { + let start = a.findDiffStart(b, pos); + if (start == null) + return null; + let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size); + if (preferredSide == "end") { + let adjust = Math.max(0, start - Math.min(endA, endB)); + preferredPos -= endA + adjust - start; + } + if (endA < start && a.size < b.size) { + let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0; + start -= move; + if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1))) + start += move ? 1 : -1; + endB = start + (endB - endA); + endA = start; + } else if (endB < start) { + let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0; + start -= move; + if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1))) + start += move ? 1 : -1; + endA = start + (endA - endB); + endB = start; + } + return { start, endA, endB }; +} +function isSurrogatePair(str) { + if (str.length != 2) + return false; + let a = str.charCodeAt(0), b = str.charCodeAt(1); + return a >= 56320 && a <= 57343 && b >= 55296 && b <= 56319; +} +var EditorView = class { + /** + Create a view. `place` may be a DOM node that the editor should + be appended to, a function that will place it into the document, + or an object whose `mount` property holds the node to use as the + document container. If it is `null`, the editor will not be + added to the document. + */ + constructor(place, props) { + this._root = null; + this.focused = false; + this.trackWrites = null; + this.mounted = false; + this.markCursor = null; + this.cursorWrapper = null; + this.lastSelectedViewDesc = void 0; + this.input = new InputState(); + this.prevDirectPlugins = []; + this.pluginViews = []; + this.requiresGeckoHackNode = false; + this.dragging = null; + this._props = props; + this.state = props.state; + this.directPlugins = props.plugins || []; + this.directPlugins.forEach(checkStateComponent); + this.dispatch = this.dispatch.bind(this); + this.dom = place && place.mount || document.createElement("div"); + if (place) { + if (place.appendChild) + place.appendChild(this.dom); + else if (typeof place == "function") + place(this.dom); + else if (place.mount) + this.mounted = true; + } + this.editable = getEditable(this); + updateCursorWrapper(this); + this.nodeViews = buildNodeViews(this); + this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this); + this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added)); + this.domObserver.start(); + initInput(this); + this.updatePluginViews(); + } + /** + Holds `true` when a + [composition](https://w3c.github.io/uievents/#events-compositionevents) + is active. + */ + get composing() { + return this.input.composing; + } + /** + The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps). + */ + get props() { + if (this._props.state != this.state) { + let prev = this._props; + this._props = {}; + for (let name in prev) + this._props[name] = prev[name]; + this._props.state = this.state; + } + return this._props; + } + /** + Update the view's props. Will immediately cause an update to + the DOM. + */ + update(props) { + if (props.handleDOMEvents != this._props.handleDOMEvents) + ensureListeners(this); + let prevProps = this._props; + this._props = props; + if (props.plugins) { + props.plugins.forEach(checkStateComponent); + this.directPlugins = props.plugins; + } + this.updateStateInner(props.state, prevProps); + } + /** + Update the view by updating existing props object with the object + given as argument. Equivalent to `view.update(Object.assign({}, + view.props, props))`. + */ + setProps(props) { + let updated = {}; + for (let name in this._props) + updated[name] = this._props[name]; + updated.state = this.state; + for (let name in props) + updated[name] = props[name]; + this.update(updated); + } + /** + Update the editor's `state` prop, without touching any of the + other props. + */ + updateState(state) { + this.updateStateInner(state, this._props); + } + updateStateInner(state, prevProps) { + var _a; + let prev = this.state, redraw = false, updateSel = false; + if (state.storedMarks && this.composing) { + clearComposition(this); + updateSel = true; + } + this.state = state; + let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins; + if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) { + let nodeViews = buildNodeViews(this); + if (changedNodeViews(nodeViews, this.nodeViews)) { + this.nodeViews = nodeViews; + redraw = true; + } + } + if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) { + ensureListeners(this); + } + this.editable = getEditable(this); + updateCursorWrapper(this); + let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this); + let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve"; + let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco); + if (updateDoc || !state.selection.eq(prev.selection)) + updateSel = true; + let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this); + if (updateSel) { + this.domObserver.stop(); + let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection); + if (updateDoc) { + let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null; + if (this.composing) + this.input.compositionNode = findCompositionNode(this); + if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) { + this.docView.updateOuterDeco(outerDeco); + this.docView.destroy(); + this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this); + } + if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites))) + forceSelUpdate = true; + } + if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) { + selectionToDOM(this, forceSelUpdate); + } else { + syncNodeSelection(this, state.selection); + this.domObserver.setCurSelection(); + } + this.domObserver.start(); + } + this.updatePluginViews(prev); + if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc)) + this.updateDraggedNode(this.dragging, prev); + if (scroll == "reset") { + this.dom.scrollTop = 0; + } else if (scroll == "to selection") { + this.scrollToSelection(); + } else if (oldScrollPos) { + resetScrollPos(oldScrollPos); + } + } + /** + @internal + */ + scrollToSelection() { + let startDOM = this.domSelectionRange().focusNode; + if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ; + else if (this.someProp("handleScrollToSelection", (f) => f(this))) ; + else if (this.state.selection instanceof NodeSelection) { + let target = this.docView.domAfterPos(this.state.selection.from); + if (target.nodeType == 1) + scrollRectIntoView(this, target.getBoundingClientRect(), startDOM); + } else { + scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM); + } + } + destroyPluginViews() { + let view; + while (view = this.pluginViews.pop()) + if (view.destroy) + view.destroy(); + } + updatePluginViews(prevState) { + if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) { + this.prevDirectPlugins = this.directPlugins; + this.destroyPluginViews(); + for (let i = 0; i < this.directPlugins.length; i++) { + let plugin = this.directPlugins[i]; + if (plugin.spec.view) + this.pluginViews.push(plugin.spec.view(this)); + } + for (let i = 0; i < this.state.plugins.length; i++) { + let plugin = this.state.plugins[i]; + if (plugin.spec.view) + this.pluginViews.push(plugin.spec.view(this)); + } + } else { + for (let i = 0; i < this.pluginViews.length; i++) { + let pluginView = this.pluginViews[i]; + if (pluginView.update) + pluginView.update(this, prevState); + } + } + } + updateDraggedNode(dragging, prev) { + let sel = dragging.node, found2 = -1; + if (this.state.doc.nodeAt(sel.from) == sel.node) { + found2 = sel.from; + } else { + let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size); + let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos); + if (moved == sel.node) + found2 = movedPos; + } + this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2)); + } + someProp(propName, f) { + let prop = this._props && this._props[propName], value; + if (prop != null && (value = f ? f(prop) : prop)) + return value; + for (let i = 0; i < this.directPlugins.length; i++) { + let prop2 = this.directPlugins[i].props[propName]; + if (prop2 != null && (value = f ? f(prop2) : prop2)) + return value; + } + let plugins = this.state.plugins; + if (plugins) + for (let i = 0; i < plugins.length; i++) { + let prop2 = plugins[i].props[propName]; + if (prop2 != null && (value = f ? f(prop2) : prop2)) + return value; + } + } + /** + Query whether the view has focus. + */ + hasFocus() { + if (ie) { + let node = this.root.activeElement; + if (node == this.dom) + return true; + if (!node || !this.dom.contains(node)) + return false; + while (node && this.dom != node && this.dom.contains(node)) { + if (node.contentEditable == "false") + return false; + node = node.parentElement; + } + return true; + } + return this.root.activeElement == this.dom; + } + /** + Focus the editor. + */ + focus() { + this.domObserver.stop(); + if (this.editable) + focusPreventScroll(this.dom); + selectionToDOM(this); + this.domObserver.start(); + } + /** + Get the document root in which the editor exists. This will + usually be the top-level `document`, but might be a [shadow + DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM) + root if the editor is inside one. + */ + get root() { + let cached = this._root; + if (cached == null) + for (let search = this.dom.parentNode; search; search = search.parentNode) { + if (search.nodeType == 9 || search.nodeType == 11 && search.host) { + if (!search.getSelection) + Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection(); + return this._root = search; + } + } + return cached || document; + } + /** + When an existing editor view is moved to a new document or + shadow tree, call this to make it recompute its root. + */ + updateRoot() { + this._root = null; + } + /** + Given a pair of viewport coordinates, return the document + position that corresponds to them. May return null if the given + coordinates aren't inside of the editor. When an object is + returned, its `pos` property is the position nearest to the + coordinates, and its `inside` property holds the position of the + inner node that the position falls inside of, or -1 if it is at + the top level, not in any node. + */ + posAtCoords(coords) { + return posAtCoords(this, coords); + } + /** + Returns the viewport rectangle at a given document position. + `left` and `right` will be the same number, as this returns a + flat cursor-ish rectangle. If the position is between two things + that aren't directly adjacent, `side` determines which element + is used. When < 0, the element before the position is used, + otherwise the element after. + */ + coordsAtPos(pos, side = 1) { + return coordsAtPos(this, pos, side); + } + /** + Find the DOM position that corresponds to the given document + position. When `side` is negative, find the position as close as + possible to the content before the position. When positive, + prefer positions close to the content after the position. When + zero, prefer as shallow a position as possible. + + Note that you should **not** mutate the editor's internal DOM, + only inspect it (and even that is usually not necessary). + */ + domAtPos(pos, side = 0) { + return this.docView.domFromPos(pos, side); + } + /** + Find the DOM node that represents the document node after the + given position. May return `null` when the position doesn't point + in front of a node or if the node is inside an opaque node view. + + This is intended to be able to call things like + `getBoundingClientRect` on that DOM node. Do **not** mutate the + editor DOM directly, or add styling this way, since that will be + immediately overriden by the editor as it redraws the node. + */ + nodeDOM(pos) { + let desc = this.docView.descAt(pos); + return desc ? desc.nodeDOM : null; + } + /** + Find the document position that corresponds to a given DOM + position. (Whenever possible, it is preferable to inspect the + document structure directly, rather than poking around in the + DOM, but sometimes—for example when interpreting an event + target—you don't have a choice.) + + The `bias` parameter can be used to influence which side of a DOM + node to use when the position is inside a leaf node. + */ + posAtDOM(node, offset, bias = -1) { + let pos = this.docView.posFromDOM(node, offset, bias); + if (pos == null) + throw new RangeError("DOM position not inside the editor"); + return pos; + } + /** + Find out whether the selection is at the end of a textblock when + moving in a given direction. When, for example, given `"left"`, + it will return true if moving left from the current cursor + position would leave that position's parent textblock. Will apply + to the view's current state by default, but it is possible to + pass a different state. + */ + endOfTextblock(dir, state) { + return endOfTextblock(this, state || this.state, dir); + } + /** + Run the editor's paste logic with the given HTML string. The + `event`, if given, will be passed to the + [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook. + */ + pasteHTML(html, event) { + return doPaste(this, "", html, false, event || new ClipboardEvent("paste")); + } + /** + Run the editor's paste logic with the given plain-text input. + */ + pasteText(text, event) { + return doPaste(this, text, null, true, event || new ClipboardEvent("paste")); + } + /** + Serialize the given slice as it would be if it was copied from + this editor. Returns a DOM element that contains a + representation of the slice as its children, a textual + representation, and the transformed slice (which can be + different from the given input due to hooks like + [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)). + */ + serializeForClipboard(slice) { + return serializeForClipboard(this, slice); + } + /** + Removes the editor from the DOM and destroys all [node + views](https://prosemirror.net/docs/ref/#view.NodeView). + */ + destroy() { + if (!this.docView) + return; + destroyInput(this); + this.destroyPluginViews(); + if (this.mounted) { + this.docView.update(this.state.doc, [], viewDecorations(this), this); + this.dom.textContent = ""; + } else if (this.dom.parentNode) { + this.dom.parentNode.removeChild(this.dom); + } + this.docView.destroy(); + this.docView = null; + clearReusedRange(); + } + /** + This is true when the view has been + [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be + used anymore). + */ + get isDestroyed() { + return this.docView == null; + } + /** + Used for testing. + */ + dispatchEvent(event) { + return dispatchEvent(this, event); + } + /** + @internal + */ + domSelectionRange() { + let sel = this.domSelection(); + if (!sel) + return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 }; + return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel; + } + /** + @internal + */ + domSelection() { + return this.root.getSelection(); + } +}; +EditorView.prototype.dispatch = function(tr) { + let dispatchTransaction = this._props.dispatchTransaction; + if (dispatchTransaction) + dispatchTransaction.call(this, tr); + else + this.updateState(this.state.apply(tr)); +}; +function computeDocDeco(view) { + let attrs = /* @__PURE__ */ Object.create(null); + attrs.class = "ProseMirror"; + attrs.contenteditable = String(view.editable); + view.someProp("attributes", (value) => { + if (typeof value == "function") + value = value(view.state); + if (value) + for (let attr in value) { + if (attr == "class") + attrs.class += " " + value[attr]; + else if (attr == "style") + attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr]; + else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName") + attrs[attr] = String(value[attr]); + } + }); + if (!attrs.translate) + attrs.translate = "no"; + return [Decoration.node(0, view.state.doc.content.size, attrs)]; +} +function updateCursorWrapper(view) { + if (view.markCursor) { + let dom = document.createElement("img"); + dom.className = "ProseMirror-separator"; + dom.setAttribute("mark-placeholder", "true"); + dom.setAttribute("alt", ""); + view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) }; + } else { + view.cursorWrapper = null; + } +} +function getEditable(view) { + return !view.someProp("editable", (value) => value(view.state) === false); +} +function selectionContextChanged(sel1, sel2) { + let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head)); + return sel1.$anchor.start(depth) != sel2.$anchor.start(depth); +} +function buildNodeViews(view) { + let result = /* @__PURE__ */ Object.create(null); + function add(obj) { + for (let prop in obj) + if (!Object.prototype.hasOwnProperty.call(result, prop)) + result[prop] = obj[prop]; + } + view.someProp("nodeViews", add); + view.someProp("markViews", add); + return result; +} +function changedNodeViews(a, b) { + let nA = 0, nB = 0; + for (let prop in a) { + if (a[prop] != b[prop]) + return true; + nA++; + } + for (let _ in b) + nB++; + return nA != nB; +} +function checkStateComponent(plugin) { + if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction) + throw new RangeError("Plugins passed directly to the view must not have a state component"); +} + +// node_modules/w3c-keyname/index.js +var base = { + 8: "Backspace", + 9: "Tab", + 10: "Enter", + 12: "NumLock", + 13: "Enter", + 16: "Shift", + 17: "Control", + 18: "Alt", + 20: "CapsLock", + 27: "Escape", + 32: " ", + 33: "PageUp", + 34: "PageDown", + 35: "End", + 36: "Home", + 37: "ArrowLeft", + 38: "ArrowUp", + 39: "ArrowRight", + 40: "ArrowDown", + 44: "PrintScreen", + 45: "Insert", + 46: "Delete", + 59: ";", + 61: "=", + 91: "Meta", + 92: "Meta", + 106: "*", + 107: "+", + 108: ",", + 109: "-", + 110: ".", + 111: "/", + 144: "NumLock", + 145: "ScrollLock", + 160: "Shift", + 161: "Shift", + 162: "Control", + 163: "Control", + 164: "Alt", + 165: "Alt", + 173: "-", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'" +}; +var shift = { + 48: ")", + 49: "!", + 50: "@", + 51: "#", + 52: "$", + 53: "%", + 54: "^", + 55: "&", + 56: "*", + 57: "(", + 59: ":", + 61: "+", + 173: "_", + 186: ":", + 187: "+", + 188: "<", + 189: "_", + 190: ">", + 191: "?", + 192: "~", + 219: "{", + 220: "|", + 221: "}", + 222: '"' +}; +var mac3 = typeof navigator != "undefined" && /Mac/.test(navigator.platform); +var ie2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); +for (i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); +var i; +for (i = 1; i <= 24; i++) base[i + 111] = "F" + i; +var i; +for (i = 65; i <= 90; i++) { + base[i] = String.fromCharCode(i + 32); + shift[i] = String.fromCharCode(i); +} +var i; +for (code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; +var code; +function keyName(event) { + var ignoreKey = mac3 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified"; + var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; + if (name == "Esc") name = "Escape"; + if (name == "Del") name = "Delete"; + if (name == "Left") name = "ArrowLeft"; + if (name == "Up") name = "ArrowUp"; + if (name == "Right") name = "ArrowRight"; + if (name == "Down") name = "ArrowDown"; + return name; +} + +// node_modules/prosemirror-keymap/dist/index.js +var mac4 = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform); +var windows2 = typeof navigator != "undefined" && /Win/.test(navigator.platform); +function normalizeKeyName(name) { + let parts = name.split(/-(?!$)/), result = parts[parts.length - 1]; + if (result == "Space") + result = " "; + let alt, ctrl, shift2, meta; + for (let i = 0; i < parts.length - 1; i++) { + let mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) + meta = true; + else if (/^a(lt)?$/i.test(mod)) + alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) + ctrl = true; + else if (/^s(hift)?$/i.test(mod)) + shift2 = true; + else if (/^mod$/i.test(mod)) { + if (mac4) + meta = true; + else + ctrl = true; + } else + throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) + result = "Alt-" + result; + if (ctrl) + result = "Ctrl-" + result; + if (meta) + result = "Meta-" + result; + if (shift2) + result = "Shift-" + result; + return result; +} +function normalize(map) { + let copy2 = /* @__PURE__ */ Object.create(null); + for (let prop in map) + copy2[normalizeKeyName(prop)] = map[prop]; + return copy2; +} +function modifiers(name, event, shift2 = true) { + if (event.altKey) + name = "Alt-" + name; + if (event.ctrlKey) + name = "Ctrl-" + name; + if (event.metaKey) + name = "Meta-" + name; + if (shift2 && event.shiftKey) + name = "Shift-" + name; + return name; +} +function keymap(bindings) { + return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } }); +} +function keydownHandler(bindings) { + let map = normalize(bindings); + return function(view, event) { + let name = keyName(event), baseName, direct = map[modifiers(name, event)]; + if (direct && direct(view.state, view.dispatch, view)) + return true; + if (name.length == 1 && name != " ") { + if (event.shiftKey) { + let noShift = map[modifiers(name, event, false)]; + if (noShift && noShift(view.state, view.dispatch, view)) + return true; + } + if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows + !(windows2 && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) { + let fromCode = map[modifiers(baseName, event)]; + if (fromCode && fromCode(view.state, view.dispatch, view)) + return true; + } + } + return false; + }; +} + +// node_modules/@tiptap/core/dist/index.js +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +function createChainableState(config) { + const { state, transaction } = config; + let { selection } = transaction; + let { doc: doc3 } = transaction; + let { storedMarks } = transaction; + return { + ...state, + apply: state.apply.bind(state), + applyTransaction: state.applyTransaction.bind(state), + plugins: state.plugins, + schema: state.schema, + reconfigure: state.reconfigure.bind(state), + toJSON: state.toJSON.bind(state), + get storedMarks() { + return storedMarks; + }, + get selection() { + return selection; + }, + get doc() { + return doc3; + }, + get tr() { + selection = transaction.selection; + doc3 = transaction.doc; + storedMarks = transaction.storedMarks; + return transaction; + } + }; +} +var CommandManager = class { + constructor(props) { + this.editor = props.editor; + this.rawCommands = this.editor.extensionManager.commands; + this.customState = props.state; + } + get hasCustomState() { + return !!this.customState; + } + get state() { + return this.customState || this.editor.state; + } + get commands() { + const { rawCommands, editor, state } = this; + const { view } = editor; + const { tr } = state; + const props = this.buildProps(tr); + return Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + const method = (...args) => { + const callback = command2(...args)(props); + if (!tr.getMeta("preventDispatch") && !this.hasCustomState) { + view.dispatch(tr); + } + return callback; + }; + return [name, method]; + }) + ); + } + get chain() { + return () => this.createChain(); + } + get can() { + return () => this.createCan(); + } + createChain(startTr, shouldDispatch = true) { + const { rawCommands, editor, state } = this; + const { view } = editor; + const callbacks = []; + const hasStartTransaction = !!startTr; + const tr = startTr || state.tr; + const run3 = () => { + if (!hasStartTransaction && shouldDispatch && !tr.getMeta("preventDispatch") && !this.hasCustomState) { + view.dispatch(tr); + } + return callbacks.every((callback) => callback === true); + }; + const chain = { + ...Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + const chainedCommand = (...args) => { + const props = this.buildProps(tr, shouldDispatch); + const callback = command2(...args)(props); + callbacks.push(callback); + return chain; + }; + return [name, chainedCommand]; + }) + ), + run: run3 + }; + return chain; + } + createCan(startTr) { + const { rawCommands, state } = this; + const dispatch = false; + const tr = startTr || state.tr; + const props = this.buildProps(tr, dispatch); + const formattedCommands = Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })]; + }) + ); + return { + ...formattedCommands, + chain: () => this.createChain(tr, dispatch) + }; + } + buildProps(tr, shouldDispatch = true) { + const { rawCommands, editor, state } = this; + const { view } = editor; + const props = { + tr, + editor, + view, + state: createChainableState({ + state, + transaction: tr + }), + dispatch: shouldDispatch ? () => void 0 : void 0, + chain: () => this.createChain(tr, shouldDispatch), + can: () => this.createCan(tr), + get commands() { + return Object.fromEntries( + Object.entries(rawCommands).map(([name, command2]) => { + return [name, (...args) => command2(...args)(props)]; + }) + ); + } + }; + return props; + } +}; +var commands_exports = {}; +__export(commands_exports, { + blur: () => blur, + clearContent: () => clearContent, + clearNodes: () => clearNodes, + command: () => command, + createParagraphNear: () => createParagraphNear2, + cut: () => cut, + deleteCurrentNode: () => deleteCurrentNode, + deleteNode: () => deleteNode, + deleteRange: () => deleteRange2, + deleteSelection: () => deleteSelection2, + enter: () => enter, + exitCode: () => exitCode2, + extendMarkRange: () => extendMarkRange, + first: () => first, + focus: () => focus, + forEach: () => forEach, + insertContent: () => insertContent, + insertContentAt: () => insertContentAt, + joinBackward: () => joinBackward2, + joinDown: () => joinDown2, + joinForward: () => joinForward2, + joinItemBackward: () => joinItemBackward, + joinItemForward: () => joinItemForward, + joinTextblockBackward: () => joinTextblockBackward2, + joinTextblockForward: () => joinTextblockForward2, + joinUp: () => joinUp2, + keyboardShortcut: () => keyboardShortcut, + lift: () => lift3, + liftEmptyBlock: () => liftEmptyBlock2, + liftListItem: () => liftListItem2, + newlineInCode: () => newlineInCode2, + resetAttributes: () => resetAttributes, + scrollIntoView: () => scrollIntoView, + selectAll: () => selectAll2, + selectNodeBackward: () => selectNodeBackward2, + selectNodeForward: () => selectNodeForward2, + selectParentNode: () => selectParentNode2, + selectTextblockEnd: () => selectTextblockEnd2, + selectTextblockStart: () => selectTextblockStart2, + setContent: () => setContent, + setMark: () => setMark, + setMeta: () => setMeta, + setNode: () => setNode, + setNodeSelection: () => setNodeSelection, + setTextDirection: () => setTextDirection, + setTextSelection: () => setTextSelection, + sinkListItem: () => sinkListItem2, + splitBlock: () => splitBlock2, + splitListItem: () => splitListItem, + toggleList: () => toggleList, + toggleMark: () => toggleMark, + toggleNode: () => toggleNode, + toggleWrap: () => toggleWrap, + undoInputRule: () => undoInputRule, + unsetAllMarks: () => unsetAllMarks, + unsetMark: () => unsetMark, + unsetTextDirection: () => unsetTextDirection, + updateAttributes: () => updateAttributes, + wrapIn: () => wrapIn2, + wrapInList: () => wrapInList2 +}); +var blur = () => ({ editor, view }) => { + requestAnimationFrame(() => { + var _a; + if (!editor.isDestroyed) { + ; + view.dom.blur(); + (_a = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a.removeAllRanges(); + } + }); + return true; +}; +var clearContent = (emitUpdate = true) => ({ commands }) => { + return commands.setContent("", { emitUpdate }); +}; +var clearNodes = () => ({ state, tr, dispatch }) => { + const { selection } = tr; + const { ranges } = selection; + if (!dispatch) { + return true; + } + ranges.forEach(({ $from, $to }) => { + state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => { + if (node.type.isText) { + return; + } + const { doc: doc3, mapping } = tr; + const $mappedFrom = doc3.resolve(mapping.map(pos)); + const $mappedTo = doc3.resolve(mapping.map(pos + node.nodeSize)); + const nodeRange = $mappedFrom.blockRange($mappedTo); + if (!nodeRange) { + return; + } + const targetLiftDepth = liftTarget(nodeRange); + if (node.type.isTextblock) { + const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index()); + tr.setNodeMarkup(nodeRange.start, defaultType); + } + if (targetLiftDepth || targetLiftDepth === 0) { + tr.lift(nodeRange, targetLiftDepth); + } + }); + }); + return true; +}; +var command = (fn) => (props) => { + return fn(props); +}; +var createParagraphNear2 = () => ({ state, dispatch }) => { + return createParagraphNear(state, dispatch); +}; +var cut = (originRange, targetPos) => ({ editor, tr }) => { + const { state } = editor; + const contentSlice = state.doc.slice(originRange.from, originRange.to); + tr.deleteRange(originRange.from, originRange.to); + const newPos = tr.mapping.map(targetPos); + tr.insert(newPos, contentSlice.content); + tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0)))); + return true; +}; +var deleteCurrentNode = () => ({ tr, dispatch }) => { + const { selection } = tr; + const currentNode = selection.$anchor.node(); + if (currentNode.content.size > 0) { + return false; + } + const $pos = tr.selection.$anchor; + for (let depth = $pos.depth; depth > 0; depth -= 1) { + const node = $pos.node(depth); + if (node.type === currentNode.type) { + if (dispatch) { + const from = $pos.before(depth); + const to = $pos.after(depth); + tr.delete(from, to).scrollIntoView(); + } + return true; + } + } + return false; +}; +function getNodeType(nameOrType, schema) { + if (typeof nameOrType === "string") { + if (!schema.nodes[nameOrType]) { + throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`); + } + return schema.nodes[nameOrType]; + } + return nameOrType; +} +var deleteNode = (typeOrName) => ({ tr, state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + const $pos = tr.selection.$anchor; + for (let depth = $pos.depth; depth > 0; depth -= 1) { + const node = $pos.node(depth); + if (node.type === type) { + if (dispatch) { + const from = $pos.before(depth); + const to = $pos.after(depth); + tr.delete(from, to).scrollIntoView(); + } + return true; + } + } + return false; +}; +var deleteRange2 = (range) => ({ tr, dispatch }) => { + const { from, to } = range; + if (dispatch) { + tr.delete(from, to); + } + return true; +}; +var deleteSelection2 = () => ({ state, dispatch }) => { + return deleteSelection(state, dispatch); +}; +var enter = () => ({ commands }) => { + return commands.keyboardShortcut("Enter"); +}; +var exitCode2 = () => ({ state, dispatch }) => { + return exitCode(state, dispatch); +}; +function isRegExp(value) { + return Object.prototype.toString.call(value) === "[object RegExp]"; +} +function objectIncludes(object1, object2, options = { strict: true }) { + const keys2 = Object.keys(object2); + if (!keys2.length) { + return true; + } + return keys2.every((key) => { + if (options.strict) { + return object2[key] === object1[key]; + } + if (isRegExp(object2[key])) { + return object2[key].test(object1[key]); + } + return object2[key] === object1[key]; + }); +} +function findMarkInSet(marks, type, attributes = {}) { + return marks.find((item) => { + return item.type === type && objectIncludes( + // Only check equality for the attributes that are provided + Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])), + attributes + ); + }); +} +function isMarkInSet(marks, type, attributes = {}) { + return !!findMarkInSet(marks, type, attributes); +} +function getMarkRange($pos, type, attributes) { + var _a; + if (!$pos || !type) { + return; + } + let start = $pos.parent.childAfter($pos.parentOffset); + if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) { + start = $pos.parent.childBefore($pos.parentOffset); + } + if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) { + return; + } + attributes = attributes || ((_a = start.node.marks[0]) == null ? void 0 : _a.attrs); + const mark = findMarkInSet([...start.node.marks], type, attributes); + if (!mark) { + return; + } + let startIndex = start.index; + let startPos = $pos.start() + start.offset; + let endIndex = startIndex + 1; + let endPos = startPos + start.node.nodeSize; + while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) { + startIndex -= 1; + startPos -= $pos.parent.child(startIndex).nodeSize; + } + while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) { + endPos += $pos.parent.child(endIndex).nodeSize; + endIndex += 1; + } + return { + from: startPos, + to: endPos + }; +} +function getMarkType(nameOrType, schema) { + if (typeof nameOrType === "string") { + if (!schema.marks[nameOrType]) { + throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`); + } + return schema.marks[nameOrType]; + } + return nameOrType; +} +var extendMarkRange = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => { + const type = getMarkType(typeOrName, state.schema); + const { doc: doc3, selection } = tr; + const { $from, from, to } = selection; + if (dispatch) { + const range = getMarkRange($from, type, attributes); + if (range && range.from <= from && range.to >= to) { + const newSelection = TextSelection.create(doc3, range.from, range.to); + tr.setSelection(newSelection); + } + } + return true; +}; +var first = (commands) => (props) => { + const items = typeof commands === "function" ? commands(props) : commands; + for (let i = 0; i < items.length; i += 1) { + if (items[i](props)) { + return true; + } + } + return false; +}; +function isTextSelection(value) { + return value instanceof TextSelection; +} +function minMax(value = 0, min = 0, max = 0) { + return Math.min(Math.max(value, min), max); +} +function resolveFocusPosition(doc3, position = null) { + if (!position) { + return null; + } + const selectionAtStart = Selection.atStart(doc3); + const selectionAtEnd = Selection.atEnd(doc3); + if (position === "start" || position === true) { + return selectionAtStart; + } + if (position === "end") { + return selectionAtEnd; + } + const minPos = selectionAtStart.from; + const maxPos = selectionAtEnd.to; + if (position === "all") { + return TextSelection.create(doc3, minMax(0, minPos, maxPos), minMax(doc3.content.size, minPos, maxPos)); + } + return TextSelection.create(doc3, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos)); +} +function isAndroid() { + return navigator.platform === "Android" || /android/i.test(navigator.userAgent); +} +function isiOS() { + return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(navigator.platform) || // iPad on iOS 13 detection + navigator.userAgent.includes("Mac") && "ontouchend" in document; +} +function isSafari() { + return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false; +} +var focus = (position = null, options = {}) => ({ editor, view, tr, dispatch }) => { + options = { + scrollIntoView: true, + ...options + }; + const delayedFocus = () => { + if (isiOS() || isAndroid()) { + ; + view.dom.focus(); + } + if (isSafari() && !isiOS() && !isAndroid()) { + ; + view.dom.focus({ preventScroll: true }); + } + requestAnimationFrame(() => { + if (!editor.isDestroyed) { + view.focus(); + if (options == null ? void 0 : options.scrollIntoView) { + editor.commands.scrollIntoView(); + } + } + }); + }; + try { + if (view.hasFocus() && position === null || position === false) { + return true; + } + } catch { + return false; + } + if (dispatch && position === null && !isTextSelection(editor.state.selection)) { + delayedFocus(); + return true; + } + const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection; + const isSameSelection = editor.state.selection.eq(selection); + if (dispatch) { + if (!isSameSelection) { + tr.setSelection(selection); + } + if (isSameSelection && tr.storedMarks) { + tr.setStoredMarks(tr.storedMarks); + } + delayedFocus(); + } + return true; +}; +var forEach = (items, fn) => (props) => { + return items.every((item, index) => fn(item, { ...props, index })); +}; +var insertContent = (value, options) => ({ tr, commands }) => { + return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options); +}; +var removeWhitespaces = (node) => { + const children = node.childNodes; + for (let i = children.length - 1; i >= 0; i -= 1) { + const child = children[i]; + if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) { + node.removeChild(child); + } else if (child.nodeType === 1) { + removeWhitespaces(child); + } + } + return node; +}; +function elementFromString(value) { + if (typeof window === "undefined") { + throw new Error("[tiptap error]: there is no window object available, so this function cannot be used"); + } + const wrappedValue = `${value}`; + const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body; + return removeWhitespaces(html); +} +function createNodeFromContent(content, schema, options) { + if (content instanceof Node || content instanceof Fragment) { + return content; + } + options = { + slice: true, + parseOptions: {}, + ...options + }; + const isJSONContent = typeof content === "object" && content !== null; + const isTextContent = typeof content === "string"; + if (isJSONContent) { + try { + const isArrayContent = Array.isArray(content) && content.length > 0; + if (isArrayContent) { + return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item))); + } + const node = schema.nodeFromJSON(content); + if (options.errorOnInvalidContent) { + node.check(); + } + return node; + } catch (error) { + if (options.errorOnInvalidContent) { + throw new Error("[tiptap error]: Invalid JSON content", { cause: error }); + } + console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error); + return createNodeFromContent("", schema, options); + } + } + if (isTextContent) { + if (options.errorOnInvalidContent) { + let hasInvalidContent = false; + let invalidContent = ""; + const contentCheckSchema = new Schema({ + topNode: schema.spec.topNode, + marks: schema.spec.marks, + // Prosemirror's schemas are executed such that: the last to execute, matches last + // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle + nodes: schema.spec.nodes.append({ + __tiptap__private__unknown__catch__all__node: { + content: "inline*", + group: "block", + parseDOM: [ + { + tag: "*", + getAttrs: (e) => { + hasInvalidContent = true; + invalidContent = typeof e === "string" ? e : e.outerHTML; + return null; + } + } + ] + } + }) + }); + if (options.slice) { + DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions); + } else { + DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions); + } + if (options.errorOnInvalidContent && hasInvalidContent) { + throw new Error("[tiptap error]: Invalid HTML content", { + cause: new Error(`Invalid element found: ${invalidContent}`) + }); + } + } + const parser = DOMParser.fromSchema(schema); + if (options.slice) { + return parser.parseSlice(elementFromString(content), options.parseOptions).content; + } + return parser.parse(elementFromString(content), options.parseOptions); + } + return createNodeFromContent("", schema, options); +} +function selectionToInsertionEnd2(tr, startLen, bias) { + const last = tr.steps.length - 1; + if (last < startLen) { + return; + } + const step = tr.steps[last]; + if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { + return; + } + const map = tr.mapping.maps[last]; + let end = 0; + map.forEach((_from, _to, _newFrom, newTo) => { + if (end === 0) { + end = newTo; + } + }); + tr.setSelection(Selection.near(tr.doc.resolve(end), bias)); +} +var isFragment = (nodeOrFragment) => { + return !("type" in nodeOrFragment); +}; +var insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => { + var _a; + if (dispatch) { + options = { + parseOptions: editor.options.parseOptions, + updateSelection: true, + applyInputRules: false, + applyPasteRules: false, + ...options + }; + let content; + const emitContentError = (error) => { + editor.emit("contentError", { + editor, + error, + disableCollaboration: () => { + if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) { + ; + editor.storage.collaboration.isDisabled = true; + } + } + }); + }; + const parseOptions = { + preserveWhitespace: "full", + ...options.parseOptions + }; + if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) { + try { + createNodeFromContent(value, editor.schema, { + parseOptions, + errorOnInvalidContent: true + }); + } catch (e) { + emitContentError(e); + } + } + try { + content = createNodeFromContent(value, editor.schema, { + parseOptions, + errorOnInvalidContent: (_a = options.errorOnInvalidContent) != null ? _a : editor.options.enableContentCheck + }); + } catch (e) { + emitContentError(e); + return false; + } + let { from, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to }; + let isOnlyTextContent = true; + let isOnlyBlockContent = true; + const nodes = isFragment(content) ? content : [content]; + nodes.forEach((node) => { + node.check(); + isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false; + isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false; + }); + if (from === to && isOnlyBlockContent) { + const { parent } = tr.doc.resolve(from); + const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount; + if (isEmptyTextBlock) { + from -= 1; + to += 1; + } + } + let newContent; + if (isOnlyTextContent) { + if (Array.isArray(value)) { + newContent = value.map((v) => v.text || "").join(""); + } else if (value instanceof Fragment) { + let text = ""; + value.forEach((node) => { + if (node.text) { + text += node.text; + } + }); + newContent = text; + } else if (typeof value === "object" && !!value && !!value.text) { + newContent = value.text; + } else { + newContent = value; + } + tr.insertText(newContent, from, to); + } else { + newContent = content; + const $from = tr.doc.resolve(from); + const $fromNode = $from.node(); + const fromSelectionAtStart = $from.parentOffset === 0; + const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock; + const hasContent = $fromNode.content.size > 0; + if (fromSelectionAtStart && isTextSelection2 && hasContent) { + from = Math.max(0, from - 1); + } + tr.replaceWith(from, to, newContent); + } + if (options.updateSelection) { + selectionToInsertionEnd2(tr, tr.steps.length - 1, -1); + } + if (options.applyInputRules) { + tr.setMeta("applyInputRules", { from, text: newContent }); + } + if (options.applyPasteRules) { + tr.setMeta("applyPasteRules", { from, text: newContent }); + } + } + return true; +}; +var joinUp2 = () => ({ state, dispatch }) => { + return joinUp(state, dispatch); +}; +var joinDown2 = () => ({ state, dispatch }) => { + return joinDown(state, dispatch); +}; +var joinBackward2 = () => ({ state, dispatch }) => { + return joinBackward(state, dispatch); +}; +var joinForward2 = () => ({ state, dispatch }) => { + return joinForward(state, dispatch); +}; +var joinItemBackward = () => ({ state, dispatch, tr }) => { + try { + const point = joinPoint(state.doc, state.selection.$from.pos, -1); + if (point === null || point === void 0) { + return false; + } + tr.join(point, 2); + if (dispatch) { + dispatch(tr); + } + return true; + } catch { + return false; + } +}; +var joinItemForward = () => ({ state, dispatch, tr }) => { + try { + const point = joinPoint(state.doc, state.selection.$from.pos, 1); + if (point === null || point === void 0) { + return false; + } + tr.join(point, 2); + if (dispatch) { + dispatch(tr); + } + return true; + } catch { + return false; + } +}; +var joinTextblockBackward2 = () => ({ state, dispatch }) => { + return joinTextblockBackward(state, dispatch); +}; +var joinTextblockForward2 = () => ({ state, dispatch }) => { + return joinTextblockForward(state, dispatch); +}; +function isMacOS() { + return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; +} +function normalizeKeyName2(name) { + const parts = name.split(/-(?!$)/); + let result = parts[parts.length - 1]; + if (result === "Space") { + result = " "; + } + let alt; + let ctrl; + let shift2; + let meta; + for (let i = 0; i < parts.length - 1; i += 1) { + const mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) { + meta = true; + } else if (/^a(lt)?$/i.test(mod)) { + alt = true; + } else if (/^(c|ctrl|control)$/i.test(mod)) { + ctrl = true; + } else if (/^s(hift)?$/i.test(mod)) { + shift2 = true; + } else if (/^mod$/i.test(mod)) { + if (isiOS() || isMacOS()) { + meta = true; + } else { + ctrl = true; + } + } else { + throw new Error(`Unrecognized modifier name: ${mod}`); + } + } + if (alt) { + result = `Alt-${result}`; + } + if (ctrl) { + result = `Ctrl-${result}`; + } + if (meta) { + result = `Meta-${result}`; + } + if (shift2) { + result = `Shift-${result}`; + } + return result; +} +var keyboardShortcut = (name) => ({ editor, view, tr, dispatch }) => { + const keys2 = normalizeKeyName2(name).split(/-(?!$)/); + const key = keys2.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item)); + const event = new KeyboardEvent("keydown", { + key: key === "Space" ? " " : key, + altKey: keys2.includes("Alt"), + ctrlKey: keys2.includes("Ctrl"), + metaKey: keys2.includes("Meta"), + shiftKey: keys2.includes("Shift"), + bubbles: true, + cancelable: true + }); + const capturedTransaction = editor.captureTransaction(() => { + view.someProp("handleKeyDown", (f) => f(view, event)); + }); + capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => { + const newStep = step.map(tr.mapping); + if (newStep && dispatch) { + tr.maybeStep(newStep); + } + }); + return true; +}; +function isNodeActive(state, typeOrName, attributes = {}) { + const { from, to, empty: empty2 } = state.selection; + const type = typeOrName ? getNodeType(typeOrName, state.schema) : null; + const nodeRanges = []; + state.doc.nodesBetween(from, to, (node, pos) => { + if (node.isText) { + return; + } + const relativeFrom = Math.max(from, pos); + const relativeTo = Math.min(to, pos + node.nodeSize); + nodeRanges.push({ + node, + from: relativeFrom, + to: relativeTo + }); + }); + const selectionRange = to - from; + const matchedNodeRanges = nodeRanges.filter((nodeRange) => { + if (!type) { + return true; + } + return type.name === nodeRange.node.type.name; + }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false })); + if (empty2) { + return !!matchedNodeRanges.length; + } + const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0); + return range >= selectionRange; +} +var lift3 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + const isActive2 = isNodeActive(state, type, attributes); + if (!isActive2) { + return false; + } + return lift2(state, dispatch); +}; +var liftEmptyBlock2 = () => ({ state, dispatch }) => { + return liftEmptyBlock(state, dispatch); +}; +var liftListItem2 = (typeOrName) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return liftListItem(type)(state, dispatch); +}; +var newlineInCode2 = () => ({ state, dispatch }) => { + return newlineInCode(state, dispatch); +}; +function getSchemaTypeNameByName(name, schema) { + if (schema.nodes[name]) { + return "node"; + } + if (schema.marks[name]) { + return "mark"; + } + return null; +} +function deleteProps(obj, propOrProps) { + const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps; + return Object.keys(obj).reduce((newObj, prop) => { + if (!props.includes(prop)) { + newObj[prop] = obj[prop]; + } + return newObj; + }, {}); +} +var resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => { + let nodeType = null; + let markType = null; + const schemaType = getSchemaTypeNameByName( + typeof typeOrName === "string" ? typeOrName : typeOrName.name, + state.schema + ); + if (!schemaType) { + return false; + } + if (schemaType === "node") { + nodeType = getNodeType(typeOrName, state.schema); + } + if (schemaType === "mark") { + markType = getMarkType(typeOrName, state.schema); + } + let canReset = false; + tr.selection.ranges.forEach((range) => { + state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => { + if (nodeType && nodeType === node.type) { + canReset = true; + if (dispatch) { + tr.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes)); + } + } + if (markType && node.marks.length) { + node.marks.forEach((mark) => { + if (markType === mark.type) { + canReset = true; + if (dispatch) { + tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes))); + } + } + }); + } + }); + }); + return canReset; +}; +var scrollIntoView = () => ({ tr, dispatch }) => { + if (dispatch) { + tr.scrollIntoView(); + } + return true; +}; +var selectAll2 = () => ({ tr, dispatch }) => { + if (dispatch) { + const selection = new AllSelection(tr.doc); + tr.setSelection(selection); + } + return true; +}; +var selectNodeBackward2 = () => ({ state, dispatch }) => { + return selectNodeBackward(state, dispatch); +}; +var selectNodeForward2 = () => ({ state, dispatch }) => { + return selectNodeForward(state, dispatch); +}; +var selectParentNode2 = () => ({ state, dispatch }) => { + return selectParentNode(state, dispatch); +}; +var selectTextblockEnd2 = () => ({ state, dispatch }) => { + return selectTextblockEnd(state, dispatch); +}; +var selectTextblockStart2 = () => ({ state, dispatch }) => { + return selectTextblockStart(state, dispatch); +}; +function createDocument(content, schema, parseOptions = {}, options = {}) { + return createNodeFromContent(content, schema, { + slice: false, + parseOptions, + errorOnInvalidContent: options.errorOnInvalidContent + }); +} +var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr, dispatch, commands }) => { + const { doc: doc3 } = tr; + if (parseOptions.preserveWhitespace !== "full") { + const document2 = createDocument(content, editor.schema, parseOptions, { + errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck + }); + if (dispatch) { + tr.replaceWith(0, doc3.content.size, document2).setMeta("preventUpdate", !emitUpdate); + } + return true; + } + if (dispatch) { + tr.setMeta("preventUpdate", !emitUpdate); + } + return commands.insertContentAt({ from: 0, to: doc3.content.size }, content, { + parseOptions, + errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck + }); +}; +function getMarkAttributes(state, typeOrName) { + const type = getMarkType(typeOrName, state.schema); + const { from, to, empty: empty2 } = state.selection; + const marks = []; + if (empty2) { + if (state.storedMarks) { + marks.push(...state.storedMarks); + } + marks.push(...state.selection.$head.marks()); + } else { + state.doc.nodesBetween(from, to, (node) => { + marks.push(...node.marks); + }); + } + const mark = marks.find((markItem) => markItem.type.name === type.name); + if (!mark) { + return {}; + } + return { ...mark.attrs }; +} +function combineTransactionSteps(oldDoc, transactions) { + const transform = new Transform(oldDoc); + transactions.forEach((transaction) => { + transaction.steps.forEach((step) => { + transform.step(step); + }); + }); + return transform; +} +function defaultBlockAt2(match) { + for (let i = 0; i < match.edgeCount; i += 1) { + const { type } = match.edge(i); + if (type.isTextblock && !type.hasRequiredAttrs()) { + return type; + } + } + return null; +} +function findChildren(node, predicate) { + const nodesWithPos = []; + node.descendants((child, pos) => { + if (predicate(child)) { + nodesWithPos.push({ + node: child, + pos + }); + } + }); + return nodesWithPos; +} +function findChildrenInRange(node, range, predicate) { + const nodesWithPos = []; + node.nodesBetween(range.from, range.to, (child, pos) => { + if (predicate(child)) { + nodesWithPos.push({ + node: child, + pos + }); + } + }); + return nodesWithPos; +} +function findParentNodeClosestToPos($pos, predicate) { + for (let i = $pos.depth; i > 0; i -= 1) { + const node = $pos.node(i); + if (predicate(node)) { + return { + pos: i > 0 ? $pos.before(i) : 0, + start: $pos.start(i), + depth: i, + node + }; + } + } +} +function findParentNode(predicate) { + return (selection) => findParentNodeClosestToPos(selection.$from, predicate); +} +function getExtensionField(extension, field, context) { + if (extension.config[field] === void 0 && extension.parent) { + return getExtensionField(extension.parent, field, context); + } + if (typeof extension.config[field] === "function") { + const value = extension.config[field].bind({ + ...context, + parent: extension.parent ? getExtensionField(extension.parent, field, context) : null + }); + return value; + } + return extension.config[field]; +} +function flattenExtensions(extensions) { + return extensions.map((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + const addExtensions = getExtensionField(extension, "addExtensions", context); + if (addExtensions) { + return [extension, ...flattenExtensions(addExtensions())]; + } + return extension; + }).flat(10); +} +function getHTMLFromFragment(fragment, schema) { + const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment); + const temporaryDocument = document.implementation.createHTMLDocument(); + const container = temporaryDocument.createElement("div"); + container.appendChild(documentFragment); + return container.innerHTML; +} +function isFunction(value) { + return typeof value === "function"; +} +function callOrReturn(value, context = void 0, ...props) { + if (isFunction(value)) { + if (context) { + return value.bind(context)(...props); + } + return value(...props); + } + return value; +} +function isEmptyObject(value = {}) { + return Object.keys(value).length === 0 && value.constructor === Object; +} +function splitExtensions(extensions) { + const baseExtensions = extensions.filter((extension) => extension.type === "extension"); + const nodeExtensions = extensions.filter((extension) => extension.type === "node"); + const markExtensions = extensions.filter((extension) => extension.type === "mark"); + return { + baseExtensions, + nodeExtensions, + markExtensions + }; +} +function getAttributesFromExtensions(extensions) { + const extensionAttributes = []; + const { nodeExtensions, markExtensions } = splitExtensions(extensions); + const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]; + const defaultAttribute = { + default: null, + validate: void 0, + rendered: true, + renderHTML: null, + parseHTML: null, + keepOnSplit: true, + isRequired: false + }; + extensions.forEach((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage, + extensions: nodeAndMarkExtensions + }; + const addGlobalAttributes = getExtensionField( + extension, + "addGlobalAttributes", + context + ); + if (!addGlobalAttributes) { + return; + } + const globalAttributes = addGlobalAttributes(); + globalAttributes.forEach((globalAttribute) => { + globalAttribute.types.forEach((type) => { + Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => { + extensionAttributes.push({ + type, + name, + attribute: { + ...defaultAttribute, + ...attribute + } + }); + }); + }); + }); + }); + nodeAndMarkExtensions.forEach((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + const addAttributes = getExtensionField( + extension, + "addAttributes", + context + ); + if (!addAttributes) { + return; + } + const attributes = addAttributes(); + Object.entries(attributes).forEach(([name, attribute]) => { + const mergedAttr = { + ...defaultAttribute, + ...attribute + }; + if (typeof (mergedAttr == null ? void 0 : mergedAttr.default) === "function") { + mergedAttr.default = mergedAttr.default(); + } + if ((mergedAttr == null ? void 0 : mergedAttr.isRequired) && (mergedAttr == null ? void 0 : mergedAttr.default) === void 0) { + delete mergedAttr.default; + } + extensionAttributes.push({ + type: extension.name, + name, + attribute: mergedAttr + }); + }); + }); + return extensionAttributes; +} +function mergeAttributes(...objects) { + return objects.filter((item) => !!item).reduce((items, item) => { + const mergedAttributes = { ...items }; + Object.entries(item).forEach(([key, value]) => { + const exists = mergedAttributes[key]; + if (!exists) { + mergedAttributes[key] = value; + return; + } + if (key === "class") { + const valueClasses = value ? String(value).split(" ") : []; + const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : []; + const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass)); + mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" "); + } else if (key === "style") { + const newStyles = value ? value.split(";").map((style2) => style2.trim()).filter(Boolean) : []; + const existingStyles = mergedAttributes[key] ? mergedAttributes[key].split(";").map((style2) => style2.trim()).filter(Boolean) : []; + const styleMap = /* @__PURE__ */ new Map(); + existingStyles.forEach((style2) => { + const [property, val] = style2.split(":").map((part) => part.trim()); + styleMap.set(property, val); + }); + newStyles.forEach((style2) => { + const [property, val] = style2.split(":").map((part) => part.trim()); + styleMap.set(property, val); + }); + mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; "); + } else { + mergedAttributes[key] = value; + } + }); + return mergedAttributes; + }, {}); +} +function getRenderedAttributes(nodeOrMark, extensionAttributes) { + return extensionAttributes.filter((attribute) => attribute.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => { + if (!item.attribute.renderHTML) { + return { + [item.name]: nodeOrMark.attrs[item.name] + }; + } + return item.attribute.renderHTML(nodeOrMark.attrs) || {}; + }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {}); +} +function fromString(value) { + if (typeof value !== "string") { + return value; + } + if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) { + return Number(value); + } + if (value === "true") { + return true; + } + if (value === "false") { + return false; + } + return value; +} +function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) { + if ("style" in parseRule) { + return parseRule; + } + return { + ...parseRule, + getAttrs: (node) => { + const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs; + if (oldAttributes === false) { + return false; + } + const newAttributes = extensionAttributes.reduce((items, item) => { + const value = item.attribute.parseHTML ? item.attribute.parseHTML(node) : fromString(node.getAttribute(item.name)); + if (value === null || value === void 0) { + return items; + } + return { + ...items, + [item.name]: value + }; + }, {}); + return { ...oldAttributes, ...newAttributes }; + } + }; +} +function cleanUpSchemaItem(data) { + return Object.fromEntries( + // @ts-ignore + Object.entries(data).filter(([key, value]) => { + if (key === "attrs" && isEmptyObject(value)) { + return false; + } + return value !== null && value !== void 0; + }) + ); +} +function buildAttributeSpec(extensionAttribute) { + var _a, _b; + const spec = {}; + if (!((_a = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _a.isRequired) && "default" in ((extensionAttribute == null ? void 0 : extensionAttribute.attribute) || {})) { + spec.default = extensionAttribute.attribute.default; + } + if (((_b = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _b.validate) !== void 0) { + spec.validate = extensionAttribute.attribute.validate; + } + return [extensionAttribute.name, spec]; +} +function getSchemaByResolvedExtensions(extensions, editor) { + var _a; + const allAttributes = getAttributesFromExtensions(extensions); + const { nodeExtensions, markExtensions } = splitExtensions(extensions); + const topNode = (_a = nodeExtensions.find((extension) => getExtensionField(extension, "topNode"))) == null ? void 0 : _a.name; + const nodes = Object.fromEntries( + nodeExtensions.map((extension) => { + const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage, + editor + }; + const extraNodeFields = extensions.reduce((fields, e) => { + const extendNodeSchema = getExtensionField(e, "extendNodeSchema", context); + return { + ...fields, + ...extendNodeSchema ? extendNodeSchema(extension) : {} + }; + }, {}); + const schema = cleanUpSchemaItem({ + ...extraNodeFields, + content: callOrReturn(getExtensionField(extension, "content", context)), + marks: callOrReturn(getExtensionField(extension, "marks", context)), + group: callOrReturn(getExtensionField(extension, "group", context)), + inline: callOrReturn(getExtensionField(extension, "inline", context)), + atom: callOrReturn(getExtensionField(extension, "atom", context)), + selectable: callOrReturn(getExtensionField(extension, "selectable", context)), + draggable: callOrReturn(getExtensionField(extension, "draggable", context)), + code: callOrReturn(getExtensionField(extension, "code", context)), + whitespace: callOrReturn(getExtensionField(extension, "whitespace", context)), + linebreakReplacement: callOrReturn( + getExtensionField(extension, "linebreakReplacement", context) + ), + defining: callOrReturn(getExtensionField(extension, "defining", context)), + isolating: callOrReturn(getExtensionField(extension, "isolating", context)), + attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) + }); + const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); + if (parseHTML) { + schema.parseDOM = parseHTML.map( + (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) + ); + } + const renderHTML = getExtensionField(extension, "renderHTML", context); + if (renderHTML) { + schema.toDOM = (node) => renderHTML({ + node, + HTMLAttributes: getRenderedAttributes(node, extensionAttributes) + }); + } + const renderText = getExtensionField(extension, "renderText", context); + if (renderText) { + schema.toText = renderText; + } + return [extension.name, schema]; + }) + ); + const marks = Object.fromEntries( + markExtensions.map((extension) => { + const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage, + editor + }; + const extraMarkFields = extensions.reduce((fields, e) => { + const extendMarkSchema = getExtensionField(e, "extendMarkSchema", context); + return { + ...fields, + ...extendMarkSchema ? extendMarkSchema(extension) : {} + }; + }, {}); + const schema = cleanUpSchemaItem({ + ...extraMarkFields, + inclusive: callOrReturn(getExtensionField(extension, "inclusive", context)), + excludes: callOrReturn(getExtensionField(extension, "excludes", context)), + group: callOrReturn(getExtensionField(extension, "group", context)), + spanning: callOrReturn(getExtensionField(extension, "spanning", context)), + code: callOrReturn(getExtensionField(extension, "code", context)), + attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) + }); + const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); + if (parseHTML) { + schema.parseDOM = parseHTML.map( + (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) + ); + } + const renderHTML = getExtensionField(extension, "renderHTML", context); + if (renderHTML) { + schema.toDOM = (mark) => renderHTML({ + mark, + HTMLAttributes: getRenderedAttributes(mark, extensionAttributes) + }); + } + return [extension.name, schema]; + }) + ); + return new Schema({ + topNode, + nodes, + marks + }); +} +function findDuplicates(items) { + const filtered = items.filter((el, index) => items.indexOf(el) !== index); + return Array.from(new Set(filtered)); +} +function sortExtensions(extensions) { + const defaultPriority = 100; + return extensions.sort((a, b) => { + const priorityA = getExtensionField(a, "priority") || defaultPriority; + const priorityB = getExtensionField(b, "priority") || defaultPriority; + if (priorityA > priorityB) { + return -1; + } + if (priorityA < priorityB) { + return 1; + } + return 0; + }); +} +function resolveExtensions(extensions) { + const resolvedExtensions = sortExtensions(flattenExtensions(extensions)); + const duplicatedNames = findDuplicates(resolvedExtensions.map((extension) => extension.name)); + if (duplicatedNames.length) { + console.warn( + `[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.` + ); + } + return resolvedExtensions; +} +function getSchema(extensions, editor) { + const resolvedExtensions = resolveExtensions(extensions); + return getSchemaByResolvedExtensions(resolvedExtensions, editor); +} +function generateHTML(doc3, extensions) { + const schema = getSchema(extensions); + const contentNode = Node.fromJSON(schema, doc3); + return getHTMLFromFragment(contentNode.content, schema); +} +function generateJSON(html, extensions) { + const schema = getSchema(extensions); + const dom = elementFromString(html); + return DOMParser.fromSchema(schema).parse(dom).toJSON(); +} +function getTextBetween(startNode, range, options) { + const { from, to } = range; + const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; + let text = ""; + startNode.nodesBetween(from, to, (node, pos, parent, index) => { + var _a; + if (node.isBlock && pos > from) { + text += blockSeparator; + } + const textSerializer = textSerializers == null ? void 0 : textSerializers[node.type.name]; + if (textSerializer) { + if (parent) { + text += textSerializer({ + node, + pos, + parent, + index, + range + }); + } + return false; + } + if (node.isText) { + text += (_a = node == null ? void 0 : node.text) == null ? void 0 : _a.slice(Math.max(from, pos) - pos, to - pos); + } + }); + return text; +} +function getText2(node, options) { + const range = { + from: 0, + to: node.content.size + }; + return getTextBetween(node, range, options); +} +function getTextSerializersFromSchema(schema) { + return Object.fromEntries( + Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText]) + ); +} +function generateText(doc3, extensions, options) { + const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; + const schema = getSchema(extensions); + const contentNode = Node.fromJSON(schema, doc3); + return getText2(contentNode, { + blockSeparator, + textSerializers: { + ...getTextSerializersFromSchema(schema), + ...textSerializers + } + }); +} +function getNodeAttributes(state, typeOrName) { + const type = getNodeType(typeOrName, state.schema); + const { from, to } = state.selection; + const nodes = []; + state.doc.nodesBetween(from, to, (node2) => { + nodes.push(node2); + }); + const node = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name); + if (!node) { + return {}; + } + return { ...node.attrs }; +} +function getAttributes(state, typeOrName) { + const schemaType = getSchemaTypeNameByName( + typeof typeOrName === "string" ? typeOrName : typeOrName.name, + state.schema + ); + if (schemaType === "node") { + return getNodeAttributes(state, typeOrName); + } + if (schemaType === "mark") { + return getMarkAttributes(state, typeOrName); + } + return {}; +} +function removeDuplicates(array, by = JSON.stringify) { + const seen = {}; + return array.filter((item) => { + const key = by(item); + return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true; + }); +} +function simplifyChangedRanges(changes) { + const uniqueChanges = removeDuplicates(changes); + return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => { + const rest = uniqueChanges.filter((_, i) => i !== index); + return !rest.some((otherChange) => { + return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to; + }); + }); +} +function getChangedRanges(transform) { + const { mapping, steps } = transform; + const changes = []; + mapping.maps.forEach((stepMap, index) => { + const ranges = []; + if (!stepMap.ranges.length) { + const { from, to } = steps[index]; + if (from === void 0 || to === void 0) { + return; + } + ranges.push({ from, to }); + } else { + stepMap.forEach((from, to) => { + ranges.push({ from, to }); + }); + } + ranges.forEach(({ from, to }) => { + const newStart = mapping.slice(index).map(from, -1); + const newEnd = mapping.slice(index).map(to); + const oldStart = mapping.invert().map(newStart, -1); + const oldEnd = mapping.invert().map(newEnd); + changes.push({ + oldRange: { + from: oldStart, + to: oldEnd + }, + newRange: { + from: newStart, + to: newEnd + } + }); + }); + }); + return simplifyChangedRanges(changes); +} +function getDebugJSON(node, startOffset = 0) { + const isTopNode = node.type === node.type.schema.topNodeType; + const increment = isTopNode ? 0 : 1; + const from = startOffset; + const to = from + node.nodeSize; + const marks = node.marks.map((mark) => { + const output2 = { + type: mark.type.name + }; + if (Object.keys(mark.attrs).length) { + output2.attrs = { ...mark.attrs }; + } + return output2; + }); + const attrs = { ...node.attrs }; + const output = { + type: node.type.name, + from, + to + }; + if (Object.keys(attrs).length) { + output.attrs = attrs; + } + if (marks.length) { + output.marks = marks; + } + if (node.content.childCount) { + output.content = []; + node.forEach((child, offset) => { + var _a; + (_a = output.content) == null ? void 0 : _a.push(getDebugJSON(child, startOffset + offset + increment)); + }); + } + if (node.text) { + output.text = node.text; + } + return output; +} +function getMarksBetween(from, to, doc3) { + const marks = []; + if (from === to) { + doc3.resolve(from).marks().forEach((mark) => { + const $pos = doc3.resolve(from); + const range = getMarkRange($pos, mark.type); + if (!range) { + return; + } + marks.push({ + mark, + ...range + }); + }); + } else { + doc3.nodesBetween(from, to, (node, pos) => { + if (!node || (node == null ? void 0 : node.nodeSize) === void 0) { + return; + } + marks.push( + ...node.marks.map((mark) => ({ + from: pos, + to: pos + node.nodeSize, + mark + })) + ); + }); + } + return marks; +} +var getNodeAtPosition = (state, typeOrName, pos, maxDepth = 20) => { + const $pos = state.doc.resolve(pos); + let currentDepth = maxDepth; + let node = null; + while (currentDepth > 0 && node === null) { + const currentNode = $pos.node(currentDepth); + if ((currentNode == null ? void 0 : currentNode.type.name) === typeOrName) { + node = currentNode; + } else { + currentDepth -= 1; + } + } + return [node, currentDepth]; +}; +function getSchemaTypeByName(name, schema) { + return schema.nodes[name] || schema.marks[name] || null; +} +function getSplittedAttributes(extensionAttributes, typeName, attributes) { + return Object.fromEntries( + Object.entries(attributes).filter(([name]) => { + const extensionAttribute = extensionAttributes.find((item) => { + return item.type === typeName && item.name === name; + }); + if (!extensionAttribute) { + return false; + } + return extensionAttribute.attribute.keepOnSplit; + }) + ); +} +var getTextContentFromNodes = ($from, maxMatch = 500) => { + let textBefore = ""; + const sliceEndPos = $from.parentOffset; + $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => { + var _a, _b; + const chunk = ((_b = (_a = node.type.spec).toText) == null ? void 0 : _b.call(_a, { + node, + pos, + parent, + index + })) || node.textContent || "%leaf%"; + textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos)); + }); + return textBefore; +}; +function isMarkActive(state, typeOrName, attributes = {}) { + const { empty: empty2, ranges } = state.selection; + const type = typeOrName ? getMarkType(typeOrName, state.schema) : null; + if (empty2) { + return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => { + if (!type) { + return true; + } + return type.name === mark.type.name; + }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false })); + } + let selectionRange = 0; + const markRanges = []; + ranges.forEach(({ $from, $to }) => { + const from = $from.pos; + const to = $to.pos; + state.doc.nodesBetween(from, to, (node, pos) => { + if (!node.isText && !node.marks.length) { + return; + } + const relativeFrom = Math.max(from, pos); + const relativeTo = Math.min(to, pos + node.nodeSize); + const range2 = relativeTo - relativeFrom; + selectionRange += range2; + markRanges.push( + ...node.marks.map((mark) => ({ + mark, + from: relativeFrom, + to: relativeTo + })) + ); + }); + }); + if (selectionRange === 0) { + return false; + } + const matchedRange = markRanges.filter((markRange) => { + if (!type) { + return true; + } + return type.name === markRange.mark.type.name; + }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); + const excludedRange = markRanges.filter((markRange) => { + if (!type) { + return true; + } + return markRange.mark.type !== type && markRange.mark.type.excludes(type); + }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); + const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange; + return range >= selectionRange; +} +function isActive(state, name, attributes = {}) { + if (!name) { + return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes); + } + const schemaType = getSchemaTypeNameByName(name, state.schema); + if (schemaType === "node") { + return isNodeActive(state, name, attributes); + } + if (schemaType === "mark") { + return isMarkActive(state, name, attributes); + } + return false; +} +var isAtEndOfNode = (state, nodeType) => { + const { $from, $to, $anchor } = state.selection; + if (nodeType) { + const parentNode2 = findParentNode((node) => node.type.name === nodeType)(state.selection); + if (!parentNode2) { + return false; + } + const $parentPos = state.doc.resolve(parentNode2.pos + 1); + if ($anchor.pos + 1 === $parentPos.end()) { + return true; + } + return false; + } + if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) { + return false; + } + return true; +}; +var isAtStartOfNode = (state) => { + const { $from, $to } = state.selection; + if ($from.parentOffset > 0 || $from.pos !== $to.pos) { + return false; + } + return true; +}; +function isExtensionRulesEnabled(extension, enabled) { + if (Array.isArray(enabled)) { + return enabled.some((enabledExtension) => { + const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name; + return name === extension.name; + }); + } + return enabled; +} +function isList(name, extensions) { + const { nodeExtensions } = splitExtensions(extensions); + const extension = nodeExtensions.find((item) => item.name === name); + if (!extension) { + return false; + } + const context = { + name: extension.name, + options: extension.options, + storage: extension.storage + }; + const group = callOrReturn(getExtensionField(extension, "group", context)); + if (typeof group !== "string") { + return false; + } + return group.split(" ").includes("list"); +} +function isNodeEmpty(node, { + checkChildren = true, + ignoreWhitespace = false +} = {}) { + var _a; + if (ignoreWhitespace) { + if (node.type.name === "hardBreak") { + return true; + } + if (node.isText) { + return /^\s*$/m.test((_a = node.text) != null ? _a : ""); + } + } + if (node.isText) { + return !node.text; + } + if (node.isAtom || node.isLeaf) { + return false; + } + if (node.content.childCount === 0) { + return true; + } + if (checkChildren) { + let isContentEmpty = true; + node.content.forEach((childNode) => { + if (isContentEmpty === false) { + return; + } + if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) { + isContentEmpty = false; + } + }); + return isContentEmpty; + } + return false; +} +function isNodeSelection(value) { + return value instanceof NodeSelection; +} +var MappablePosition = class _MappablePosition { + constructor(position) { + this.position = position; + } + /** + * Creates a MappablePosition from a JSON object. + */ + static fromJSON(json) { + return new _MappablePosition(json.position); + } + /** + * Converts the MappablePosition to a JSON object. + */ + toJSON() { + return { + position: this.position + }; + } +}; +function getUpdatedPosition(position, transaction) { + const mapResult = transaction.mapping.mapResult(position.position); + return { + position: new MappablePosition(mapResult.pos), + mapResult + }; +} +function createMappablePosition(position) { + return new MappablePosition(position); +} +function posToDOMRect(view, from, to) { + const minPos = 0; + const maxPos = view.state.doc.content.size; + const resolvedFrom = minMax(from, minPos, maxPos); + const resolvedEnd = minMax(to, minPos, maxPos); + const start = view.coordsAtPos(resolvedFrom); + const end = view.coordsAtPos(resolvedEnd, -1); + const top = Math.min(start.top, end.top); + const bottom = Math.max(start.bottom, end.bottom); + const left = Math.min(start.left, end.left); + const right = Math.max(start.right, end.right); + const width = right - left; + const height = bottom - top; + const x = left; + const y = top; + const data = { + top, + bottom, + left, + right, + width, + height, + x, + y + }; + return { + ...data, + toJSON: () => data + }; +} +function rewriteUnknownContentInner({ + json, + validMarks, + validNodes, + options, + rewrittenContent = [] +}) { + if (json.marks && Array.isArray(json.marks)) { + json.marks = json.marks.filter((mark) => { + const name = typeof mark === "string" ? mark : mark.type; + if (validMarks.has(name)) { + return true; + } + rewrittenContent.push({ + original: JSON.parse(JSON.stringify(mark)), + unsupported: name + }); + return false; + }); + } + if (json.content && Array.isArray(json.content)) { + json.content = json.content.map( + (value) => rewriteUnknownContentInner({ + json: value, + validMarks, + validNodes, + options, + rewrittenContent + }).json + ).filter((a) => a !== null && a !== void 0); + } + if (json.type && !validNodes.has(json.type)) { + rewrittenContent.push({ + original: JSON.parse(JSON.stringify(json)), + unsupported: json.type + }); + if (json.content && Array.isArray(json.content) && (options == null ? void 0 : options.fallbackToParagraph) !== false) { + json.type = "paragraph"; + return { + json, + rewrittenContent + }; + } + return { + json: null, + rewrittenContent + }; + } + return { json, rewrittenContent }; +} +function rewriteUnknownContent(json, schema, options) { + return rewriteUnknownContentInner({ + json, + validNodes: new Set(Object.keys(schema.nodes)), + validMarks: new Set(Object.keys(schema.marks)), + options + }); +} +function canSetMark(state, tr, newMarkType) { + var _a; + const { selection } = tr; + let cursor = null; + if (isTextSelection(selection)) { + cursor = selection.$cursor; + } + if (cursor) { + const currentMarks = (_a = state.storedMarks) != null ? _a : cursor.marks(); + const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType); + return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType))); + } + const { ranges } = selection; + return ranges.some(({ $from, $to }) => { + let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false; + state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => { + if (someNodeSupportsMark) { + return false; + } + if (node.isInline) { + const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType); + const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType)); + someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType; + } + return !someNodeSupportsMark; + }); + return someNodeSupportsMark; + }); +} +var setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => { + const { selection } = tr; + const { empty: empty2, ranges } = selection; + const type = getMarkType(typeOrName, state.schema); + if (dispatch) { + if (empty2) { + const oldAttributes = getMarkAttributes(state, type); + tr.addStoredMark( + type.create({ + ...oldAttributes, + ...attributes + }) + ); + } else { + ranges.forEach((range) => { + const from = range.$from.pos; + const to = range.$to.pos; + state.doc.nodesBetween(from, to, (node, pos) => { + const trimmedFrom = Math.max(pos, from); + const trimmedTo = Math.min(pos + node.nodeSize, to); + const someHasMark = node.marks.find((mark) => mark.type === type); + if (someHasMark) { + node.marks.forEach((mark) => { + if (type === mark.type) { + tr.addMark( + trimmedFrom, + trimmedTo, + type.create({ + ...mark.attrs, + ...attributes + }) + ); + } + }); + } else { + tr.addMark(trimmedFrom, trimmedTo, type.create(attributes)); + } + }); + }); + } + } + return canSetMark(state, tr, type); +}; +var setMeta = (key, value) => ({ tr }) => { + tr.setMeta(key, value); + return true; +}; +var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => { + const type = getNodeType(typeOrName, state.schema); + let attributesToCopy; + if (state.selection.$anchor.sameParent(state.selection.$head)) { + attributesToCopy = state.selection.$anchor.parent.attrs; + } + if (!type.isTextblock) { + console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'); + return false; + } + return chain().command(({ commands }) => { + const canSetBlock = setBlockType2(type, { ...attributesToCopy, ...attributes })(state); + if (canSetBlock) { + return true; + } + return commands.clearNodes(); + }).command(({ state: updatedState }) => { + return setBlockType2(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch); + }).run(); +}; +var setNodeSelection = (position) => ({ tr, dispatch }) => { + if (dispatch) { + const { doc: doc3 } = tr; + const from = minMax(position, 0, doc3.content.size); + const selection = NodeSelection.create(doc3, from); + tr.setSelection(selection); + } + return true; +}; +var setTextDirection = (direction, position) => ({ tr, state, dispatch }) => { + const { selection } = state; + let from; + let to; + if (typeof position === "number") { + from = position; + to = position; + } else if (position && "from" in position && "to" in position) { + from = position.from; + to = position.to; + } else { + from = selection.from; + to = selection.to; + } + if (dispatch) { + tr.doc.nodesBetween(from, to, (node, pos) => { + if (node.isText) { + return; + } + tr.setNodeMarkup(pos, void 0, { + ...node.attrs, + dir: direction + }); + }); + } + return true; +}; +var setTextSelection = (position) => ({ tr, dispatch }) => { + if (dispatch) { + const { doc: doc3 } = tr; + const { from, to } = typeof position === "number" ? { from: position, to: position } : position; + const minPos = TextSelection.atStart(doc3).from; + const maxPos = TextSelection.atEnd(doc3).to; + const resolvedFrom = minMax(from, minPos, maxPos); + const resolvedEnd = minMax(to, minPos, maxPos); + const selection = TextSelection.create(doc3, resolvedFrom, resolvedEnd); + tr.setSelection(selection); + } + return true; +}; +var sinkListItem2 = (typeOrName) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return sinkListItem(type)(state, dispatch); +}; +function ensureMarks(state, splittableMarks) { + const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks(); + if (marks) { + const filteredMarks = marks.filter((mark) => splittableMarks == null ? void 0 : splittableMarks.includes(mark.type.name)); + state.tr.ensureMarks(filteredMarks); + } +} +var splitBlock2 = ({ keepMarks = true } = {}) => ({ tr, state, dispatch, editor }) => { + const { selection, doc: doc3 } = tr; + const { $from, $to } = selection; + const extensionAttributes = editor.extensionManager.attributes; + const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs); + if (selection instanceof NodeSelection && selection.node.isBlock) { + if (!$from.parentOffset || !canSplit(doc3, $from.pos)) { + return false; + } + if (dispatch) { + if (keepMarks) { + ensureMarks(state, editor.extensionManager.splittableMarks); + } + tr.split($from.pos).scrollIntoView(); + } + return true; + } + if (!$from.parent.isBlock) { + return false; + } + const atEnd = $to.parentOffset === $to.parent.content.size; + const deflt = $from.depth === 0 ? void 0 : defaultBlockAt2($from.node(-1).contentMatchAt($from.indexAfter(-1))); + let types = atEnd && deflt ? [ + { + type: deflt, + attrs: newAttributes + } + ] : void 0; + let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types); + if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) { + can = true; + types = deflt ? [ + { + type: deflt, + attrs: newAttributes + } + ] : void 0; + } + if (dispatch) { + if (can) { + if (selection instanceof TextSelection) { + tr.deleteSelection(); + } + tr.split(tr.mapping.map($from.pos), 1, types); + if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) { + const first2 = tr.mapping.map($from.before()); + const $first = tr.doc.resolve(first2); + if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) { + tr.setNodeMarkup(tr.mapping.map($from.before()), deflt); + } + } + } + if (keepMarks) { + ensureMarks(state, editor.extensionManager.splittableMarks); + } + tr.scrollIntoView(); + } + return can; +}; +var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr, state, dispatch, editor }) => { + var _a; + const type = getNodeType(typeOrName, state.schema); + const { $from, $to } = state.selection; + const node = state.selection.node; + if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) { + return false; + } + const grandParent = $from.node(-1); + if (grandParent.type !== type) { + return false; + } + const extensionAttributes = editor.extensionManager.attributes; + if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) { + if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) { + return false; + } + if (dispatch) { + let wrap2 = Fragment.empty; + const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3; + for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) { + wrap2 = Fragment.from($from.node(d).copy(wrap2)); + } + const depthAfter = ( + // eslint-disable-next-line no-nested-ternary + $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3 + ); + const newNextTypeAttributes2 = { + ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), + ...overrideAttrs + }; + const nextType2 = ((_a = type.contentMatch.defaultType) == null ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0; + wrap2 = wrap2.append(Fragment.from(type.createAndFill(null, nextType2) || void 0)); + const start = $from.before($from.depth - (depthBefore - 1)); + tr.replace(start, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0)); + let sel = -1; + tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => { + if (sel > -1) { + return false; + } + if (n.isTextblock && n.content.size === 0) { + sel = pos + 1; + } + }); + if (sel > -1) { + tr.setSelection(TextSelection.near(tr.doc.resolve(sel))); + } + tr.scrollIntoView(); + } + return true; + } + const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null; + const newTypeAttributes = { + ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs), + ...overrideAttrs + }; + const newNextTypeAttributes = { + ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), + ...overrideAttrs + }; + tr.delete($from.pos, $to.pos); + const types = nextType ? [ + { type, attrs: newTypeAttributes }, + { type: nextType, attrs: newNextTypeAttributes } + ] : [{ type, attrs: newTypeAttributes }]; + if (!canSplit(tr.doc, $from.pos, 2)) { + return false; + } + if (dispatch) { + const { selection, storedMarks } = state; + const { splittableMarks } = editor.extensionManager; + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + tr.split($from.pos, 2, types).scrollIntoView(); + if (!marks || !dispatch) { + return true; + } + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr.ensureMarks(filteredMarks); + } + return true; +}; +var joinListBackwards = (tr, listType) => { + const list = findParentNode((node) => node.type === listType)(tr.selection); + if (!list) { + return true; + } + const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth); + if (before === void 0) { + return true; + } + const nodeBefore = tr.doc.nodeAt(before); + const canJoinBackwards = list.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr.doc, list.pos); + if (!canJoinBackwards) { + return true; + } + tr.join(list.pos); + return true; +}; +var joinListForwards = (tr, listType) => { + const list = findParentNode((node) => node.type === listType)(tr.selection); + if (!list) { + return true; + } + const after = tr.doc.resolve(list.start).after(list.depth); + if (after === void 0) { + return true; + } + const nodeAfter = tr.doc.nodeAt(after); + const canJoinForwards = list.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr.doc, after); + if (!canJoinForwards) { + return true; + } + tr.join(after); + return true; +}; +var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr, state, dispatch, chain, commands, can }) => { + const { extensions, splittableMarks } = editor.extensionManager; + const listType = getNodeType(listTypeOrName, state.schema); + const itemType = getNodeType(itemTypeOrName, state.schema); + const { selection, storedMarks } = state; + const { $from, $to } = selection; + const range = $from.blockRange($to); + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + if (!range) { + return false; + } + const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection); + if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) { + if (parentList.node.type === listType) { + return commands.liftListItem(itemType); + } + if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) { + return chain().command(() => { + tr.setNodeMarkup(parentList.pos, listType); + return true; + }).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run(); + } + } + if (!keepMarks || !marks || !dispatch) { + return chain().command(() => { + const canWrapInList = can().wrapInList(listType, attributes); + if (canWrapInList) { + return true; + } + return commands.clearNodes(); + }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run(); + } + return chain().command(() => { + const canWrapInList = can().wrapInList(listType, attributes); + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr.ensureMarks(filteredMarks); + if (canWrapInList) { + return true; + } + return commands.clearNodes(); + }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run(); +}; +var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => { + const { extendEmptyMarkRange = false } = options; + const type = getMarkType(typeOrName, state.schema); + const isActive2 = isMarkActive(state, type, attributes); + if (isActive2) { + return commands.unsetMark(type, { extendEmptyMarkRange }); + } + return commands.setMark(type, attributes); +}; +var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => { + const type = getNodeType(typeOrName, state.schema); + const toggleType = getNodeType(toggleTypeOrName, state.schema); + const isActive2 = isNodeActive(state, type, attributes); + let attributesToCopy; + if (state.selection.$anchor.sameParent(state.selection.$head)) { + attributesToCopy = state.selection.$anchor.parent.attrs; + } + if (isActive2) { + return commands.setNode(toggleType, attributesToCopy); + } + return commands.setNode(type, { ...attributesToCopy, ...attributes }); +}; +var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => { + const type = getNodeType(typeOrName, state.schema); + const isActive2 = isNodeActive(state, type, attributes); + if (isActive2) { + return commands.lift(type); + } + return commands.wrapIn(type, attributes); +}; +var undoInputRule = () => ({ state, dispatch }) => { + const plugins = state.plugins; + for (let i = 0; i < plugins.length; i += 1) { + const plugin = plugins[i]; + let undoable; + if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) { + if (dispatch) { + const tr = state.tr; + const toUndo = undoable.transform; + for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) { + tr.step(toUndo.steps[j].invert(toUndo.docs[j])); + } + if (undoable.text) { + const marks = tr.doc.resolve(undoable.from).marks(); + tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks)); + } else { + tr.delete(undoable.from, undoable.to); + } + } + return true; + } + } + return false; +}; +var unsetAllMarks = () => ({ tr, dispatch }) => { + const { selection } = tr; + const { empty: empty2, ranges } = selection; + if (empty2) { + return true; + } + if (dispatch) { + ranges.forEach((range) => { + tr.removeMark(range.$from.pos, range.$to.pos); + }); + } + return true; +}; +var unsetMark = (typeOrName, options = {}) => ({ tr, state, dispatch }) => { + var _a; + const { extendEmptyMarkRange = false } = options; + const { selection } = tr; + const type = getMarkType(typeOrName, state.schema); + const { $from, empty: empty2, ranges } = selection; + if (!dispatch) { + return true; + } + if (empty2 && extendEmptyMarkRange) { + let { from, to } = selection; + const attrs = (_a = $from.marks().find((mark) => mark.type === type)) == null ? void 0 : _a.attrs; + const range = getMarkRange($from, type, attrs); + if (range) { + from = range.from; + to = range.to; + } + tr.removeMark(from, to, type); + } else { + ranges.forEach((range) => { + tr.removeMark(range.$from.pos, range.$to.pos, type); + }); + } + tr.removeStoredMark(type); + return true; +}; +var unsetTextDirection = (position) => ({ tr, state, dispatch }) => { + const { selection } = state; + let from; + let to; + if (typeof position === "number") { + from = position; + to = position; + } else if (position && "from" in position && "to" in position) { + from = position.from; + to = position.to; + } else { + from = selection.from; + to = selection.to; + } + if (dispatch) { + tr.doc.nodesBetween(from, to, (node, pos) => { + if (node.isText) { + return; + } + const newAttrs = { ...node.attrs }; + delete newAttrs.dir; + tr.setNodeMarkup(pos, void 0, newAttrs); + }); + } + return true; +}; +var updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => { + let nodeType = null; + let markType = null; + const schemaType = getSchemaTypeNameByName( + typeof typeOrName === "string" ? typeOrName : typeOrName.name, + state.schema + ); + if (!schemaType) { + return false; + } + if (schemaType === "node") { + nodeType = getNodeType(typeOrName, state.schema); + } + if (schemaType === "mark") { + markType = getMarkType(typeOrName, state.schema); + } + let canUpdate = false; + tr.selection.ranges.forEach((range) => { + const from = range.$from.pos; + const to = range.$to.pos; + let lastPos; + let lastNode; + let trimmedFrom; + let trimmedTo; + if (tr.selection.empty) { + state.doc.nodesBetween(from, to, (node, pos) => { + if (nodeType && nodeType === node.type) { + canUpdate = true; + trimmedFrom = Math.max(pos, from); + trimmedTo = Math.min(pos + node.nodeSize, to); + lastPos = pos; + lastNode = node; + } + }); + } else { + state.doc.nodesBetween(from, to, (node, pos) => { + if (pos < from && nodeType && nodeType === node.type) { + canUpdate = true; + trimmedFrom = Math.max(pos, from); + trimmedTo = Math.min(pos + node.nodeSize, to); + lastPos = pos; + lastNode = node; + } + if (pos >= from && pos <= to) { + if (nodeType && nodeType === node.type) { + canUpdate = true; + if (dispatch) { + tr.setNodeMarkup(pos, void 0, { + ...node.attrs, + ...attributes + }); + } + } + if (markType && node.marks.length) { + node.marks.forEach((mark) => { + if (markType === mark.type) { + canUpdate = true; + if (dispatch) { + const trimmedFrom2 = Math.max(pos, from); + const trimmedTo2 = Math.min(pos + node.nodeSize, to); + tr.addMark( + trimmedFrom2, + trimmedTo2, + markType.create({ + ...mark.attrs, + ...attributes + }) + ); + } + } + }); + } + } + }); + } + if (lastNode) { + if (lastPos !== void 0 && dispatch) { + tr.setNodeMarkup(lastPos, void 0, { + ...lastNode.attrs, + ...attributes + }); + } + if (markType && lastNode.marks.length) { + lastNode.marks.forEach((mark) => { + if (markType === mark.type && dispatch) { + tr.addMark( + trimmedFrom, + trimmedTo, + markType.create({ + ...mark.attrs, + ...attributes + }) + ); + } + }); + } + } + }); + return canUpdate; +}; +var wrapIn2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return wrapIn(type, attributes)(state, dispatch); +}; +var wrapInList2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => { + const type = getNodeType(typeOrName, state.schema); + return wrapInList(type, attributes)(state, dispatch); +}; +var EventEmitter = class { + constructor() { + this.callbacks = {}; + } + on(event, fn) { + if (!this.callbacks[event]) { + this.callbacks[event] = []; + } + this.callbacks[event].push(fn); + return this; + } + emit(event, ...args) { + const callbacks = this.callbacks[event]; + if (callbacks) { + callbacks.forEach((callback) => callback.apply(this, args)); + } + return this; + } + off(event, fn) { + const callbacks = this.callbacks[event]; + if (callbacks) { + if (fn) { + this.callbacks[event] = callbacks.filter((callback) => callback !== fn); + } else { + delete this.callbacks[event]; + } + } + return this; + } + once(event, fn) { + const onceFn = (...args) => { + this.off(event, onceFn); + fn.apply(this, args); + }; + return this.on(event, onceFn); + } + removeAllListeners() { + this.callbacks = {}; + } +}; +var InputRule = class { + constructor(config) { + var _a; + this.find = config.find; + this.handler = config.handler; + this.undoable = (_a = config.undoable) != null ? _a : true; + } +}; +var inputRuleMatcherHandler = (text, find) => { + if (isRegExp(find)) { + return find.exec(text); + } + const inputRuleMatch = find(text); + if (!inputRuleMatch) { + return null; + } + const result = [inputRuleMatch.text]; + result.index = inputRuleMatch.index; + result.input = text; + result.data = inputRuleMatch.data; + if (inputRuleMatch.replaceWith) { + if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) { + console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'); + } + result.push(inputRuleMatch.replaceWith); + } + return result; +}; +function run(config) { + var _a; + const { editor, from, to, text, rules, plugin } = config; + const { view } = editor; + if (view.composing) { + return false; + } + const $from = view.state.doc.resolve(from); + if ( + // check for code node + $from.parent.type.spec.code || // check for code mark + !!((_a = $from.nodeBefore || $from.nodeAfter) == null ? void 0 : _a.marks.find((mark) => mark.type.spec.code)) + ) { + return false; + } + let matched = false; + const textBefore = getTextContentFromNodes($from) + text; + rules.forEach((rule) => { + if (matched) { + return; + } + const match = inputRuleMatcherHandler(textBefore, rule.find); + if (!match) { + return; + } + const tr = view.state.tr; + const state = createChainableState({ + state: view.state, + transaction: tr + }); + const range = { + from: from - (match[0].length - text.length), + to + }; + const { commands, chain, can } = new CommandManager({ + editor, + state + }); + const handler = rule.handler({ + state, + range, + match, + commands, + chain, + can + }); + if (handler === null || !tr.steps.length) { + return; + } + if (rule.undoable) { + tr.setMeta(plugin, { + transform: tr, + from, + to, + text + }); + } + view.dispatch(tr); + matched = true; + }); + return matched; +} +function inputRulesPlugin(props) { + const { editor, rules } = props; + const plugin = new Plugin({ + state: { + init() { + return null; + }, + apply(tr, prev, state) { + const stored = tr.getMeta(plugin); + if (stored) { + return stored; + } + const simulatedInputMeta = tr.getMeta("applyInputRules"); + const isSimulatedInput = !!simulatedInputMeta; + if (isSimulatedInput) { + setTimeout(() => { + let { text } = simulatedInputMeta; + if (typeof text === "string") { + text = text; + } else { + text = getHTMLFromFragment(Fragment.from(text), state.schema); + } + const { from } = simulatedInputMeta; + const to = from + text.length; + run({ + editor, + from, + to, + text, + rules, + plugin + }); + }); + } + return tr.selectionSet || tr.docChanged ? null : prev; + } + }, + props: { + handleTextInput(view, from, to, text) { + return run({ + editor, + from, + to, + text, + rules, + plugin + }); + }, + handleDOMEvents: { + compositionend: (view) => { + setTimeout(() => { + const { $cursor } = view.state.selection; + if ($cursor) { + run({ + editor, + from: $cursor.pos, + to: $cursor.pos, + text: "", + rules, + plugin + }); + } + }); + return false; + } + }, + // add support for input rules to trigger on enter + // this is useful for example for code blocks + handleKeyDown(view, event) { + if (event.key !== "Enter") { + return false; + } + const { $cursor } = view.state.selection; + if ($cursor) { + return run({ + editor, + from: $cursor.pos, + to: $cursor.pos, + text: "\n", + rules, + plugin + }); + } + return false; + } + }, + // @ts-ignore + isInputRules: true + }); + return plugin; +} +function getType(value) { + return Object.prototype.toString.call(value).slice(8, -1); +} +function isPlainObject(value) { + if (getType(value) !== "Object") { + return false; + } + return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype; +} +function mergeDeep(target, source) { + const output = { ...target }; + if (isPlainObject(target) && isPlainObject(source)) { + Object.keys(source).forEach((key) => { + if (isPlainObject(source[key]) && isPlainObject(target[key])) { + output[key] = mergeDeep(target[key], source[key]); + } else { + output[key] = source[key]; + } + }); + } + return output; +} +var Extendable = class { + constructor(config = {}) { + this.type = "extendable"; + this.parent = null; + this.child = null; + this.name = ""; + this.config = { + name: this.name + }; + this.config = { + ...this.config, + ...config + }; + this.name = this.config.name; + } + get options() { + return { + ...callOrReturn( + getExtensionField(this, "addOptions", { + name: this.name + }) + ) || {} + }; + } + get storage() { + return { + ...callOrReturn( + getExtensionField(this, "addStorage", { + name: this.name, + options: this.options + }) + ) || {} + }; + } + configure(options = {}) { + const extension = this.extend({ + ...this.config, + addOptions: () => { + return mergeDeep(this.options, options); + } + }); + extension.name = this.name; + extension.parent = this.parent; + return extension; + } + extend(extendedConfig = {}) { + const extension = new this.constructor({ ...this.config, ...extendedConfig }); + extension.parent = this; + this.child = extension; + extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name; + return extension; + } +}; +var Mark2 = class _Mark extends Extendable { + constructor() { + super(...arguments); + this.type = "mark"; + } + /** + * Create a new Mark instance + * @param config - Mark configuration object or a function that returns a configuration object + */ + static create(config = {}) { + const resolvedConfig = typeof config === "function" ? config() : config; + return new _Mark(resolvedConfig); + } + static handleExit({ editor, mark }) { + const { tr } = editor.state; + const currentPos = editor.state.selection.$from; + const isAtEnd = currentPos.pos === currentPos.end(); + if (isAtEnd) { + const currentMarks = currentPos.marks(); + const isInMark = !!currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name); + if (!isInMark) { + return false; + } + const removeMark2 = currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name); + if (removeMark2) { + tr.removeStoredMark(removeMark2); + } + tr.insertText(" ", currentPos.pos); + editor.view.dispatch(tr); + return true; + } + return false; + } + configure(options) { + return super.configure(options); + } + extend(extendedConfig) { + const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; + return super.extend(resolvedConfig); + } +}; +function isNumber(value) { + return typeof value === "number"; +} +var PasteRule = class { + constructor(config) { + this.find = config.find; + this.handler = config.handler; + } +}; +var pasteRuleMatcherHandler = (text, find, event) => { + if (isRegExp(find)) { + return [...text.matchAll(find)]; + } + const matches2 = find(text, event); + if (!matches2) { + return []; + } + return matches2.map((pasteRuleMatch) => { + const result = [pasteRuleMatch.text]; + result.index = pasteRuleMatch.index; + result.input = text; + result.data = pasteRuleMatch.data; + if (pasteRuleMatch.replaceWith) { + if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) { + console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'); + } + result.push(pasteRuleMatch.replaceWith); + } + return result; + }); +}; +function run2(config) { + const { editor, state, from, to, rule, pasteEvent, dropEvent } = config; + const { commands, chain, can } = new CommandManager({ + editor, + state + }); + const handlers2 = []; + state.doc.nodesBetween(from, to, (node, pos) => { + var _a, _b, _c, _d, _e; + if (((_b = (_a = node.type) == null ? void 0 : _a.spec) == null ? void 0 : _b.code) || !(node.isText || node.isTextblock || node.isInline)) { + return; + } + const contentSize = (_e = (_d = (_c = node.content) == null ? void 0 : _c.size) != null ? _d : node.nodeSize) != null ? _e : 0; + const resolvedFrom = Math.max(from, pos); + const resolvedTo = Math.min(to, pos + contentSize); + if (resolvedFrom >= resolvedTo) { + return; + } + const textToMatch = node.isText ? node.text || "" : node.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, ""); + const matches2 = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent); + matches2.forEach((match) => { + if (match.index === void 0) { + return; + } + const start = resolvedFrom + match.index + 1; + const end = start + match[0].length; + const range = { + from: state.tr.mapping.map(start), + to: state.tr.mapping.map(end) + }; + const handler = rule.handler({ + state, + range, + match, + commands, + chain, + can, + pasteEvent, + dropEvent + }); + handlers2.push(handler); + }); + }); + const success = handlers2.every((handler) => handler !== null); + return success; +} +var tiptapDragFromOtherEditor = null; +var createClipboardPasteEvent = (text) => { + var _a; + const event = new ClipboardEvent("paste", { + clipboardData: new DataTransfer() + }); + (_a = event.clipboardData) == null ? void 0 : _a.setData("text/html", text); + return event; +}; +function pasteRulesPlugin(props) { + const { editor, rules } = props; + let dragSourceElement = null; + let isPastedFromProseMirror = false; + let isDroppedFromProseMirror = false; + let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; + let dropEvent; + try { + dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; + } catch { + dropEvent = null; + } + const processEvent = ({ + state, + from, + to, + rule, + pasteEvt + }) => { + const tr = state.tr; + const chainableState = createChainableState({ + state, + transaction: tr + }); + const handler = run2({ + editor, + state: chainableState, + from: Math.max(from - 1, 0), + to: to.b - 1, + rule, + pasteEvent: pasteEvt, + dropEvent + }); + if (!handler || !tr.steps.length) { + return; + } + try { + dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; + } catch { + dropEvent = null; + } + pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; + return tr; + }; + const plugins = rules.map((rule) => { + return new Plugin({ + // we register a global drag handler to track the current drag source element + view(view) { + const handleDragstart = (event) => { + var _a; + dragSourceElement = ((_a = view.dom.parentElement) == null ? void 0 : _a.contains(event.target)) ? view.dom.parentElement : null; + if (dragSourceElement) { + tiptapDragFromOtherEditor = editor; + } + }; + const handleDragend = () => { + if (tiptapDragFromOtherEditor) { + tiptapDragFromOtherEditor = null; + } + }; + window.addEventListener("dragstart", handleDragstart); + window.addEventListener("dragend", handleDragend); + return { + destroy() { + window.removeEventListener("dragstart", handleDragstart); + window.removeEventListener("dragend", handleDragend); + } + }; + }, + props: { + handleDOMEvents: { + drop: (view, event) => { + isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement; + dropEvent = event; + if (!isDroppedFromProseMirror) { + const dragFromOtherEditor = tiptapDragFromOtherEditor; + if (dragFromOtherEditor == null ? void 0 : dragFromOtherEditor.isEditable) { + setTimeout(() => { + const selection = dragFromOtherEditor.state.selection; + if (selection) { + dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to }); + } + }, 10); + } + } + return false; + }, + paste: (_view, event) => { + var _a; + const html = (_a = event.clipboardData) == null ? void 0 : _a.getData("text/html"); + pasteEvent = event; + isPastedFromProseMirror = !!(html == null ? void 0 : html.includes("data-pm-slice")); + return false; + } + } + }, + appendTransaction: (transactions, oldState, state) => { + const transaction = transactions[0]; + const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror; + const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror; + const simulatedPasteMeta = transaction.getMeta("applyPasteRules"); + const isSimulatedPaste = !!simulatedPasteMeta; + if (!isPaste && !isDrop && !isSimulatedPaste) { + return; + } + if (isSimulatedPaste) { + let { text } = simulatedPasteMeta; + if (typeof text === "string") { + text = text; + } else { + text = getHTMLFromFragment(Fragment.from(text), state.schema); + } + const { from: from2 } = simulatedPasteMeta; + const to2 = from2 + text.length; + const pasteEvt = createClipboardPasteEvent(text); + return processEvent({ + rule, + state, + from: from2, + to: { b: to2 }, + pasteEvt + }); + } + const from = oldState.doc.content.findDiffStart(state.doc.content); + const to = oldState.doc.content.findDiffEnd(state.doc.content); + if (!isNumber(from) || !to || from === to.b) { + return; + } + return processEvent({ + rule, + state, + from, + to, + pasteEvt: pasteEvent + }); + } + }); + }); + return plugins; +} +var ExtensionManager = class { + constructor(extensions, editor) { + this.splittableMarks = []; + this.editor = editor; + this.baseExtensions = extensions; + this.extensions = resolveExtensions(extensions); + this.schema = getSchemaByResolvedExtensions(this.extensions, editor); + this.setupExtensions(); + } + /** + * Get all commands from the extensions. + * @returns An object with all commands where the key is the command name and the value is the command function + */ + get commands() { + return this.extensions.reduce((commands, extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor: this.editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + const addCommands = getExtensionField(extension, "addCommands", context); + if (!addCommands) { + return commands; + } + return { + ...commands, + ...addCommands() + }; + }, {}); + } + /** + * Get all registered Prosemirror plugins from the extensions. + * @returns An array of Prosemirror plugins + */ + get plugins() { + const { editor } = this; + const extensions = sortExtensions([...this.extensions].reverse()); + const allPlugins = extensions.flatMap((extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + const plugins = []; + const addKeyboardShortcuts = getExtensionField( + extension, + "addKeyboardShortcuts", + context + ); + let defaultBindings = {}; + if (extension.type === "mark" && getExtensionField(extension, "exitable", context)) { + defaultBindings.ArrowRight = () => Mark2.handleExit({ editor, mark: extension }); + } + if (addKeyboardShortcuts) { + const bindings = Object.fromEntries( + Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => { + return [shortcut, () => method({ editor })]; + }) + ); + defaultBindings = { ...defaultBindings, ...bindings }; + } + const keyMapPlugin = keymap(defaultBindings); + plugins.push(keyMapPlugin); + const addInputRules = getExtensionField(extension, "addInputRules", context); + if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) { + const rules = addInputRules(); + if (rules && rules.length) { + const inputResult = inputRulesPlugin({ + editor, + rules + }); + const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult]; + plugins.push(...inputPlugins); + } + } + const addPasteRules = getExtensionField(extension, "addPasteRules", context); + if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) { + const rules = addPasteRules(); + if (rules && rules.length) { + const pasteRules = pasteRulesPlugin({ editor, rules }); + plugins.push(...pasteRules); + } + } + const addProseMirrorPlugins = getExtensionField( + extension, + "addProseMirrorPlugins", + context + ); + if (addProseMirrorPlugins) { + const proseMirrorPlugins = addProseMirrorPlugins(); + plugins.push(...proseMirrorPlugins); + } + return plugins; + }); + return allPlugins; + } + /** + * Get all attributes from the extensions. + * @returns An array of attributes + */ + get attributes() { + return getAttributesFromExtensions(this.extensions); + } + /** + * Get all node views from the extensions. + * @returns An object with all node views where the key is the node name and the value is the node view function + */ + get nodeViews() { + const { editor } = this; + const { nodeExtensions } = splitExtensions(this.extensions); + return Object.fromEntries( + nodeExtensions.filter((extension) => !!getExtensionField(extension, "addNodeView")).map((extension) => { + const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getNodeType(extension.name, this.schema) + }; + const addNodeView = getExtensionField(extension, "addNodeView", context); + if (!addNodeView) { + return []; + } + const nodeViewResult = addNodeView(); + if (!nodeViewResult) { + return []; + } + const nodeview = (node, view, getPos, decorations, innerDecorations) => { + const HTMLAttributes = getRenderedAttributes(node, extensionAttributes); + return nodeViewResult({ + // pass-through + node, + view, + getPos, + decorations, + innerDecorations, + // tiptap-specific + editor, + extension, + HTMLAttributes + }); + }; + return [extension.name, nodeview]; + }) + ); + } + /** + * Get the composed dispatchTransaction function from all extensions. + * @param baseDispatch The base dispatch function (e.g. from the editor or user props) + * @returns A composed dispatch function + */ + dispatchTransaction(baseDispatch) { + const { editor } = this; + const extensions = sortExtensions([...this.extensions].reverse()); + return extensions.reduceRight((next, extension) => { + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + const dispatchTransaction = getExtensionField( + extension, + "dispatchTransaction", + context + ); + if (!dispatchTransaction) { + return next; + } + return (transaction) => { + dispatchTransaction.call(context, { transaction, next }); + }; + }, baseDispatch); + } + get markViews() { + const { editor } = this; + const { markExtensions } = splitExtensions(this.extensions); + return Object.fromEntries( + markExtensions.filter((extension) => !!getExtensionField(extension, "addMarkView")).map((extension) => { + const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor, + type: getMarkType(extension.name, this.schema) + }; + const addMarkView = getExtensionField(extension, "addMarkView", context); + if (!addMarkView) { + return []; + } + const markView = (mark, view, inline) => { + const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes); + return addMarkView()({ + // pass-through + mark, + view, + inline, + // tiptap-specific + editor, + extension, + HTMLAttributes, + updateAttributes: (attrs) => { + updateMarkViewAttributes(mark, editor, attrs); + } + }); + }; + return [extension.name, markView]; + }) + ); + } + /** + * Go through all extensions, create extension storages & setup marks + * & bind editor event listener. + */ + setupExtensions() { + const extensions = this.extensions; + this.editor.extensionStorage = Object.fromEntries( + extensions.map((extension) => [extension.name, extension.storage]) + ); + extensions.forEach((extension) => { + var _a; + const context = { + name: extension.name, + options: extension.options, + storage: this.editor.extensionStorage[extension.name], + editor: this.editor, + type: getSchemaTypeByName(extension.name, this.schema) + }; + if (extension.type === "mark") { + const keepOnSplit = (_a = callOrReturn(getExtensionField(extension, "keepOnSplit", context))) != null ? _a : true; + if (keepOnSplit) { + this.splittableMarks.push(extension.name); + } + } + const onBeforeCreate = getExtensionField(extension, "onBeforeCreate", context); + const onCreate = getExtensionField(extension, "onCreate", context); + const onUpdate = getExtensionField(extension, "onUpdate", context); + const onSelectionUpdate = getExtensionField( + extension, + "onSelectionUpdate", + context + ); + const onTransaction = getExtensionField(extension, "onTransaction", context); + const onFocus = getExtensionField(extension, "onFocus", context); + const onBlur = getExtensionField(extension, "onBlur", context); + const onDestroy = getExtensionField(extension, "onDestroy", context); + if (onBeforeCreate) { + this.editor.on("beforeCreate", onBeforeCreate); + } + if (onCreate) { + this.editor.on("create", onCreate); + } + if (onUpdate) { + this.editor.on("update", onUpdate); + } + if (onSelectionUpdate) { + this.editor.on("selectionUpdate", onSelectionUpdate); + } + if (onTransaction) { + this.editor.on("transaction", onTransaction); + } + if (onFocus) { + this.editor.on("focus", onFocus); + } + if (onBlur) { + this.editor.on("blur", onBlur); + } + if (onDestroy) { + this.editor.on("destroy", onDestroy); + } + }); + } +}; +ExtensionManager.resolve = resolveExtensions; +ExtensionManager.sort = sortExtensions; +ExtensionManager.flatten = flattenExtensions; +var extensions_exports = {}; +__export(extensions_exports, { + ClipboardTextSerializer: () => ClipboardTextSerializer, + Commands: () => Commands, + Delete: () => Delete, + Drop: () => Drop, + Editable: () => Editable, + FocusEvents: () => FocusEvents, + Keymap: () => Keymap, + Paste: () => Paste, + Tabindex: () => Tabindex, + TextDirection: () => TextDirection, + focusEventsPluginKey: () => focusEventsPluginKey +}); +var Extension = class _Extension extends Extendable { + constructor() { + super(...arguments); + this.type = "extension"; + } + /** + * Create a new Extension instance + * @param config - Extension configuration object or a function that returns a configuration object + */ + static create(config = {}) { + const resolvedConfig = typeof config === "function" ? config() : config; + return new _Extension(resolvedConfig); + } + configure(options) { + return super.configure(options); + } + extend(extendedConfig) { + const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; + return super.extend(resolvedConfig); + } +}; +var ClipboardTextSerializer = Extension.create({ + name: "clipboardTextSerializer", + addOptions() { + return { + blockSeparator: void 0 + }; + }, + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("clipboardTextSerializer"), + props: { + clipboardTextSerializer: () => { + const { editor } = this; + const { state, schema } = editor; + const { doc: doc3, selection } = state; + const { ranges } = selection; + const from = Math.min(...ranges.map((range2) => range2.$from.pos)); + const to = Math.max(...ranges.map((range2) => range2.$to.pos)); + const textSerializers = getTextSerializersFromSchema(schema); + const range = { from, to }; + return getTextBetween(doc3, range, { + ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {}, + textSerializers + }); + } + } + }) + ]; + } +}); +var Commands = Extension.create({ + name: "commands", + addCommands() { + return { + ...commands_exports + }; + } +}); +var Delete = Extension.create({ + name: "delete", + onUpdate({ transaction, appendedTransactions }) { + var _a, _b, _c; + const callback = () => { + var _a2, _b2, _c2, _d; + if ((_d = (_c2 = (_b2 = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) { + return; + } + const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]); + const changes = getChangedRanges(nextTransaction); + changes.forEach((change) => { + if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) { + nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from) => { + const to = from + node.nodeSize - 2; + const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to; + this.editor.emit("delete", { + type: "node", + node, + from, + to, + newFrom: nextTransaction.mapping.map(from), + newTo: nextTransaction.mapping.map(to), + deletedRange: change.oldRange, + newRange: change.newRange, + partial: !isFullyWithinRange, + editor: this.editor, + transaction, + combinedTransform: nextTransaction + }); + }); + } + }); + const mapping = nextTransaction.mapping; + nextTransaction.steps.forEach((step, index) => { + var _a3, _b3; + if (step instanceof RemoveMarkStep) { + const newStart = mapping.slice(index).map(step.from, -1); + const newEnd = mapping.slice(index).map(step.to); + const oldStart = mapping.invert().map(newStart, -1); + const oldEnd = mapping.invert().map(newEnd); + const foundBeforeMark = (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark) => mark.eq(step.mark)); + const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark) => mark.eq(step.mark)); + this.editor.emit("delete", { + type: "mark", + mark: step.mark, + from: step.from, + to: step.to, + deletedRange: { + from: oldStart, + to: oldEnd + }, + newRange: { + from: newStart, + to: newEnd + }, + partial: Boolean(foundAfterMark || foundBeforeMark), + editor: this.editor, + transaction, + combinedTransform: nextTransaction + }); + } + }); + }; + if ((_c = (_b = (_a = this.editor.options.coreExtensionOptions) == null ? void 0 : _a.delete) == null ? void 0 : _b.async) != null ? _c : true) { + setTimeout(callback, 0); + } else { + callback(); + } + } +}); +var Drop = Extension.create({ + name: "drop", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("tiptapDrop"), + props: { + handleDrop: (_, e, slice, moved) => { + this.editor.emit("drop", { + editor: this.editor, + event: e, + slice, + moved + }); + } + } + }) + ]; + } +}); +var Editable = Extension.create({ + name: "editable", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("editable"), + props: { + editable: () => this.editor.options.editable + } + }) + ]; + } +}); +var focusEventsPluginKey = new PluginKey("focusEvents"); +var FocusEvents = Extension.create({ + name: "focusEvents", + addProseMirrorPlugins() { + const { editor } = this; + return [ + new Plugin({ + key: focusEventsPluginKey, + props: { + handleDOMEvents: { + focus: (view, event) => { + editor.isFocused = true; + const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false); + view.dispatch(transaction); + return false; + }, + blur: (view, event) => { + editor.isFocused = false; + const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false); + view.dispatch(transaction); + return false; + } + } + } + }) + ]; + } +}); +var Keymap = Extension.create({ + name: "keymap", + addKeyboardShortcuts() { + const handleBackspace = () => this.editor.commands.first(({ commands }) => [ + () => commands.undoInputRule(), + // maybe convert first text block node to default node + () => commands.command(({ tr }) => { + const { selection, doc: doc3 } = tr; + const { empty: empty2, $anchor } = selection; + const { pos, parent } = $anchor; + const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor; + const parentIsIsolating = $parentPos.parent.type.spec.isolating; + const parentPos = $anchor.pos - $anchor.parentOffset; + const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc3).from === pos; + if (!empty2 || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") { + return false; + } + return commands.clearNodes(); + }), + () => commands.deleteSelection(), + () => commands.joinBackward(), + () => commands.selectNodeBackward() + ]); + const handleDelete = () => this.editor.commands.first(({ commands }) => [ + () => commands.deleteSelection(), + () => commands.deleteCurrentNode(), + () => commands.joinForward(), + () => commands.selectNodeForward() + ]); + const handleEnter = () => this.editor.commands.first(({ commands }) => [ + () => commands.newlineInCode(), + () => commands.createParagraphNear(), + () => commands.liftEmptyBlock(), + () => commands.splitBlock() + ]); + const baseKeymap = { + Enter: handleEnter, + "Mod-Enter": () => this.editor.commands.exitCode(), + Backspace: handleBackspace, + "Mod-Backspace": handleBackspace, + "Shift-Backspace": handleBackspace, + Delete: handleDelete, + "Mod-Delete": handleDelete, + "Mod-a": () => this.editor.commands.selectAll() + }; + const pcKeymap = { + ...baseKeymap + }; + const macKeymap = { + ...baseKeymap, + "Ctrl-h": handleBackspace, + "Alt-Backspace": handleBackspace, + "Ctrl-d": handleDelete, + "Ctrl-Alt-Backspace": handleDelete, + "Alt-Delete": handleDelete, + "Alt-d": handleDelete, + "Ctrl-a": () => this.editor.commands.selectTextblockStart(), + "Ctrl-e": () => this.editor.commands.selectTextblockEnd() + }; + if (isiOS() || isMacOS()) { + return macKeymap; + } + return pcKeymap; + }, + addProseMirrorPlugins() { + return [ + // With this plugin we check if the whole document was selected and deleted. + // In this case we will additionally call `clearNodes()` to convert e.g. a heading + // to a paragraph if necessary. + // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well + // with many other commands. + new Plugin({ + key: new PluginKey("clearDocument"), + appendTransaction: (transactions, oldState, newState) => { + if (transactions.some((tr2) => tr2.getMeta("composition"))) { + return; + } + const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); + const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument")); + if (!docChanges || ignoreTr) { + return; + } + const { empty: empty2, from, to } = oldState.selection; + const allFrom = Selection.atStart(oldState.doc).from; + const allEnd = Selection.atEnd(oldState.doc).to; + const allWasSelected = from === allFrom && to === allEnd; + if (empty2 || !allWasSelected) { + return; + } + const isEmpty = isNodeEmpty(newState.doc); + if (!isEmpty) { + return; + } + const tr = newState.tr; + const state = createChainableState({ + state: newState, + transaction: tr + }); + const { commands } = new CommandManager({ + editor: this.editor, + state + }); + commands.clearNodes(); + if (!tr.steps.length) { + return; + } + return tr; + } + }) + ]; + } +}); +var Paste = Extension.create({ + name: "paste", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("tiptapPaste"), + props: { + handlePaste: (_view, e, slice) => { + this.editor.emit("paste", { + editor: this.editor, + event: e, + slice + }); + } + } + }) + ]; + } +}); +var Tabindex = Extension.create({ + name: "tabindex", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("tabindex"), + props: { + attributes: () => this.editor.isEditable ? { tabindex: "0" } : {} + } + }) + ]; + } +}); +var TextDirection = Extension.create({ + name: "textDirection", + addOptions() { + return { + direction: void 0 + }; + }, + addGlobalAttributes() { + if (!this.options.direction) { + return []; + } + const { nodeExtensions } = splitExtensions(this.extensions); + return [ + { + types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name), + attributes: { + dir: { + default: this.options.direction, + parseHTML: (element) => { + const dir = element.getAttribute("dir"); + if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) { + return dir; + } + return this.options.direction; + }, + renderHTML: (attributes) => { + if (!attributes.dir) { + return {}; + } + return { + dir: attributes.dir + }; + } + } + } + } + ]; + }, + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("textDirection"), + props: { + attributes: () => { + const direction = this.options.direction; + if (!direction) { + return {}; + } + return { + dir: direction + }; + } + } + }) + ]; + } +}); +var NodePos = class _NodePos { + constructor(pos, editor, isBlock = false, node = null) { + this.currentNode = null; + this.actualDepth = null; + this.isBlock = isBlock; + this.resolvedPos = pos; + this.editor = editor; + this.currentNode = node; + } + get name() { + return this.node.type.name; + } + get node() { + return this.currentNode || this.resolvedPos.node(); + } + get element() { + return this.editor.view.domAtPos(this.pos).node; + } + get depth() { + var _a; + return (_a = this.actualDepth) != null ? _a : this.resolvedPos.depth; + } + get pos() { + return this.resolvedPos.pos; + } + get content() { + return this.node.content; + } + set content(content) { + let from = this.from; + let to = this.to; + if (this.isBlock) { + if (this.content.size === 0) { + console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`); + return; + } + from = this.from + 1; + to = this.to - 1; + } + this.editor.commands.insertContentAt({ from, to }, content); + } + get attributes() { + return this.node.attrs; + } + get textContent() { + return this.node.textContent; + } + get size() { + return this.node.nodeSize; + } + get from() { + if (this.isBlock) { + return this.pos; + } + return this.resolvedPos.start(this.resolvedPos.depth); + } + get range() { + return { + from: this.from, + to: this.to + }; + } + get to() { + if (this.isBlock) { + return this.pos + this.size; + } + return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1); + } + get parent() { + if (this.depth === 0) { + return null; + } + const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1); + const $pos = this.resolvedPos.doc.resolve(parentPos); + return new _NodePos($pos, this.editor); + } + get before() { + let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2)); + if ($pos.depth !== this.depth) { + $pos = this.resolvedPos.doc.resolve(this.from - 3); + } + return new _NodePos($pos, this.editor); + } + get after() { + let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1)); + if ($pos.depth !== this.depth) { + $pos = this.resolvedPos.doc.resolve(this.to + 3); + } + return new _NodePos($pos, this.editor); + } + get children() { + const children = []; + this.node.content.forEach((node, offset) => { + const isBlock = node.isBlock && !node.isTextblock; + const isNonTextAtom = node.isAtom && !node.isText; + const isInline2 = node.isInline; + const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1); + if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) { + return; + } + const $pos = this.resolvedPos.doc.resolve(targetPos); + if (!isBlock && !isInline2 && $pos.depth <= this.depth) { + return; + } + const childNodePos = new _NodePos($pos, this.editor, isBlock, isBlock || isInline2 ? node : null); + if (isBlock) { + childNodePos.actualDepth = this.depth + 1; + } + children.push(childNodePos); + }); + return children; + } + get firstChild() { + return this.children[0] || null; + } + get lastChild() { + const children = this.children; + return children[children.length - 1] || null; + } + closest(selector, attributes = {}) { + let node = null; + let currentNode = this.parent; + while (currentNode && !node) { + if (currentNode.node.type.name === selector) { + if (Object.keys(attributes).length > 0) { + const nodeAttributes = currentNode.node.attrs; + const attrKeys = Object.keys(attributes); + for (let index = 0; index < attrKeys.length; index += 1) { + const key = attrKeys[index]; + if (nodeAttributes[key] !== attributes[key]) { + break; + } + } + } else { + node = currentNode; + } + } + currentNode = currentNode.parent; + } + return node; + } + querySelector(selector, attributes = {}) { + return this.querySelectorAll(selector, attributes, true)[0] || null; + } + querySelectorAll(selector, attributes = {}, firstItemOnly = false) { + let nodes = []; + if (!this.children || this.children.length === 0) { + return nodes; + } + const attrKeys = Object.keys(attributes); + this.children.forEach((childPos) => { + if (firstItemOnly && nodes.length > 0) { + return; + } + if (childPos.node.type.name === selector) { + const doesAllAttributesMatch = attrKeys.every((key) => attributes[key] === childPos.node.attrs[key]); + if (doesAllAttributesMatch) { + nodes.push(childPos); + } + } + if (firstItemOnly && nodes.length > 0) { + return; + } + nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly)); + }); + return nodes; + } + setAttribute(attributes) { + const { tr } = this.editor.state; + tr.setNodeMarkup(this.from, void 0, { + ...this.node.attrs, + ...attributes + }); + this.editor.view.dispatch(tr); + } +}; +var style = `.ProseMirror { + position: relative; +} + +.ProseMirror { + word-wrap: break-word; + white-space: pre-wrap; + white-space: break-spaces; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; + font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ +} + +.ProseMirror [contenteditable="false"] { + white-space: normal; +} + +.ProseMirror [contenteditable="false"] [contenteditable="true"] { + white-space: pre-wrap; +} + +.ProseMirror pre { + white-space: pre-wrap; +} + +img.ProseMirror-separator { + display: inline !important; + border: none !important; + margin: 0 !important; + width: 0 !important; + height: 0 !important; +} + +.ProseMirror-gapcursor { + display: none; + pointer-events: none; + position: absolute; + margin: 0; +} + +.ProseMirror-gapcursor:after { + content: ""; + display: block; + position: absolute; + top: -2px; + width: 20px; + border-top: 1px solid black; + animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; +} + +@keyframes ProseMirror-cursor-blink { + to { + visibility: hidden; + } +} + +.ProseMirror-hideselection *::selection { + background: transparent; +} + +.ProseMirror-hideselection *::-moz-selection { + background: transparent; +} + +.ProseMirror-hideselection * { + caret-color: transparent; +} + +.ProseMirror-focused .ProseMirror-gapcursor { + display: block; +}`; +function createStyleTag(style2, nonce, suffix) { + const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ""}]`); + if (tiptapStyleTag !== null) { + return tiptapStyleTag; + } + const styleNode = document.createElement("style"); + if (nonce) { + styleNode.setAttribute("nonce", nonce); + } + styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ""}`, ""); + styleNode.innerHTML = style2; + document.getElementsByTagName("head")[0].appendChild(styleNode); + return styleNode; +} +var Editor = class extends EventEmitter { + constructor(options = {}) { + super(); + this.css = null; + this.className = "tiptap"; + this.editorView = null; + this.isFocused = false; + this.isInitialized = false; + this.extensionStorage = {}; + this.instanceId = Math.random().toString(36).slice(2, 9); + this.options = { + element: typeof document !== "undefined" ? document.createElement("div") : null, + content: "", + injectCSS: true, + injectNonce: void 0, + extensions: [], + autofocus: false, + editable: true, + textDirection: void 0, + editorProps: {}, + parseOptions: {}, + coreExtensionOptions: {}, + enableInputRules: true, + enablePasteRules: true, + enableCoreExtensions: true, + enableContentCheck: false, + emitContentError: false, + onBeforeCreate: () => null, + onCreate: () => null, + onMount: () => null, + onUnmount: () => null, + onUpdate: () => null, + onSelectionUpdate: () => null, + onTransaction: () => null, + onFocus: () => null, + onBlur: () => null, + onDestroy: () => null, + onContentError: ({ error }) => { + throw error; + }, + onPaste: () => null, + onDrop: () => null, + onDelete: () => null, + enableExtensionDispatchTransaction: true + }; + this.isCapturingTransaction = false; + this.capturedTransaction = null; + this.utils = { + getUpdatedPosition, + createMappablePosition + }; + this.setOptions(options); + this.createExtensionManager(); + this.createCommandManager(); + this.createSchema(); + this.on("beforeCreate", this.options.onBeforeCreate); + this.emit("beforeCreate", { editor: this }); + this.on("mount", this.options.onMount); + this.on("unmount", this.options.onUnmount); + this.on("contentError", this.options.onContentError); + this.on("create", this.options.onCreate); + this.on("update", this.options.onUpdate); + this.on("selectionUpdate", this.options.onSelectionUpdate); + this.on("transaction", this.options.onTransaction); + this.on("focus", this.options.onFocus); + this.on("blur", this.options.onBlur); + this.on("destroy", this.options.onDestroy); + this.on("drop", ({ event, slice, moved }) => this.options.onDrop(event, slice, moved)); + this.on("paste", ({ event, slice }) => this.options.onPaste(event, slice)); + this.on("delete", this.options.onDelete); + const initialDoc = this.createDoc(); + const selection = resolveFocusPosition(initialDoc, this.options.autofocus); + this.editorState = EditorState.create({ + doc: initialDoc, + schema: this.schema, + selection: selection || void 0 + }); + if (this.options.element) { + this.mount(this.options.element); + } + } + /** + * Attach the editor to the DOM, creating a new editor view. + */ + mount(el) { + if (typeof document === "undefined") { + throw new Error( + `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.` + ); + } + this.createView(el); + this.emit("mount", { editor: this }); + if (this.css && !document.head.contains(this.css)) { + document.head.appendChild(this.css); + } + window.setTimeout(() => { + if (this.isDestroyed) { + return; + } + if (this.options.autofocus !== false && this.options.autofocus !== null) { + this.commands.focus(this.options.autofocus); + } + this.emit("create", { editor: this }); + this.isInitialized = true; + }, 0); + } + /** + * Remove the editor from the DOM, but still allow remounting at a different point in time + */ + unmount() { + if (this.editorView) { + const dom = this.editorView.dom; + if (dom == null ? void 0 : dom.editor) { + delete dom.editor; + } + this.editorView.destroy(); + } + this.editorView = null; + this.isInitialized = false; + if (this.css && !document.querySelectorAll(`.${this.className}`).length) { + try { + if (typeof this.css.remove === "function") { + this.css.remove(); + } else if (this.css.parentNode) { + this.css.parentNode.removeChild(this.css); + } + } catch (error) { + console.warn("Failed to remove CSS element:", error); + } + } + this.css = null; + this.emit("unmount", { editor: this }); + } + /** + * Returns the editor storage. + */ + get storage() { + return this.extensionStorage; + } + /** + * An object of all registered commands. + */ + get commands() { + return this.commandManager.commands; + } + /** + * Create a command chain to call multiple commands at once. + */ + chain() { + return this.commandManager.chain(); + } + /** + * Check if a command or a command chain can be executed. Without executing it. + */ + can() { + return this.commandManager.can(); + } + /** + * Inject CSS styles. + */ + injectCSS() { + if (this.options.injectCSS && typeof document !== "undefined") { + this.css = createStyleTag(style, this.options.injectNonce); + } + } + /** + * Update editor options. + * + * @param options A list of options + */ + setOptions(options = {}) { + this.options = { + ...this.options, + ...options + }; + if (!this.editorView || !this.state || this.isDestroyed) { + return; + } + if (this.options.editorProps) { + this.view.setProps(this.options.editorProps); + } + this.view.updateState(this.state); + } + /** + * Update editable state of the editor. + */ + setEditable(editable, emitUpdate = true) { + this.setOptions({ editable }); + if (emitUpdate) { + this.emit("update", { editor: this, transaction: this.state.tr, appendedTransactions: [] }); + } + } + /** + * Returns whether the editor is editable. + */ + get isEditable() { + return this.options.editable && this.view && this.view.editable; + } + /** + * Returns the editor state. + */ + get view() { + if (this.editorView) { + return this.editorView; + } + return new Proxy( + { + state: this.editorState, + updateState: (state) => { + this.editorState = state; + }, + dispatch: (tr) => { + this.dispatchTransaction(tr); + }, + // Stub some commonly accessed properties to prevent errors + composing: false, + dragging: null, + editable: true, + isDestroyed: false + }, + { + get: (obj, key) => { + if (this.editorView) { + return this.editorView[key]; + } + if (key === "state") { + return this.editorState; + } + if (key in obj) { + return Reflect.get(obj, key); + } + throw new Error( + `[tiptap error]: The editor view is not available. Cannot access view['${key}']. The editor may not be mounted yet.` + ); + } + } + ); + } + /** + * Returns the editor state. + */ + get state() { + if (this.editorView) { + this.editorState = this.view.state; + } + return this.editorState; + } + /** + * Register a ProseMirror plugin. + * + * @param plugin A ProseMirror plugin + * @param handlePlugins Control how to merge the plugin into the existing plugins. + * @returns The new editor state + */ + registerPlugin(plugin, handlePlugins) { + const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin]; + const state = this.state.reconfigure({ plugins }); + this.view.updateState(state); + return state; + } + /** + * Unregister a ProseMirror plugin. + * + * @param nameOrPluginKeyToRemove The plugins name + * @returns The new editor state or undefined if the editor is destroyed + */ + unregisterPlugin(nameOrPluginKeyToRemove) { + if (this.isDestroyed) { + return void 0; + } + const prevPlugins = this.state.plugins; + let plugins = prevPlugins; + [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => { + const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key; + plugins = plugins.filter((plugin) => !plugin.key.startsWith(name)); + }); + if (prevPlugins.length === plugins.length) { + return void 0; + } + const state = this.state.reconfigure({ + plugins + }); + this.view.updateState(state); + return state; + } + /** + * Creates an extension manager. + */ + createExtensionManager() { + var _a, _b; + const coreExtensions = this.options.enableCoreExtensions ? [ + Editable, + ClipboardTextSerializer.configure({ + blockSeparator: (_b = (_a = this.options.coreExtensionOptions) == null ? void 0 : _a.clipboardTextSerializer) == null ? void 0 : _b.blockSeparator + }), + Commands, + FocusEvents, + Keymap, + Tabindex, + Drop, + Paste, + Delete, + TextDirection.configure({ + direction: this.options.textDirection + }) + ].filter((ext) => { + if (typeof this.options.enableCoreExtensions === "object") { + return this.options.enableCoreExtensions[ext.name] !== false; + } + return true; + }) : []; + const allExtensions = [...coreExtensions, ...this.options.extensions].filter((extension) => { + return ["extension", "node", "mark"].includes(extension == null ? void 0 : extension.type); + }); + this.extensionManager = new ExtensionManager(allExtensions, this); + } + /** + * Creates an command manager. + */ + createCommandManager() { + this.commandManager = new CommandManager({ + editor: this + }); + } + /** + * Creates a ProseMirror schema. + */ + createSchema() { + this.schema = this.extensionManager.schema; + } + /** + * Creates the initial document. + */ + createDoc() { + let doc3; + try { + doc3 = createDocument(this.options.content, this.schema, this.options.parseOptions, { + errorOnInvalidContent: this.options.enableContentCheck + }); + } catch (e) { + if (!(e instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e.message)) { + throw e; + } + this.emit("contentError", { + editor: this, + error: e, + disableCollaboration: () => { + if ("collaboration" in this.storage && typeof this.storage.collaboration === "object" && this.storage.collaboration) { + ; + this.storage.collaboration.isDisabled = true; + } + this.options.extensions = this.options.extensions.filter((extension) => extension.name !== "collaboration"); + this.createExtensionManager(); + } + }); + doc3 = createDocument(this.options.content, this.schema, this.options.parseOptions, { + errorOnInvalidContent: false + }); + } + return doc3; + } + /** + * Creates a ProseMirror view. + */ + createView(element) { + const { editorProps, enableExtensionDispatchTransaction } = this.options; + const baseDispatch = editorProps.dispatchTransaction || this.dispatchTransaction.bind(this); + const dispatch = enableExtensionDispatchTransaction ? this.extensionManager.dispatchTransaction(baseDispatch) : baseDispatch; + this.editorView = new EditorView(element, { + ...editorProps, + attributes: { + // add `role="textbox"` to the editor element + role: "textbox", + ...editorProps == null ? void 0 : editorProps.attributes + }, + dispatchTransaction: dispatch, + state: this.editorState, + markViews: this.extensionManager.markViews, + nodeViews: this.extensionManager.nodeViews + }); + const newState = this.state.reconfigure({ + plugins: this.extensionManager.plugins + }); + this.view.updateState(newState); + this.prependClass(); + this.injectCSS(); + const dom = this.view.dom; + dom.editor = this; + } + /** + * Creates all node and mark views. + */ + createNodeViews() { + if (this.view.isDestroyed) { + return; + } + this.view.setProps({ + markViews: this.extensionManager.markViews, + nodeViews: this.extensionManager.nodeViews + }); + } + /** + * Prepend class name to element. + */ + prependClass() { + this.view.dom.className = `${this.className} ${this.view.dom.className}`; + } + captureTransaction(fn) { + this.isCapturingTransaction = true; + fn(); + this.isCapturingTransaction = false; + const tr = this.capturedTransaction; + this.capturedTransaction = null; + return tr; + } + /** + * The callback over which to send transactions (state updates) produced by the view. + * + * @param transaction An editor state transaction + */ + dispatchTransaction(transaction) { + if (this.view.isDestroyed) { + return; + } + if (this.isCapturingTransaction) { + if (!this.capturedTransaction) { + this.capturedTransaction = transaction; + return; + } + transaction.steps.forEach((step) => { + var _a; + return (_a = this.capturedTransaction) == null ? void 0 : _a.step(step); + }); + return; + } + const { state, transactions } = this.state.applyTransaction(transaction); + const selectionHasChanged = !this.state.selection.eq(state.selection); + const rootTrWasApplied = transactions.includes(transaction); + const prevState = this.state; + this.emit("beforeTransaction", { + editor: this, + transaction, + nextState: state + }); + if (!rootTrWasApplied) { + return; + } + this.view.updateState(state); + this.emit("transaction", { + editor: this, + transaction, + appendedTransactions: transactions.slice(1) + }); + if (selectionHasChanged) { + this.emit("selectionUpdate", { + editor: this, + transaction + }); + } + const mostRecentFocusTr = transactions.findLast((tr) => tr.getMeta("focus") || tr.getMeta("blur")); + const focus2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("focus"); + const blur2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("blur"); + if (focus2) { + this.emit("focus", { + editor: this, + event: focus2.event, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + transaction: mostRecentFocusTr + }); + } + if (blur2) { + this.emit("blur", { + editor: this, + event: blur2.event, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + transaction: mostRecentFocusTr + }); + } + if (transaction.getMeta("preventUpdate") || !transactions.some((tr) => tr.docChanged) || prevState.doc.eq(state.doc)) { + return; + } + this.emit("update", { + editor: this, + transaction, + appendedTransactions: transactions.slice(1) + }); + } + /** + * Get attributes of the currently selected node or mark. + */ + getAttributes(nameOrType) { + return getAttributes(this.state, nameOrType); + } + isActive(nameOrAttributes, attributesOrUndefined) { + const name = typeof nameOrAttributes === "string" ? nameOrAttributes : null; + const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes; + return isActive(this.state, name, attributes); + } + /** + * Get the document as JSON. + */ + getJSON() { + return this.state.doc.toJSON(); + } + /** + * Get the document as HTML. + */ + getHTML() { + return getHTMLFromFragment(this.state.doc.content, this.schema); + } + /** + * Get the document as text. + */ + getText(options) { + const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; + return getText2(this.state.doc, { + blockSeparator, + textSerializers: { + ...getTextSerializersFromSchema(this.schema), + ...textSerializers + } + }); + } + /** + * Check if there is no content. + */ + get isEmpty() { + return isNodeEmpty(this.state.doc); + } + /** + * Destroy the editor. + */ + destroy() { + this.emit("destroy"); + this.unmount(); + this.removeAllListeners(); + } + /** + * Check if the editor is already destroyed. + */ + get isDestroyed() { + var _a, _b; + return (_b = (_a = this.editorView) == null ? void 0 : _a.isDestroyed) != null ? _b : true; + } + $node(selector, attributes) { + var _a; + return ((_a = this.$doc) == null ? void 0 : _a.querySelector(selector, attributes)) || null; + } + $nodes(selector, attributes) { + var _a; + return ((_a = this.$doc) == null ? void 0 : _a.querySelectorAll(selector, attributes)) || null; + } + $pos(pos) { + const $pos = this.state.doc.resolve(pos); + return new NodePos($pos, this); + } + get $doc() { + return this.$pos(0); + } +}; +function markInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match); + if (attributes === false || attributes === null) { + return null; + } + const { tr } = state; + const captureGroup = match[match.length - 1]; + const fullMatch = match[0]; + if (captureGroup) { + const startSpaces = fullMatch.search(/\S/); + const textStart = range.from + fullMatch.indexOf(captureGroup); + const textEnd = textStart + captureGroup.length; + const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { + const excluded = item.mark.type.excluded; + return excluded.find((type) => type === config.type && type !== item.mark.type); + }).filter((item) => item.to > textStart); + if (excludedMarks.length) { + return null; + } + if (textEnd < range.to) { + tr.delete(textEnd, range.to); + } + if (textStart > range.from) { + tr.delete(range.from + startSpaces, textStart); + } + const markEnd = range.from + startSpaces + captureGroup.length; + tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); + tr.removeStoredMark(config.type); + } + }, + undoable: config.undoable + }); +} +function nodeInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; + const { tr } = state; + const start = range.from; + let end = range.to; + const newNode = config.type.create(attributes); + if (match[1]) { + const offset = match[0].lastIndexOf(match[1]); + let matchStart = start + offset; + if (matchStart > end) { + matchStart = end; + } else { + end = matchStart + match[1].length; + } + const lastChar = match[0][match[0].length - 1]; + tr.insertText(lastChar, start + match[0].length - 1); + tr.replaceWith(matchStart, end, newNode); + } else if (match[0]) { + const insertionStart = config.type.isInline ? start : start - 1; + tr.insert(insertionStart, config.type.create(attributes)).delete(tr.mapping.map(start), tr.mapping.map(end)); + } + tr.scrollIntoView(); + }, + undoable: config.undoable + }); +} +function textblockTypeInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match }) => { + const $start = state.doc.resolve(range.from); + const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; + if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) { + return null; + } + state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes); + }, + undoable: config.undoable + }); +} +function textInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match }) => { + let insert = config.replace; + let start = range.from; + const end = range.to; + if (match[1]) { + const offset = match[0].lastIndexOf(match[1]); + insert += match[0].slice(offset + match[1].length); + start += offset; + const cutOff = start - end; + if (cutOff > 0) { + insert = match[0].slice(offset - cutOff, offset) + insert; + start = end; + } + } + state.tr.insertText(insert, start, end); + }, + undoable: config.undoable + }); +} +function wrappingInputRule(config) { + return new InputRule({ + find: config.find, + handler: ({ state, range, match, chain }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; + const tr = state.tr.delete(range.from, range.to); + const $start = tr.doc.resolve(range.from); + const blockRange = $start.blockRange(); + const wrapping = blockRange && findWrapping(blockRange, config.type, attributes); + if (!wrapping) { + return null; + } + tr.wrap(blockRange, wrapping); + if (config.keepMarks && config.editor) { + const { selection, storedMarks } = state; + const { splittableMarks } = config.editor.extensionManager; + const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); + if (marks) { + const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); + tr.ensureMarks(filteredMarks); + } + } + if (config.keepAttributes) { + const nodeType = config.type.name === "bulletList" || config.type.name === "orderedList" ? "listItem" : "taskList"; + chain().updateAttributes(nodeType, attributes).run(); + } + const before = tr.doc.resolve(range.from - 1).nodeBefore; + if (before && before.type === config.type && canJoin(tr.doc, range.from - 1) && (!config.joinPredicate || config.joinPredicate(match, before))) { + tr.join(range.from - 1); + } + }, + undoable: config.undoable + }); +} +function Fragment6(props) { + return props.children; +} +var h = (tag, attributes) => { + if (tag === "slot") { + return 0; + } + if (tag instanceof Function) { + return tag(attributes); + } + const { children, ...rest } = attributes != null ? attributes : {}; + if (tag === "svg") { + throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead"); + } + return [tag, rest, children]; +}; +var isTouchEvent = (e) => { + return "touches" in e; +}; +var ResizableNodeView = class { + /** + * Creates a new ResizableNodeView instance. + * + * The constructor sets up the resize handles, applies initial sizing from + * node attributes, and configures all resize behavior options. + * + * @param options - Configuration options for the resizable node view + */ + constructor(options) { + this.directions = ["bottom-left", "bottom-right", "top-left", "top-right"]; + this.minSize = { + height: 8, + width: 8 + }; + this.preserveAspectRatio = false; + this.classNames = { + container: "", + wrapper: "", + handle: "", + resizing: "" + }; + this.initialWidth = 0; + this.initialHeight = 0; + this.aspectRatio = 1; + this.isResizing = false; + this.activeHandle = null; + this.startX = 0; + this.startY = 0; + this.startWidth = 0; + this.startHeight = 0; + this.isShiftKeyPressed = false; + this.lastEditableState = void 0; + this.handleMap = /* @__PURE__ */ new Map(); + this.handleMouseMove = (event) => { + if (!this.isResizing || !this.activeHandle) { + return; + } + const deltaX = event.clientX - this.startX; + const deltaY = event.clientY - this.startY; + this.handleResize(deltaX, deltaY); + }; + this.handleTouchMove = (event) => { + if (!this.isResizing || !this.activeHandle) { + return; + } + const touch = event.touches[0]; + if (!touch) { + return; + } + const deltaX = touch.clientX - this.startX; + const deltaY = touch.clientY - this.startY; + this.handleResize(deltaX, deltaY); + }; + this.handleMouseUp = () => { + if (!this.isResizing) { + return; + } + const finalWidth = this.element.offsetWidth; + const finalHeight = this.element.offsetHeight; + this.onCommit(finalWidth, finalHeight); + this.isResizing = false; + this.activeHandle = null; + this.container.dataset.resizeState = "false"; + if (this.classNames.resizing) { + this.container.classList.remove(this.classNames.resizing); + } + document.removeEventListener("mousemove", this.handleMouseMove); + document.removeEventListener("mouseup", this.handleMouseUp); + document.removeEventListener("keydown", this.handleKeyDown); + document.removeEventListener("keyup", this.handleKeyUp); + }; + this.handleKeyDown = (event) => { + if (event.key === "Shift") { + this.isShiftKeyPressed = true; + } + }; + this.handleKeyUp = (event) => { + if (event.key === "Shift") { + this.isShiftKeyPressed = false; + } + }; + var _a, _b, _c, _d, _e, _f; + this.node = options.node; + this.editor = options.editor; + this.element = options.element; + this.contentElement = options.contentElement; + this.getPos = options.getPos; + this.onResize = options.onResize; + this.onCommit = options.onCommit; + this.onUpdate = options.onUpdate; + if ((_a = options.options) == null ? void 0 : _a.min) { + this.minSize = { + ...this.minSize, + ...options.options.min + }; + } + if ((_b = options.options) == null ? void 0 : _b.max) { + this.maxSize = options.options.max; + } + if ((_c = options == null ? void 0 : options.options) == null ? void 0 : _c.directions) { + this.directions = options.options.directions; + } + if ((_d = options.options) == null ? void 0 : _d.preserveAspectRatio) { + this.preserveAspectRatio = options.options.preserveAspectRatio; + } + if ((_e = options.options) == null ? void 0 : _e.className) { + this.classNames = { + container: options.options.className.container || "", + wrapper: options.options.className.wrapper || "", + handle: options.options.className.handle || "", + resizing: options.options.className.resizing || "" + }; + } + if ((_f = options.options) == null ? void 0 : _f.createCustomHandle) { + this.createCustomHandle = options.options.createCustomHandle; + } + this.wrapper = this.createWrapper(); + this.container = this.createContainer(); + this.applyInitialSize(); + this.attachHandles(); + this.editor.on("update", this.handleEditorUpdate.bind(this)); + } + /** + * Returns the top-level DOM node that should be placed in the editor. + * + * This is required by the ProseMirror NodeView interface. The container + * includes the wrapper, handles, and the actual content element. + * + * @returns The container element to be inserted into the editor + */ + get dom() { + return this.container; + } + get contentDOM() { + var _a; + return (_a = this.contentElement) != null ? _a : null; + } + handleEditorUpdate() { + const isEditable = this.editor.isEditable; + if (isEditable === this.lastEditableState) { + return; + } + this.lastEditableState = isEditable; + if (!isEditable) { + this.removeHandles(); + } else if (isEditable && this.handleMap.size === 0) { + this.attachHandles(); + } + } + /** + * Called when the node's content or attributes change. + * + * Updates the internal node reference. If a custom `onUpdate` callback + * was provided, it will be called to handle additional update logic. + * + * @param node - The new/updated node + * @param decorations - Node decorations + * @param innerDecorations - Inner decorations + * @returns `false` if the node type has changed (requires full rebuild), otherwise the result of `onUpdate` or `true` + */ + update(node, decorations, innerDecorations) { + if (node.type !== this.node.type) { + return false; + } + this.node = node; + if (this.onUpdate) { + return this.onUpdate(node, decorations, innerDecorations); + } + return true; + } + /** + * Cleanup method called when the node view is being removed. + * + * Removes all event listeners to prevent memory leaks. This is required + * by the ProseMirror NodeView interface. If a resize is active when + * destroy is called, it will be properly cancelled. + */ + destroy() { + if (this.isResizing) { + this.container.dataset.resizeState = "false"; + if (this.classNames.resizing) { + this.container.classList.remove(this.classNames.resizing); + } + document.removeEventListener("mousemove", this.handleMouseMove); + document.removeEventListener("mouseup", this.handleMouseUp); + document.removeEventListener("keydown", this.handleKeyDown); + document.removeEventListener("keyup", this.handleKeyUp); + this.isResizing = false; + this.activeHandle = null; + } + this.editor.off("update", this.handleEditorUpdate.bind(this)); + this.container.remove(); + } + /** + * Creates the outer container element. + * + * The container is the top-level element returned by the NodeView and + * wraps the entire resizable node. It's set up with flexbox to handle + * alignment and includes data attributes for styling and identification. + * + * @returns The container element + */ + createContainer() { + const element = document.createElement("div"); + element.dataset.resizeContainer = ""; + element.dataset.node = this.node.type.name; + element.style.display = "flex"; + if (this.classNames.container) { + element.className = this.classNames.container; + } + element.appendChild(this.wrapper); + return element; + } + /** + * Creates the wrapper element that contains the content and handles. + * + * The wrapper uses relative positioning so that resize handles can be + * positioned absolutely within it. This is the direct parent of the + * content element being made resizable. + * + * @returns The wrapper element + */ + createWrapper() { + const element = document.createElement("div"); + element.style.position = "relative"; + element.style.display = "block"; + element.dataset.resizeWrapper = ""; + if (this.classNames.wrapper) { + element.className = this.classNames.wrapper; + } + element.appendChild(this.element); + return element; + } + /** + * Creates a resize handle element for a specific direction. + * + * Each handle is absolutely positioned and includes a data attribute + * identifying its direction for styling purposes. + * + * @param direction - The resize direction for this handle + * @returns The handle element + */ + createHandle(direction) { + const handle = document.createElement("div"); + handle.dataset.resizeHandle = direction; + handle.style.position = "absolute"; + if (this.classNames.handle) { + handle.className = this.classNames.handle; + } + return handle; + } + /** + * Positions a handle element according to its direction. + * + * Corner handles (e.g., 'top-left') are positioned at the intersection + * of two edges. Edge handles (e.g., 'top') span the full width or height. + * + * @param handle - The handle element to position + * @param direction - The direction determining the position + */ + positionHandle(handle, direction) { + const isTop = direction.includes("top"); + const isBottom = direction.includes("bottom"); + const isLeft = direction.includes("left"); + const isRight = direction.includes("right"); + if (isTop) { + handle.style.top = "0"; + } + if (isBottom) { + handle.style.bottom = "0"; + } + if (isLeft) { + handle.style.left = "0"; + } + if (isRight) { + handle.style.right = "0"; + } + if (direction === "top" || direction === "bottom") { + handle.style.left = "0"; + handle.style.right = "0"; + } + if (direction === "left" || direction === "right") { + handle.style.top = "0"; + handle.style.bottom = "0"; + } + } + /** + * Creates and attaches all resize handles to the wrapper. + * + * Iterates through the configured directions, creates a handle for each, + * positions it, attaches the mousedown listener, and appends it to the DOM. + */ + attachHandles() { + this.directions.forEach((direction) => { + let handle; + if (this.createCustomHandle) { + handle = this.createCustomHandle(direction); + } else { + handle = this.createHandle(direction); + } + if (!(handle instanceof HTMLElement)) { + console.warn( + `[ResizableNodeView] createCustomHandle("${direction}") did not return an HTMLElement. Falling back to default handle.` + ); + handle = this.createHandle(direction); + } + if (!this.createCustomHandle) { + this.positionHandle(handle, direction); + } + handle.addEventListener("mousedown", (event) => this.handleResizeStart(event, direction)); + handle.addEventListener("touchstart", (event) => this.handleResizeStart(event, direction)); + this.handleMap.set(direction, handle); + this.wrapper.appendChild(handle); + }); + } + /** + * Removes all resize handles from the wrapper. + * + * Cleans up the handle map and removes each handle element from the DOM. + */ + removeHandles() { + this.handleMap.forEach((el) => el.remove()); + this.handleMap.clear(); + } + /** + * Applies initial sizing from node attributes to the element. + * + * If width/height attributes exist on the node, they're applied to the element. + * Otherwise, the element's natural/current dimensions are measured. The aspect + * ratio is calculated for later use in aspect-ratio-preserving resizes. + */ + applyInitialSize() { + const width = this.node.attrs.width; + const height = this.node.attrs.height; + if (width) { + this.element.style.width = `${width}px`; + this.initialWidth = width; + } else { + this.initialWidth = this.element.offsetWidth; + } + if (height) { + this.element.style.height = `${height}px`; + this.initialHeight = height; + } else { + this.initialHeight = this.element.offsetHeight; + } + if (this.initialWidth > 0 && this.initialHeight > 0) { + this.aspectRatio = this.initialWidth / this.initialHeight; + } + } + /** + * Initiates a resize operation when a handle is clicked. + * + * Captures the starting mouse position and element dimensions, sets up + * the resize state, adds the resizing class and state attribute, and + * attaches document-level listeners for mouse movement and keyboard input. + * + * @param event - The mouse down event + * @param direction - The direction of the handle being dragged + */ + handleResizeStart(event, direction) { + event.preventDefault(); + event.stopPropagation(); + this.isResizing = true; + this.activeHandle = direction; + if (isTouchEvent(event)) { + this.startX = event.touches[0].clientX; + this.startY = event.touches[0].clientY; + } else { + this.startX = event.clientX; + this.startY = event.clientY; + } + this.startWidth = this.element.offsetWidth; + this.startHeight = this.element.offsetHeight; + if (this.startWidth > 0 && this.startHeight > 0) { + this.aspectRatio = this.startWidth / this.startHeight; + } + const pos = this.getPos(); + if (pos !== void 0) { + } + this.container.dataset.resizeState = "true"; + if (this.classNames.resizing) { + this.container.classList.add(this.classNames.resizing); + } + document.addEventListener("mousemove", this.handleMouseMove); + document.addEventListener("touchmove", this.handleTouchMove); + document.addEventListener("mouseup", this.handleMouseUp); + document.addEventListener("keydown", this.handleKeyDown); + document.addEventListener("keyup", this.handleKeyUp); + } + handleResize(deltaX, deltaY) { + if (!this.activeHandle) { + return; + } + const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed; + const { width, height } = this.calculateNewDimensions(this.activeHandle, deltaX, deltaY); + const constrained = this.applyConstraints(width, height, shouldPreserveAspectRatio); + this.element.style.width = `${constrained.width}px`; + this.element.style.height = `${constrained.height}px`; + if (this.onResize) { + this.onResize(constrained.width, constrained.height); + } + } + /** + * Calculates new dimensions based on mouse delta and resize direction. + * + * Takes the starting dimensions and applies the mouse movement delta + * according to the handle direction. For corner handles, both dimensions + * are affected. For edge handles, only one dimension changes. If aspect + * ratio should be preserved, delegates to applyAspectRatio. + * + * @param direction - The active resize handle direction + * @param deltaX - Horizontal mouse movement since resize start + * @param deltaY - Vertical mouse movement since resize start + * @returns The calculated width and height + */ + calculateNewDimensions(direction, deltaX, deltaY) { + let newWidth = this.startWidth; + let newHeight = this.startHeight; + const isRight = direction.includes("right"); + const isLeft = direction.includes("left"); + const isBottom = direction.includes("bottom"); + const isTop = direction.includes("top"); + if (isRight) { + newWidth = this.startWidth + deltaX; + } else if (isLeft) { + newWidth = this.startWidth - deltaX; + } + if (isBottom) { + newHeight = this.startHeight + deltaY; + } else if (isTop) { + newHeight = this.startHeight - deltaY; + } + if (direction === "right" || direction === "left") { + newWidth = this.startWidth + (isRight ? deltaX : -deltaX); + } + if (direction === "top" || direction === "bottom") { + newHeight = this.startHeight + (isBottom ? deltaY : -deltaY); + } + const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed; + if (shouldPreserveAspectRatio) { + return this.applyAspectRatio(newWidth, newHeight, direction); + } + return { width: newWidth, height: newHeight }; + } + /** + * Applies min/max constraints to dimensions. + * + * When aspect ratio is NOT preserved, constraints are applied independently + * to width and height. When aspect ratio IS preserved, constraints are + * applied while maintaining the aspect ratio—if one dimension hits a limit, + * the other is recalculated proportionally. + * + * This ensures that aspect ratio is never broken when constrained. + * + * @param width - The unconstrained width + * @param height - The unconstrained height + * @param preserveAspectRatio - Whether to maintain aspect ratio while constraining + * @returns The constrained dimensions + */ + applyConstraints(width, height, preserveAspectRatio) { + var _a, _b, _c, _d; + if (!preserveAspectRatio) { + let constrainedWidth2 = Math.max(this.minSize.width, width); + let constrainedHeight2 = Math.max(this.minSize.height, height); + if ((_a = this.maxSize) == null ? void 0 : _a.width) { + constrainedWidth2 = Math.min(this.maxSize.width, constrainedWidth2); + } + if ((_b = this.maxSize) == null ? void 0 : _b.height) { + constrainedHeight2 = Math.min(this.maxSize.height, constrainedHeight2); + } + return { width: constrainedWidth2, height: constrainedHeight2 }; + } + let constrainedWidth = width; + let constrainedHeight = height; + if (constrainedWidth < this.minSize.width) { + constrainedWidth = this.minSize.width; + constrainedHeight = constrainedWidth / this.aspectRatio; + } + if (constrainedHeight < this.minSize.height) { + constrainedHeight = this.minSize.height; + constrainedWidth = constrainedHeight * this.aspectRatio; + } + if (((_c = this.maxSize) == null ? void 0 : _c.width) && constrainedWidth > this.maxSize.width) { + constrainedWidth = this.maxSize.width; + constrainedHeight = constrainedWidth / this.aspectRatio; + } + if (((_d = this.maxSize) == null ? void 0 : _d.height) && constrainedHeight > this.maxSize.height) { + constrainedHeight = this.maxSize.height; + constrainedWidth = constrainedHeight * this.aspectRatio; + } + return { width: constrainedWidth, height: constrainedHeight }; + } + /** + * Adjusts dimensions to maintain the original aspect ratio. + * + * For horizontal handles (left/right), uses width as the primary dimension + * and calculates height from it. For vertical handles (top/bottom), uses + * height as primary and calculates width. For corner handles, uses width + * as the primary dimension. + * + * @param width - The new width + * @param height - The new height + * @param direction - The active resize direction + * @returns Dimensions adjusted to preserve aspect ratio + */ + applyAspectRatio(width, height, direction) { + const isHorizontal = direction === "left" || direction === "right"; + const isVertical = direction === "top" || direction === "bottom"; + if (isHorizontal) { + return { + width, + height: width / this.aspectRatio + }; + } + if (isVertical) { + return { + width: height * this.aspectRatio, + height + }; + } + return { + width, + height: width / this.aspectRatio + }; + } +}; +var ResizableNodeview = ResizableNodeView; +function canInsertNode(state, nodeType) { + const { selection } = state; + const { $from } = selection; + if (selection instanceof NodeSelection) { + const index = $from.index(); + const parent = $from.parent; + return parent.canReplaceWith(index, index + 1, nodeType); + } + let depth = $from.depth; + while (depth >= 0) { + const index = $from.index(depth); + const parent = $from.node(depth); + const match = parent.contentMatchAt(index); + if (match.matchType(nodeType)) { + return true; + } + depth -= 1; + } + return false; +} +function escapeForRegEx(string) { + return string.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"); +} +function isFirefox() { + return typeof navigator !== "undefined" ? /Firefox/.test(navigator.userAgent) : false; +} +function isString(value) { + return typeof value === "string"; +} +var markdown_exports = {}; +__export(markdown_exports, { + createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec, + createBlockMarkdownSpec: () => createBlockMarkdownSpec, + createInlineMarkdownSpec: () => createInlineMarkdownSpec, + parseAttributes: () => parseAttributes, + parseIndentedBlocks: () => parseIndentedBlocks, + renderNestedMarkdownContent: () => renderNestedMarkdownContent, + serializeAttributes: () => serializeAttributes +}); +function parseAttributes(attrString) { + if (!(attrString == null ? void 0 : attrString.trim())) { + return {}; + } + const attributes = {}; + const quotedStrings = []; + const tempString = attrString.replace(/["']([^"']*)["']/g, (match) => { + quotedStrings.push(match); + return `__QUOTED_${quotedStrings.length - 1}__`; + }); + const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g); + if (classMatches) { + const classes = classMatches.map((match) => match.trim().slice(1)); + attributes.class = classes.join(" "); + } + const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/); + if (idMatch) { + attributes.id = idMatch[1]; + } + const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g; + const kvMatches = Array.from(tempString.matchAll(kvRegex)); + kvMatches.forEach(([, key, quotedRef]) => { + var _a; + const quotedIndex = parseInt(((_a = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a[1]) || "0", 10); + const quotedValue = quotedStrings[quotedIndex]; + if (quotedValue) { + attributes[key] = quotedValue.slice(1, -1); + } + }); + const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim(); + if (cleanString) { + const booleanAttrs = cleanString.split(/\s+/).filter(Boolean); + booleanAttrs.forEach((attr) => { + if (attr.match(/^[a-zA-Z][\w-]*$/)) { + attributes[attr] = true; + } + }); + } + return attributes; +} +function serializeAttributes(attributes) { + if (!attributes || Object.keys(attributes).length === 0) { + return ""; + } + const parts = []; + if (attributes.class) { + const classes = String(attributes.class).split(/\s+/).filter(Boolean); + classes.forEach((cls) => parts.push(`.${cls}`)); + } + if (attributes.id) { + parts.push(`#${attributes.id}`); + } + Object.entries(attributes).forEach(([key, value]) => { + if (key === "class" || key === "id") { + return; + } + if (value === true) { + parts.push(key); + } else if (value !== false && value != null) { + parts.push(`${key}="${String(value)}"`); + } + }); + return parts.join(" "); +} +function createAtomBlockMarkdownSpec(options) { + const { + nodeName, + name: markdownName, + parseAttributes: parseAttributes2 = parseAttributes, + serializeAttributes: serializeAttributes2 = serializeAttributes, + defaultAttributes = {}, + requiredAttributes = [], + allowedAttributes + } = options; + const blockName = markdownName || nodeName; + const filterAttributes = (attrs) => { + if (!allowedAttributes) { + return attrs; + } + const filtered = {}; + allowedAttributes.forEach((key) => { + if (key in attrs) { + filtered[key] = attrs[key]; + } + }); + return filtered; + }; + return { + parseMarkdown: (token, h2) => { + const attrs = { ...defaultAttributes, ...token.attributes }; + return h2.createNode(nodeName, attrs, []); + }, + markdownTokenizer: { + name: nodeName, + level: "block", + start(src) { + var _a; + const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m"); + const index = (_a = src.match(regex)) == null ? void 0 : _a.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, _tokens, _lexer) { + const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`); + const match = src.match(regex); + if (!match) { + return void 0; + } + const attrString = match[1] || ""; + const attributes = parseAttributes2(attrString); + const missingRequired = requiredAttributes.find((required) => !(required in attributes)); + if (missingRequired) { + return void 0; + } + return { + type: nodeName, + raw: match[0], + attributes + }; + } + }, + renderMarkdown: (node) => { + const filteredAttrs = filterAttributes(node.attrs || {}); + const attrs = serializeAttributes2(filteredAttrs); + const attrString = attrs ? ` {${attrs}}` : ""; + return `:::${blockName}${attrString} :::`; + } + }; +} +function createBlockMarkdownSpec(options) { + const { + nodeName, + name: markdownName, + getContent, + parseAttributes: parseAttributes2 = parseAttributes, + serializeAttributes: serializeAttributes2 = serializeAttributes, + defaultAttributes = {}, + content = "block", + allowedAttributes + } = options; + const blockName = markdownName || nodeName; + const filterAttributes = (attrs) => { + if (!allowedAttributes) { + return attrs; + } + const filtered = {}; + allowedAttributes.forEach((key) => { + if (key in attrs) { + filtered[key] = attrs[key]; + } + }); + return filtered; + }; + return { + parseMarkdown: (token, h2) => { + let nodeContent; + if (getContent) { + const contentResult = getContent(token); + nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult; + } else if (content === "block") { + nodeContent = h2.parseChildren(token.tokens || []); + } else { + nodeContent = h2.parseInline(token.tokens || []); + } + const attrs = { ...defaultAttributes, ...token.attributes }; + return h2.createNode(nodeName, attrs, nodeContent); + }, + markdownTokenizer: { + name: nodeName, + level: "block", + start(src) { + var _a; + const regex = new RegExp(`^:::${blockName}`, "m"); + const index = (_a = src.match(regex)) == null ? void 0 : _a.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, _tokens, lexer) { + var _a; + const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`); + const openingMatch = src.match(openingRegex); + if (!openingMatch) { + return void 0; + } + const [openingTag, attrString = ""] = openingMatch; + const attributes = parseAttributes2(attrString); + let level = 1; + const position = openingTag.length; + let matchedContent = ""; + const blockPattern = /^:::([\w-]*)(\s.*)?/gm; + const remaining = src.slice(position); + blockPattern.lastIndex = 0; + for (; ; ) { + const match = blockPattern.exec(remaining); + if (match === null) { + break; + } + const matchPos = match.index; + const blockType = match[1]; + if ((_a = match[2]) == null ? void 0 : _a.endsWith(":::")) { + continue; + } + if (blockType) { + level += 1; + } else { + level -= 1; + if (level === 0) { + const rawContent = remaining.slice(0, matchPos); + matchedContent = rawContent.trim(); + const fullMatch = src.slice(0, position + matchPos + match[0].length); + let contentTokens = []; + if (matchedContent) { + if (content === "block") { + contentTokens = lexer.blockTokens(rawContent); + contentTokens.forEach((token) => { + if (token.text && (!token.tokens || token.tokens.length === 0)) { + token.tokens = lexer.inlineTokens(token.text); + } + }); + while (contentTokens.length > 0) { + const lastToken = contentTokens[contentTokens.length - 1]; + if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) { + contentTokens.pop(); + } else { + break; + } + } + } else { + contentTokens = lexer.inlineTokens(matchedContent); + } + } + return { + type: nodeName, + raw: fullMatch, + attributes, + content: matchedContent, + tokens: contentTokens + }; + } + } + } + return void 0; + } + }, + renderMarkdown: (node, h2) => { + const filteredAttrs = filterAttributes(node.attrs || {}); + const attrs = serializeAttributes2(filteredAttrs); + const attrString = attrs ? ` {${attrs}}` : ""; + const renderedContent = h2.renderChildren(node.content || [], "\n\n"); + return `:::${blockName}${attrString} + +${renderedContent} + +:::`; + } + }; +} +function parseShortcodeAttributes(attrString) { + if (!attrString.trim()) { + return {}; + } + const attributes = {}; + const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g; + let match = regex.exec(attrString); + while (match !== null) { + const [, key, doubleQuoted, singleQuoted] = match; + attributes[key] = doubleQuoted || singleQuoted; + match = regex.exec(attrString); + } + return attributes; +} +function serializeShortcodeAttributes(attrs) { + return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}="${value}"`).join(" "); +} +function createInlineMarkdownSpec(options) { + const { + nodeName, + name: shortcodeName, + getContent, + parseAttributes: parseAttributes2 = parseShortcodeAttributes, + serializeAttributes: serializeAttributes2 = serializeShortcodeAttributes, + defaultAttributes = {}, + selfClosing = false, + allowedAttributes + } = options; + const shortcode = shortcodeName || nodeName; + const filterAttributes = (attrs) => { + if (!allowedAttributes) { + return attrs; + } + const filtered = {}; + allowedAttributes.forEach((attr) => { + const attrName = typeof attr === "string" ? attr : attr.name; + const skipIfDefault = typeof attr === "string" ? void 0 : attr.skipIfDefault; + if (attrName in attrs) { + const value = attrs[attrName]; + if (skipIfDefault !== void 0 && value === skipIfDefault) { + return; + } + filtered[attrName] = value; + } + }); + return filtered; + }; + const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return { + parseMarkdown: (token, h2) => { + const attrs = { ...defaultAttributes, ...token.attributes }; + if (selfClosing) { + return h2.createNode(nodeName, attrs); + } + const content = getContent ? getContent(token) : token.content || ""; + if (content) { + return h2.createNode(nodeName, attrs, [h2.createTextNode(content)]); + } + return h2.createNode(nodeName, attrs, []); + }, + markdownTokenizer: { + name: nodeName, + level: "inline", + start(src) { + const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`); + const match = src.match(startPattern); + const index = match == null ? void 0 : match.index; + return index !== void 0 ? index : -1; + }, + tokenize(src, _tokens, _lexer) { + const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`); + const match = src.match(tokenPattern); + if (!match) { + return void 0; + } + let content = ""; + let attrString = ""; + if (selfClosing) { + const [, attrs] = match; + attrString = attrs; + } else { + const [, attrs, contentMatch] = match; + attrString = attrs; + content = contentMatch || ""; + } + const attributes = parseAttributes2(attrString.trim()); + return { + type: nodeName, + raw: match[0], + content: content.trim(), + attributes + }; + } + }, + renderMarkdown: (node) => { + let content = ""; + if (getContent) { + content = getContent(node); + } else if (node.content && node.content.length > 0) { + content = node.content.filter((child) => child.type === "text").map((child) => child.text).join(""); + } + const filteredAttrs = filterAttributes(node.attrs || {}); + const attrs = serializeAttributes2(filteredAttrs); + const attrString = attrs ? ` ${attrs}` : ""; + if (selfClosing) { + return `[${shortcode}${attrString}]`; + } + return `[${shortcode}${attrString}]${content}[/${shortcode}]`; + } + }; +} +function parseIndentedBlocks(src, config, lexer) { + var _a, _b, _c, _d; + const lines = src.split("\n"); + const items = []; + let totalRaw = ""; + let i = 0; + const baseIndentSize = config.baseIndentSize || 2; + while (i < lines.length) { + const currentLine = lines[i]; + const itemMatch = currentLine.match(config.itemPattern); + if (!itemMatch) { + if (items.length > 0) { + break; + } else if (currentLine.trim() === "") { + i += 1; + totalRaw = `${totalRaw}${currentLine} +`; + continue; + } else { + return void 0; + } + } + const itemData = config.extractItemData(itemMatch); + const { indentLevel, mainContent } = itemData; + totalRaw = `${totalRaw}${currentLine} +`; + const itemContent = [mainContent]; + i += 1; + while (i < lines.length) { + const nextLine = lines[i]; + if (nextLine.trim() === "") { + const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== ""); + if (nextNonEmptyIndex === -1) { + break; + } + const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex]; + const nextIndent2 = ((_b = (_a = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.length) || 0; + if (nextIndent2 > indentLevel) { + itemContent.push(nextLine); + totalRaw = `${totalRaw}${nextLine} +`; + i += 1; + continue; + } else { + break; + } + } + const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0; + if (nextIndent > indentLevel) { + itemContent.push(nextLine); + totalRaw = `${totalRaw}${nextLine} +`; + i += 1; + } else { + break; + } + } + let nestedTokens; + const nestedContent = itemContent.slice(1); + if (nestedContent.length > 0) { + const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n"); + if (dedentedNested.trim()) { + if (config.customNestedParser) { + nestedTokens = config.customNestedParser(dedentedNested); + } else { + nestedTokens = lexer.blockTokens(dedentedNested); + } + } + } + const token = config.createToken(itemData, nestedTokens); + items.push(token); + } + if (items.length === 0) { + return void 0; + } + return { + items, + raw: totalRaw + }; +} +function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx) { + if (!node || !Array.isArray(node.content)) { + return ""; + } + const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator; + const [content, ...children] = node.content; + const mainContent = h2.renderChildren([content]); + const output = [`${prefix}${mainContent}`]; + if (children && children.length > 0) { + children.forEach((child) => { + const childContent = h2.renderChildren([child]); + if (childContent) { + const indentedChild = childContent.split("\n").map((line) => line ? h2.indent(line) : "").join("\n"); + output.push(indentedChild); + } + }); + } + return output.join("\n"); +} +function updateMarkViewAttributes(checkMark, editor, attrs = {}) { + const { state } = editor; + const { doc: doc3, tr } = state; + const thisMark = checkMark; + doc3.descendants((node, pos) => { + const from = tr.mapping.map(pos); + const to = tr.mapping.map(pos) + node.nodeSize; + let foundMark = null; + node.marks.forEach((mark) => { + if (mark !== thisMark) { + return false; + } + foundMark = mark; + }); + if (!foundMark) { + return; + } + let needsUpdate = false; + Object.keys(attrs).forEach((k) => { + if (attrs[k] !== foundMark.attrs[k]) { + needsUpdate = true; + } + }); + if (needsUpdate) { + const updatedMark = checkMark.type.create({ + ...checkMark.attrs, + ...attrs + }); + tr.removeMark(from, to, checkMark.type); + tr.addMark(from, to, updatedMark); + } + }); + if (tr.docChanged) { + editor.view.dispatch(tr); + } +} +var MarkView = class { + constructor(component, props, options) { + this.component = component; + this.editor = props.editor; + this.options = { ...options }; + this.mark = props.mark; + this.HTMLAttributes = props.HTMLAttributes; + } + get dom() { + return this.editor.view.dom; + } + get contentDOM() { + return null; + } + /** + * Update the attributes of the mark in the document. + * @param attrs The attributes to update. + */ + updateAttributes(attrs, checkMark) { + updateMarkViewAttributes(checkMark || this.mark, this.editor, attrs); + } + ignoreMutation(mutation) { + if (!this.dom || !this.contentDOM) { + return true; + } + if (typeof this.options.ignoreMutation === "function") { + return this.options.ignoreMutation({ mutation }); + } + if (mutation.type === "selection") { + return false; + } + if (this.dom.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid()) && this.editor.isFocused) { + const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)]; + if (changedNodes.every((node) => node.isContentEditable)) { + return false; + } + } + if (this.contentDOM === mutation.target && mutation.type === "attributes") { + return true; + } + if (this.contentDOM.contains(mutation.target)) { + return false; + } + return true; + } +}; +var Node3 = class _Node extends Extendable { + constructor() { + super(...arguments); + this.type = "node"; + } + /** + * Create a new Node instance + * @param config - Node configuration object or a function that returns a configuration object + */ + static create(config = {}) { + const resolvedConfig = typeof config === "function" ? config() : config; + return new _Node(resolvedConfig); + } + configure(options) { + return super.configure(options); + } + extend(extendedConfig) { + const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; + return super.extend(resolvedConfig); + } +}; +var NodeView = class { + constructor(component, props, options) { + this.isDragging = false; + this.component = component; + this.editor = props.editor; + this.options = { + stopEvent: null, + ignoreMutation: null, + ...options + }; + this.extension = props.extension; + this.node = props.node; + this.decorations = props.decorations; + this.innerDecorations = props.innerDecorations; + this.view = props.view; + this.HTMLAttributes = props.HTMLAttributes; + this.getPos = props.getPos; + this.mount(); + } + mount() { + return; + } + get dom() { + return this.editor.view.dom; + } + get contentDOM() { + return null; + } + onDragStart(event) { + var _a, _b, _c, _d, _e, _f, _g; + const { view } = this.editor; + const target = event.target; + const dragHandle = target.nodeType === 3 ? (_a = target.parentElement) == null ? void 0 : _a.closest("[data-drag-handle]") : target.closest("[data-drag-handle]"); + if (!this.dom || ((_b = this.contentDOM) == null ? void 0 : _b.contains(target)) || !dragHandle) { + return; + } + let x = 0; + let y = 0; + if (this.dom !== dragHandle) { + const domBox = this.dom.getBoundingClientRect(); + const handleBox = dragHandle.getBoundingClientRect(); + const offsetX = (_d = event.offsetX) != null ? _d : (_c = event.nativeEvent) == null ? void 0 : _c.offsetX; + const offsetY = (_f = event.offsetY) != null ? _f : (_e = event.nativeEvent) == null ? void 0 : _e.offsetY; + x = handleBox.x - domBox.x + offsetX; + y = handleBox.y - domBox.y + offsetY; + } + const clonedNode = this.dom.cloneNode(true); + try { + const domBox = this.dom.getBoundingClientRect(); + clonedNode.style.width = `${Math.round(domBox.width)}px`; + clonedNode.style.height = `${Math.round(domBox.height)}px`; + clonedNode.style.boxSizing = "border-box"; + clonedNode.style.pointerEvents = "none"; + } catch { + } + let dragImageWrapper = null; + try { + dragImageWrapper = document.createElement("div"); + dragImageWrapper.style.position = "absolute"; + dragImageWrapper.style.top = "-9999px"; + dragImageWrapper.style.left = "-9999px"; + dragImageWrapper.style.pointerEvents = "none"; + dragImageWrapper.appendChild(clonedNode); + document.body.appendChild(dragImageWrapper); + (_g = event.dataTransfer) == null ? void 0 : _g.setDragImage(clonedNode, x, y); + } finally { + if (dragImageWrapper) { + setTimeout(() => { + try { + dragImageWrapper == null ? void 0 : dragImageWrapper.remove(); + } catch { + } + }, 0); + } + } + const pos = this.getPos(); + if (typeof pos !== "number") { + return; + } + const selection = NodeSelection.create(view.state.doc, pos); + const transaction = view.state.tr.setSelection(selection); + view.dispatch(transaction); + } + stopEvent(event) { + var _a; + if (!this.dom) { + return false; + } + if (typeof this.options.stopEvent === "function") { + return this.options.stopEvent({ event }); + } + const target = event.target; + const isInElement = this.dom.contains(target) && !((_a = this.contentDOM) == null ? void 0 : _a.contains(target)); + if (!isInElement) { + return false; + } + const isDragEvent = event.type.startsWith("drag"); + const isDropEvent = event.type === "drop"; + const isInput = ["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(target.tagName) || target.isContentEditable; + if (isInput && !isDropEvent && !isDragEvent) { + return true; + } + const { isEditable } = this.editor; + const { isDragging } = this; + const isDraggable = !!this.node.type.spec.draggable; + const isSelectable = NodeSelection.isSelectable(this.node); + const isCopyEvent = event.type === "copy"; + const isPasteEvent = event.type === "paste"; + const isCutEvent = event.type === "cut"; + const isClickEvent = event.type === "mousedown"; + if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) { + event.preventDefault(); + } + if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) { + event.preventDefault(); + return false; + } + if (isDraggable && isEditable && !isDragging && isClickEvent) { + const dragHandle = target.closest("[data-drag-handle]"); + const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle)); + if (isValidDragHandle) { + this.isDragging = true; + document.addEventListener( + "dragend", + () => { + this.isDragging = false; + }, + { once: true } + ); + document.addEventListener( + "drop", + () => { + this.isDragging = false; + }, + { once: true } + ); + document.addEventListener( + "mouseup", + () => { + this.isDragging = false; + }, + { once: true } + ); + } + } + if (isDragging || isDropEvent || isCopyEvent || isPasteEvent || isCutEvent || isClickEvent && isSelectable) { + return false; + } + return true; + } + /** + * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view. + * @return `false` if the editor should re-read the selection or re-parse the range around the mutation + * @return `true` if it can safely be ignored. + */ + ignoreMutation(mutation) { + if (!this.dom || !this.contentDOM) { + return true; + } + if (typeof this.options.ignoreMutation === "function") { + return this.options.ignoreMutation({ mutation }); + } + if (this.node.isLeaf || this.node.isAtom) { + return true; + } + if (mutation.type === "selection") { + return false; + } + if (this.dom.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid()) && this.editor.isFocused) { + const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)]; + if (changedNodes.every((node) => node.isContentEditable)) { + return false; + } + } + if (this.contentDOM === mutation.target && mutation.type === "attributes") { + return true; + } + if (this.contentDOM.contains(mutation.target)) { + return false; + } + return true; + } + /** + * Update the attributes of the prosemirror node. + */ + updateAttributes(attributes) { + this.editor.commands.command(({ tr }) => { + const pos = this.getPos(); + if (typeof pos !== "number") { + return false; + } + tr.setNodeMarkup(pos, void 0, { + ...this.node.attrs, + ...attributes + }); + return true; + }); + } + /** + * Delete the node. + */ + deleteNode() { + const from = this.getPos(); + if (typeof from !== "number") { + return; + } + const to = from + this.node.nodeSize; + this.editor.commands.deleteRange({ from, to }); + } +}; +function markPasteRule(config) { + return new PasteRule({ + find: config.find, + handler: ({ state, range, match, pasteEvent }) => { + const attributes = callOrReturn(config.getAttributes, void 0, match, pasteEvent); + if (attributes === false || attributes === null) { + return null; + } + const { tr } = state; + const captureGroup = match[match.length - 1]; + const fullMatch = match[0]; + let markEnd = range.to; + if (captureGroup) { + const startSpaces = fullMatch.search(/\S/); + const textStart = range.from + fullMatch.indexOf(captureGroup); + const textEnd = textStart + captureGroup.length; + const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { + const excluded = item.mark.type.excluded; + return excluded.find((type) => type === config.type && type !== item.mark.type); + }).filter((item) => item.to > textStart); + if (excludedMarks.length) { + return null; + } + if (textEnd < range.to) { + tr.delete(textEnd, range.to); + } + if (textStart > range.from) { + tr.delete(range.from + startSpaces, textStart); + } + markEnd = range.from + startSpaces + captureGroup.length; + tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); + tr.removeStoredMark(config.type); + } + } + }); +} +function nodePasteRule(config) { + return new PasteRule({ + find: config.find, + handler({ match, chain, range, pasteEvent }) { + const attributes = callOrReturn(config.getAttributes, void 0, match, pasteEvent); + const content = callOrReturn(config.getContent, void 0, attributes); + if (attributes === false || attributes === null) { + return null; + } + const node = { type: config.type.name, attrs: attributes }; + if (content) { + node.content = content; + } + if (match.input) { + chain().deleteRange(range).insertContentAt(range.from, node); + } + } + }); +} +function textPasteRule(config) { + return new PasteRule({ + find: config.find, + handler: ({ state, range, match }) => { + let insert = config.replace; + let start = range.from; + const end = range.to; + if (match[1]) { + const offset = match[0].lastIndexOf(match[1]); + insert += match[0].slice(offset + match[1].length); + start += offset; + const cutOff = start - end; + if (cutOff > 0) { + insert = match[0].slice(offset - cutOff, offset) + insert; + start = end; + } + } + state.tr.insertText(insert, start, end); + } + }); +} +var Tracker = class { + constructor(transaction) { + this.transaction = transaction; + this.currentStep = this.transaction.steps.length; + } + map(position) { + let deleted = false; + const mappedPosition = this.transaction.steps.slice(this.currentStep).reduce((newPosition, step) => { + const mapResult = step.getMap().mapResult(newPosition); + if (mapResult.deleted) { + deleted = true; + } + return mapResult.pos; + }, position); + return { + position: mappedPosition, + deleted + }; + } +}; + +export { + Fragment, + Slice, + Mapping, + dropPoint, + Selection, + TextSelection, + NodeSelection, + Plugin, + PluginKey, + Decoration, + DecorationSet, + keydownHandler, + createChainableState, + CommandManager, + commands_exports, + getNodeType, + isRegExp, + objectIncludes, + getMarkRange, + getMarkType, + isTextSelection, + minMax, + resolveFocusPosition, + isAndroid, + isiOS, + isSafari, + elementFromString, + createNodeFromContent, + selectionToInsertionEnd2 as selectionToInsertionEnd, + isMacOS, + isNodeActive, + getSchemaTypeNameByName, + deleteProps, + createDocument, + getMarkAttributes, + combineTransactionSteps, + defaultBlockAt2 as defaultBlockAt, + findChildren, + findChildrenInRange, + findParentNodeClosestToPos, + findParentNode, + getExtensionField, + flattenExtensions, + getHTMLFromFragment, + isFunction, + callOrReturn, + isEmptyObject, + splitExtensions, + getAttributesFromExtensions, + mergeAttributes, + getRenderedAttributes, + fromString, + injectExtensionAttributesToParseRule, + getSchemaByResolvedExtensions, + findDuplicates, + sortExtensions, + resolveExtensions, + getSchema, + generateHTML, + generateJSON, + getTextBetween, + getText2 as getText, + getTextSerializersFromSchema, + generateText, + getNodeAttributes, + getAttributes, + removeDuplicates, + getChangedRanges, + getDebugJSON, + getMarksBetween, + getNodeAtPosition, + getSchemaTypeByName, + getSplittedAttributes, + getTextContentFromNodes, + isMarkActive, + isActive, + isAtEndOfNode, + isAtStartOfNode, + isExtensionRulesEnabled, + isList, + isNodeEmpty, + isNodeSelection, + MappablePosition, + getUpdatedPosition, + createMappablePosition, + posToDOMRect, + rewriteUnknownContent, + InputRule, + inputRulesPlugin, + isPlainObject, + mergeDeep, + Extendable, + Mark2 as Mark, + isNumber, + PasteRule, + pasteRulesPlugin, + extensions_exports, + Extension, + NodePos, + createStyleTag, + Editor, + markInputRule, + nodeInputRule, + textblockTypeInputRule, + textInputRule, + wrappingInputRule, + Fragment6, + h, + ResizableNodeView, + ResizableNodeview, + canInsertNode, + escapeForRegEx, + isFirefox, + isString, + markdown_exports, + parseAttributes, + serializeAttributes, + createAtomBlockMarkdownSpec, + createBlockMarkdownSpec, + createInlineMarkdownSpec, + parseIndentedBlocks, + renderNestedMarkdownContent, + updateMarkViewAttributes, + MarkView, + Node3, + NodeView, + markPasteRule, + nodePasteRule, + textPasteRule, + Tracker +}; +//# sourceMappingURL=chunk-YRIELJS7.js.map diff --git a/frontend/node_modules/.vite/deps/chunk-YRIELJS7.js.map b/frontend/node_modules/.vite/deps/chunk-YRIELJS7.js.map new file mode 100644 index 00000000..4713f977 --- /dev/null +++ b/frontend/node_modules/.vite/deps/chunk-YRIELJS7.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../orderedmap/dist/index.js", "../../prosemirror-model/dist/index.js", "../../prosemirror-transform/dist/index.js", "../../prosemirror-state/dist/index.js", "../../prosemirror-commands/dist/index.js", "../../prosemirror-schema-list/dist/index.js", "../../prosemirror-view/dist/index.js", "../../w3c-keyname/index.js", "../../prosemirror-keymap/dist/index.js", "../../@tiptap/core/src/helpers/createChainableState.ts", "../../@tiptap/core/src/CommandManager.ts", "../../@tiptap/core/src/commands/index.ts", "../../@tiptap/core/src/commands/blur.ts", "../../@tiptap/core/src/commands/clearContent.ts", "../../@tiptap/core/src/commands/clearNodes.ts", "../../@tiptap/core/src/commands/command.ts", "../../@tiptap/core/src/commands/createParagraphNear.ts", "../../@tiptap/core/src/commands/cut.ts", "../../@tiptap/core/src/commands/deleteCurrentNode.ts", "../../@tiptap/core/src/helpers/getNodeType.ts", "../../@tiptap/core/src/commands/deleteNode.ts", "../../@tiptap/core/src/commands/deleteRange.ts", "../../@tiptap/core/src/commands/deleteSelection.ts", "../../@tiptap/core/src/commands/enter.ts", "../../@tiptap/core/src/commands/exitCode.ts", "../../@tiptap/core/src/commands/extendMarkRange.ts", "../../@tiptap/core/src/utilities/isRegExp.ts", "../../@tiptap/core/src/utilities/objectIncludes.ts", "../../@tiptap/core/src/helpers/getMarkRange.ts", "../../@tiptap/core/src/helpers/getMarkType.ts", "../../@tiptap/core/src/commands/first.ts", "../../@tiptap/core/src/helpers/isTextSelection.ts", "../../@tiptap/core/src/helpers/resolveFocusPosition.ts", "../../@tiptap/core/src/utilities/minMax.ts", "../../@tiptap/core/src/utilities/isAndroid.ts", "../../@tiptap/core/src/utilities/isiOS.ts", "../../@tiptap/core/src/utilities/isSafari.ts", "../../@tiptap/core/src/commands/focus.ts", "../../@tiptap/core/src/commands/forEach.ts", "../../@tiptap/core/src/commands/insertContent.ts", "../../@tiptap/core/src/commands/insertContentAt.ts", "../../@tiptap/core/src/helpers/createNodeFromContent.ts", "../../@tiptap/core/src/utilities/elementFromString.ts", "../../@tiptap/core/src/helpers/selectionToInsertionEnd.ts", "../../@tiptap/core/src/commands/join.ts", "../../@tiptap/core/src/commands/joinItemBackward.ts", "../../@tiptap/core/src/commands/joinItemForward.ts", "../../@tiptap/core/src/commands/joinTextblockBackward.ts", "../../@tiptap/core/src/commands/joinTextblockForward.ts", "../../@tiptap/core/src/utilities/isMacOS.ts", "../../@tiptap/core/src/commands/keyboardShortcut.ts", "../../@tiptap/core/src/commands/lift.ts", "../../@tiptap/core/src/helpers/isNodeActive.ts", "../../@tiptap/core/src/commands/liftEmptyBlock.ts", "../../@tiptap/core/src/commands/liftListItem.ts", "../../@tiptap/core/src/commands/newlineInCode.ts", "../../@tiptap/core/src/helpers/getSchemaTypeNameByName.ts", "../../@tiptap/core/src/utilities/deleteProps.ts", "../../@tiptap/core/src/commands/resetAttributes.ts", "../../@tiptap/core/src/commands/scrollIntoView.ts", "../../@tiptap/core/src/commands/selectAll.ts", "../../@tiptap/core/src/commands/selectNodeBackward.ts", "../../@tiptap/core/src/commands/selectNodeForward.ts", "../../@tiptap/core/src/commands/selectParentNode.ts", "../../@tiptap/core/src/commands/selectTextblockEnd.ts", "../../@tiptap/core/src/commands/selectTextblockStart.ts", "../../@tiptap/core/src/helpers/createDocument.ts", "../../@tiptap/core/src/commands/setContent.ts", "../../@tiptap/core/src/helpers/getMarkAttributes.ts", "../../@tiptap/core/src/helpers/combineTransactionSteps.ts", "../../@tiptap/core/src/helpers/defaultBlockAt.ts", "../../@tiptap/core/src/helpers/findChildren.ts", "../../@tiptap/core/src/helpers/findChildrenInRange.ts", "../../@tiptap/core/src/helpers/findParentNodeClosestToPos.ts", "../../@tiptap/core/src/helpers/findParentNode.ts", "../../@tiptap/core/src/helpers/getExtensionField.ts", "../../@tiptap/core/src/helpers/flattenExtensions.ts", "../../@tiptap/core/src/helpers/generateHTML.ts", "../../@tiptap/core/src/helpers/getHTMLFromFragment.ts", "../../@tiptap/core/src/helpers/getSchemaByResolvedExtensions.ts", "../../@tiptap/core/src/utilities/isFunction.ts", "../../@tiptap/core/src/utilities/callOrReturn.ts", "../../@tiptap/core/src/utilities/isEmptyObject.ts", "../../@tiptap/core/src/helpers/splitExtensions.ts", "../../@tiptap/core/src/helpers/getAttributesFromExtensions.ts", "../../@tiptap/core/src/utilities/mergeAttributes.ts", "../../@tiptap/core/src/helpers/getRenderedAttributes.ts", "../../@tiptap/core/src/utilities/fromString.ts", "../../@tiptap/core/src/helpers/injectExtensionAttributesToParseRule.ts", "../../@tiptap/core/src/utilities/findDuplicates.ts", "../../@tiptap/core/src/helpers/sortExtensions.ts", "../../@tiptap/core/src/helpers/resolveExtensions.ts", "../../@tiptap/core/src/helpers/getSchema.ts", "../../@tiptap/core/src/helpers/generateJSON.ts", "../../@tiptap/core/src/helpers/generateText.ts", "../../@tiptap/core/src/helpers/getTextBetween.ts", "../../@tiptap/core/src/helpers/getText.ts", "../../@tiptap/core/src/helpers/getTextSerializersFromSchema.ts", "../../@tiptap/core/src/helpers/getNodeAttributes.ts", "../../@tiptap/core/src/helpers/getAttributes.ts", "../../@tiptap/core/src/utilities/removeDuplicates.ts", "../../@tiptap/core/src/helpers/getChangedRanges.ts", "../../@tiptap/core/src/helpers/getDebugJSON.ts", "../../@tiptap/core/src/helpers/getMarksBetween.ts", "../../@tiptap/core/src/helpers/getNodeAtPosition.ts", "../../@tiptap/core/src/helpers/getSchemaTypeByName.ts", "../../@tiptap/core/src/helpers/getSplittedAttributes.ts", "../../@tiptap/core/src/helpers/getTextContentFromNodes.ts", "../../@tiptap/core/src/helpers/isMarkActive.ts", "../../@tiptap/core/src/helpers/isActive.ts", "../../@tiptap/core/src/helpers/isAtEndOfNode.ts", "../../@tiptap/core/src/helpers/isAtStartOfNode.ts", "../../@tiptap/core/src/helpers/isExtensionRulesEnabled.ts", "../../@tiptap/core/src/helpers/isList.ts", "../../@tiptap/core/src/helpers/isNodeEmpty.ts", "../../@tiptap/core/src/helpers/isNodeSelection.ts", "../../@tiptap/core/src/helpers/MappablePosition.ts", "../../@tiptap/core/src/helpers/posToDOMRect.ts", "../../@tiptap/core/src/helpers/rewriteUnknownContent.ts", "../../@tiptap/core/src/commands/setMark.ts", "../../@tiptap/core/src/commands/setMeta.ts", "../../@tiptap/core/src/commands/setNode.ts", "../../@tiptap/core/src/commands/setNodeSelection.ts", "../../@tiptap/core/src/commands/setTextDirection.ts", "../../@tiptap/core/src/commands/setTextSelection.ts", "../../@tiptap/core/src/commands/sinkListItem.ts", "../../@tiptap/core/src/commands/splitBlock.ts", "../../@tiptap/core/src/commands/splitListItem.ts", "../../@tiptap/core/src/commands/toggleList.ts", "../../@tiptap/core/src/commands/toggleMark.ts", "../../@tiptap/core/src/commands/toggleNode.ts", "../../@tiptap/core/src/commands/toggleWrap.ts", "../../@tiptap/core/src/commands/undoInputRule.ts", "../../@tiptap/core/src/commands/unsetAllMarks.ts", "../../@tiptap/core/src/commands/unsetMark.ts", "../../@tiptap/core/src/commands/unsetTextDirection.ts", "../../@tiptap/core/src/commands/updateAttributes.ts", "../../@tiptap/core/src/commands/wrapIn.ts", "../../@tiptap/core/src/commands/wrapInList.ts", "../../@tiptap/core/src/Editor.ts", "../../@tiptap/core/src/EventEmitter.ts", "../../@tiptap/core/src/ExtensionManager.ts", "../../@tiptap/core/src/InputRule.ts", "../../@tiptap/core/src/utilities/isPlainObject.ts", "../../@tiptap/core/src/utilities/mergeDeep.ts", "../../@tiptap/core/src/Extendable.ts", "../../@tiptap/core/src/Mark.ts", "../../@tiptap/core/src/PasteRule.ts", "../../@tiptap/core/src/utilities/isNumber.ts", "../../@tiptap/core/src/extensions/index.ts", "../../@tiptap/core/src/extensions/clipboardTextSerializer.ts", "../../@tiptap/core/src/Extension.ts", "../../@tiptap/core/src/extensions/commands.ts", "../../@tiptap/core/src/extensions/delete.ts", "../../@tiptap/core/src/extensions/drop.ts", "../../@tiptap/core/src/extensions/editable.ts", "../../@tiptap/core/src/extensions/focusEvents.ts", "../../@tiptap/core/src/extensions/keymap.ts", "../../@tiptap/core/src/extensions/paste.ts", "../../@tiptap/core/src/extensions/tabindex.ts", "../../@tiptap/core/src/extensions/textDirection.ts", "../../@tiptap/core/src/NodePos.ts", "../../@tiptap/core/src/style.ts", "../../@tiptap/core/src/utilities/createStyleTag.ts", "../../@tiptap/core/src/inputRules/markInputRule.ts", "../../@tiptap/core/src/inputRules/nodeInputRule.ts", "../../@tiptap/core/src/inputRules/textblockTypeInputRule.ts", "../../@tiptap/core/src/inputRules/textInputRule.ts", "../../@tiptap/core/src/inputRules/wrappingInputRule.ts", "../../@tiptap/core/src/jsx-runtime.ts", "../../@tiptap/core/src/lib/ResizableNodeView.ts", "../../@tiptap/core/src/utilities/canInsertNode.ts", "../../@tiptap/core/src/utilities/escapeForRegEx.ts", "../../@tiptap/core/src/utilities/isFirefox.ts", "../../@tiptap/core/src/utilities/isString.ts", "../../@tiptap/core/src/utilities/markdown/index.ts", "../../@tiptap/core/src/utilities/markdown/attributeUtils.ts", "../../@tiptap/core/src/utilities/markdown/createAtomBlockMarkdownSpec.ts", "../../@tiptap/core/src/utilities/markdown/createBlockMarkdownSpec.ts", "../../@tiptap/core/src/utilities/markdown/createInlineMarkdownSpec.ts", "../../@tiptap/core/src/utilities/markdown/parseIndentedBlocks.ts", "../../@tiptap/core/src/utilities/markdown/renderNestedMarkdownContent.ts", "../../@tiptap/core/src/MarkView.ts", "../../@tiptap/core/src/Node.ts", "../../@tiptap/core/src/NodeView.ts", "../../@tiptap/core/src/pasteRules/markPasteRule.ts", "../../@tiptap/core/src/pasteRules/nodePasteRule.ts", "../../@tiptap/core/src/pasteRules/textPasteRule.ts", "../../@tiptap/core/src/Tracker.ts"], + "sourcesContent": ["// ::- Persistent data structure representing an ordered mapping from\n// strings to values, with some convenient update methods.\nfunction OrderedMap(content) {\n this.content = content;\n}\n\nOrderedMap.prototype = {\n constructor: OrderedMap,\n\n find: function(key) {\n for (var i = 0; i < this.content.length; i += 2)\n if (this.content[i] === key) return i\n return -1\n },\n\n // :: (string) → ?any\n // Retrieve the value stored under `key`, or return undefined when\n // no such key exists.\n get: function(key) {\n var found = this.find(key);\n return found == -1 ? undefined : this.content[found + 1]\n },\n\n // :: (string, any, ?string) → OrderedMap\n // Create a new map by replacing the value of `key` with a new\n // value, or adding a binding to the end of the map. If `newKey` is\n // given, the key of the binding will be replaced with that key.\n update: function(key, value, newKey) {\n var self = newKey && newKey != key ? this.remove(newKey) : this;\n var found = self.find(key), content = self.content.slice();\n if (found == -1) {\n content.push(newKey || key, value);\n } else {\n content[found + 1] = value;\n if (newKey) content[found] = newKey;\n }\n return new OrderedMap(content)\n },\n\n // :: (string) → OrderedMap\n // Return a map with the given key removed, if it existed.\n remove: function(key) {\n var found = this.find(key);\n if (found == -1) return this\n var content = this.content.slice();\n content.splice(found, 2);\n return new OrderedMap(content)\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the start of the map.\n addToStart: function(key, value) {\n return new OrderedMap([key, value].concat(this.remove(key).content))\n },\n\n // :: (string, any) → OrderedMap\n // Add a new key to the end of the map.\n addToEnd: function(key, value) {\n var content = this.remove(key).content.slice();\n content.push(key, value);\n return new OrderedMap(content)\n },\n\n // :: (string, string, any) → OrderedMap\n // Add a key after the given key. If `place` is not found, the new\n // key is added to the end.\n addBefore: function(place, key, value) {\n var without = this.remove(key), content = without.content.slice();\n var found = without.find(place);\n content.splice(found == -1 ? content.length : found, 0, key, value);\n return new OrderedMap(content)\n },\n\n // :: ((key: string, value: any))\n // Call the given function for each key/value pair in the map, in\n // order.\n forEach: function(f) {\n for (var i = 0; i < this.content.length; i += 2)\n f(this.content[i], this.content[i + 1]);\n },\n\n // :: (union) → OrderedMap\n // Create a new map by prepending the keys in this map that don't\n // appear in `map` before the keys in `map`.\n prepend: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(map.content.concat(this.subtract(map).content))\n },\n\n // :: (union) → OrderedMap\n // Create a new map by appending the keys in this map that don't\n // appear in `map` after the keys in `map`.\n append: function(map) {\n map = OrderedMap.from(map);\n if (!map.size) return this\n return new OrderedMap(this.subtract(map).content.concat(map.content))\n },\n\n // :: (union) → OrderedMap\n // Create a map containing all the keys in this map that don't\n // appear in `map`.\n subtract: function(map) {\n var result = this;\n map = OrderedMap.from(map);\n for (var i = 0; i < map.content.length; i += 2)\n result = result.remove(map.content[i]);\n return result\n },\n\n // :: () → Object\n // Turn ordered map into a plain object.\n toObject: function() {\n var result = {};\n this.forEach(function(key, value) { result[key] = value; });\n return result\n },\n\n // :: number\n // The amount of keys in this map.\n get size() {\n return this.content.length >> 1\n }\n};\n\n// :: (?union) → OrderedMap\n// Return a map with the given content. If null, create an empty\n// map. If given an ordered map, return that map itself. If given an\n// object, create a map from the object's properties.\nOrderedMap.from = function(value) {\n if (value instanceof OrderedMap) return value\n var content = [];\n if (value) for (var prop in value) content.push(prop, value[prop]);\n return new OrderedMap(content)\n};\n\nexport default OrderedMap;\n", "import OrderedMap from 'orderedmap';\n\nfunction findDiffStart(a, b, pos) {\n for (let i = 0;; i++) {\n if (i == a.childCount || i == b.childCount)\n return a.childCount == b.childCount ? null : pos;\n let childA = a.child(i), childB = b.child(i);\n if (childA == childB) {\n pos += childA.nodeSize;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return pos;\n if (childA.isText && childA.text != childB.text) {\n for (let j = 0; childA.text[j] == childB.text[j]; j++)\n pos++;\n return pos;\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffStart(childA.content, childB.content, pos + 1);\n if (inner != null)\n return inner;\n }\n pos += childA.nodeSize;\n }\n}\nfunction findDiffEnd(a, b, posA, posB) {\n for (let iA = a.childCount, iB = b.childCount;;) {\n if (iA == 0 || iB == 0)\n return iA == iB ? null : { a: posA, b: posB };\n let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize;\n if (childA == childB) {\n posA -= size;\n posB -= size;\n continue;\n }\n if (!childA.sameMarkup(childB))\n return { a: posA, b: posB };\n if (childA.isText && childA.text != childB.text) {\n let same = 0, minSize = Math.min(childA.text.length, childB.text.length);\n while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {\n same++;\n posA--;\n posB--;\n }\n return { a: posA, b: posB };\n }\n if (childA.content.size || childB.content.size) {\n let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);\n if (inner)\n return inner;\n }\n posA -= size;\n posB -= size;\n }\n}\n\n/**\nA fragment represents a node's collection of child nodes.\n\nLike nodes, fragments are persistent data structures, and you\nshould not mutate them or their content. Rather, you create new\ninstances whenever needed. The API tries to make this easy.\n*/\nclass Fragment {\n /**\n @internal\n */\n constructor(\n /**\n The child nodes in this fragment.\n */\n content, size) {\n this.content = content;\n this.size = size || 0;\n if (size == null)\n for (let i = 0; i < content.length; i++)\n this.size += content[i].nodeSize;\n }\n /**\n Invoke a callback for all descendant nodes between the given two\n positions (relative to start of this fragment). Doesn't descend\n into a node when the callback returns `false`.\n */\n nodesBetween(from, to, f, nodeStart = 0, parent) {\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {\n let start = pos + 1;\n child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start);\n }\n pos = end;\n }\n }\n /**\n Call the given callback for every descendant node. `pos` will be\n relative to the start of the fragment. The callback may return\n `false` to prevent traversal of a given node's children.\n */\n descendants(f) {\n this.nodesBetween(0, this.size, f);\n }\n /**\n Extract the text between `from` and `to`. See the same method on\n [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).\n */\n textBetween(from, to, blockSeparator, leafText) {\n let text = \"\", first = true;\n this.nodesBetween(from, to, (node, pos) => {\n let nodeText = node.isText ? node.text.slice(Math.max(from, pos) - pos, to - pos)\n : !node.isLeaf ? \"\"\n : leafText ? (typeof leafText === \"function\" ? leafText(node) : leafText)\n : node.type.spec.leafText ? node.type.spec.leafText(node)\n : \"\";\n if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {\n if (first)\n first = false;\n else\n text += blockSeparator;\n }\n text += nodeText;\n }, 0);\n return text;\n }\n /**\n Create a new fragment containing the combined content of this\n fragment and the other.\n */\n append(other) {\n if (!other.size)\n return this;\n if (!this.size)\n return other;\n let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0;\n if (last.isText && last.sameMarkup(first)) {\n content[content.length - 1] = last.withText(last.text + first.text);\n i = 1;\n }\n for (; i < other.content.length; i++)\n content.push(other.content[i]);\n return new Fragment(content, this.size + other.size);\n }\n /**\n Cut out the sub-fragment between the two given positions.\n */\n cut(from, to = this.size) {\n if (from == 0 && to == this.size)\n return this;\n let result = [], size = 0;\n if (to > from)\n for (let i = 0, pos = 0; pos < to; i++) {\n let child = this.content[i], end = pos + child.nodeSize;\n if (end > from) {\n if (pos < from || end > to) {\n if (child.isText)\n child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos));\n else\n child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1));\n }\n result.push(child);\n size += child.nodeSize;\n }\n pos = end;\n }\n return new Fragment(result, size);\n }\n /**\n @internal\n */\n cutByIndex(from, to) {\n if (from == to)\n return Fragment.empty;\n if (from == 0 && to == this.content.length)\n return this;\n return new Fragment(this.content.slice(from, to));\n }\n /**\n Create a new fragment in which the node at the given index is\n replaced by the given node.\n */\n replaceChild(index, node) {\n let current = this.content[index];\n if (current == node)\n return this;\n let copy = this.content.slice();\n let size = this.size + node.nodeSize - current.nodeSize;\n copy[index] = node;\n return new Fragment(copy, size);\n }\n /**\n Create a new fragment by prepending the given node to this\n fragment.\n */\n addToStart(node) {\n return new Fragment([node].concat(this.content), this.size + node.nodeSize);\n }\n /**\n Create a new fragment by appending the given node to this\n fragment.\n */\n addToEnd(node) {\n return new Fragment(this.content.concat(node), this.size + node.nodeSize);\n }\n /**\n Compare this fragment to another one.\n */\n eq(other) {\n if (this.content.length != other.content.length)\n return false;\n for (let i = 0; i < this.content.length; i++)\n if (!this.content[i].eq(other.content[i]))\n return false;\n return true;\n }\n /**\n The first child of the fragment, or `null` if it is empty.\n */\n get firstChild() { return this.content.length ? this.content[0] : null; }\n /**\n The last child of the fragment, or `null` if it is empty.\n */\n get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null; }\n /**\n The number of child nodes in this fragment.\n */\n get childCount() { return this.content.length; }\n /**\n Get the child node at the given index. Raise an error when the\n index is out of range.\n */\n child(index) {\n let found = this.content[index];\n if (!found)\n throw new RangeError(\"Index \" + index + \" out of range for \" + this);\n return found;\n }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) {\n return this.content[index] || null;\n }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) {\n for (let i = 0, p = 0; i < this.content.length; i++) {\n let child = this.content[i];\n f(child, p, i);\n p += child.nodeSize;\n }\n }\n /**\n Find the first position at which this fragment and another\n fragment differ, or `null` if they are the same.\n */\n findDiffStart(other, pos = 0) {\n return findDiffStart(this, other, pos);\n }\n /**\n Find the first position, searching from the end, at which this\n fragment and the given fragment differ, or `null` if they are\n the same. Since this position will not be the same in both\n nodes, an object with two separate positions is returned.\n */\n findDiffEnd(other, pos = this.size, otherPos = other.size) {\n return findDiffEnd(this, other, pos, otherPos);\n }\n /**\n Find the index and inner offset corresponding to a given relative\n position in this fragment. The result object will be reused\n (overwritten) the next time the function is called. @internal\n */\n findIndex(pos) {\n if (pos == 0)\n return retIndex(0, pos);\n if (pos == this.size)\n return retIndex(this.content.length, pos);\n if (pos > this.size || pos < 0)\n throw new RangeError(`Position ${pos} outside of fragment (${this})`);\n for (let i = 0, curPos = 0;; i++) {\n let cur = this.child(i), end = curPos + cur.nodeSize;\n if (end >= pos) {\n if (end == pos)\n return retIndex(i + 1, end);\n return retIndex(i, curPos);\n }\n curPos = end;\n }\n }\n /**\n Return a debugging string that describes this fragment.\n */\n toString() { return \"<\" + this.toStringInner() + \">\"; }\n /**\n @internal\n */\n toStringInner() { return this.content.join(\", \"); }\n /**\n Create a JSON-serializeable representation of this fragment.\n */\n toJSON() {\n return this.content.length ? this.content.map(n => n.toJSON()) : null;\n }\n /**\n Deserialize a fragment from its JSON representation.\n */\n static fromJSON(schema, value) {\n if (!value)\n return Fragment.empty;\n if (!Array.isArray(value))\n throw new RangeError(\"Invalid input for Fragment.fromJSON\");\n return new Fragment(value.map(schema.nodeFromJSON));\n }\n /**\n Build a fragment from an array of nodes. Ensures that adjacent\n text nodes with the same marks are joined together.\n */\n static fromArray(array) {\n if (!array.length)\n return Fragment.empty;\n let joined, size = 0;\n for (let i = 0; i < array.length; i++) {\n let node = array[i];\n size += node.nodeSize;\n if (i && node.isText && array[i - 1].sameMarkup(node)) {\n if (!joined)\n joined = array.slice(0, i);\n joined[joined.length - 1] = node\n .withText(joined[joined.length - 1].text + node.text);\n }\n else if (joined) {\n joined.push(node);\n }\n }\n return new Fragment(joined || array, size);\n }\n /**\n Create a fragment from something that can be interpreted as a\n set of nodes. For `null`, it returns the empty fragment. For a\n fragment, the fragment itself. For a node or array of nodes, a\n fragment containing those nodes.\n */\n static from(nodes) {\n if (!nodes)\n return Fragment.empty;\n if (nodes instanceof Fragment)\n return nodes;\n if (Array.isArray(nodes))\n return this.fromArray(nodes);\n if (nodes.attrs)\n return new Fragment([nodes], nodes.nodeSize);\n throw new RangeError(\"Can not convert \" + nodes + \" to a Fragment\" +\n (nodes.nodesBetween ? \" (looks like multiple versions of prosemirror-model were loaded)\" : \"\"));\n }\n}\n/**\nAn empty fragment. Intended to be reused whenever a node doesn't\ncontain anything (rather than allocating a new empty fragment for\neach leaf node).\n*/\nFragment.empty = new Fragment([], 0);\nconst found = { index: 0, offset: 0 };\nfunction retIndex(index, offset) {\n found.index = index;\n found.offset = offset;\n return found;\n}\n\nfunction compareDeep(a, b) {\n if (a === b)\n return true;\n if (!(a && typeof a == \"object\") ||\n !(b && typeof b == \"object\"))\n return false;\n let array = Array.isArray(a);\n if (Array.isArray(b) != array)\n return false;\n if (array) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compareDeep(a[i], b[i]))\n return false;\n }\n else {\n for (let p in a)\n if (!(p in b) || !compareDeep(a[p], b[p]))\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n }\n return true;\n}\n\n/**\nA mark is a piece of information that can be attached to a node,\nsuch as it being emphasized, in code font, or a link. It has a\ntype and optionally a set of attributes that provide further\ninformation (such as the target of the link). Marks are created\nthrough a `Schema`, which controls which types exist and which\nattributes they have.\n*/\nclass Mark {\n /**\n @internal\n */\n constructor(\n /**\n The type of this mark.\n */\n type, \n /**\n The attributes associated with this mark.\n */\n attrs) {\n this.type = type;\n this.attrs = attrs;\n }\n /**\n Given a set of marks, create a new set which contains this one as\n well, in the right position. If this mark is already in the set,\n the set itself is returned. If any marks that are set to be\n [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,\n those are replaced by this one.\n */\n addToSet(set) {\n let copy, placed = false;\n for (let i = 0; i < set.length; i++) {\n let other = set[i];\n if (this.eq(other))\n return set;\n if (this.type.excludes(other.type)) {\n if (!copy)\n copy = set.slice(0, i);\n }\n else if (other.type.excludes(this.type)) {\n return set;\n }\n else {\n if (!placed && other.type.rank > this.type.rank) {\n if (!copy)\n copy = set.slice(0, i);\n copy.push(this);\n placed = true;\n }\n if (copy)\n copy.push(other);\n }\n }\n if (!copy)\n copy = set.slice();\n if (!placed)\n copy.push(this);\n return copy;\n }\n /**\n Remove this mark from the given set, returning a new set. If this\n mark is not in the set, the set itself is returned.\n */\n removeFromSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return set.slice(0, i).concat(set.slice(i + 1));\n return set;\n }\n /**\n Test whether this mark is in the given set of marks.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (this.eq(set[i]))\n return true;\n return false;\n }\n /**\n Test whether this mark has the same type and attributes as\n another mark.\n */\n eq(other) {\n return this == other ||\n (this.type == other.type && compareDeep(this.attrs, other.attrs));\n }\n /**\n Convert this mark to a JSON-serializeable representation.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n return obj;\n }\n /**\n Deserialize a mark from JSON.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Mark.fromJSON\");\n let type = schema.marks[json.type];\n if (!type)\n throw new RangeError(`There is no mark type ${json.type} in this schema`);\n let mark = type.create(json.attrs);\n type.checkAttrs(mark.attrs);\n return mark;\n }\n /**\n Test whether two sets of marks are identical.\n */\n static sameSet(a, b) {\n if (a == b)\n return true;\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].eq(b[i]))\n return false;\n return true;\n }\n /**\n Create a properly sorted mark set from null, a single mark, or an\n unsorted array of marks.\n */\n static setFrom(marks) {\n if (!marks || Array.isArray(marks) && marks.length == 0)\n return Mark.none;\n if (marks instanceof Mark)\n return [marks];\n let copy = marks.slice();\n copy.sort((a, b) => a.type.rank - b.type.rank);\n return copy;\n }\n}\n/**\nThe empty set of marks.\n*/\nMark.none = [];\n\n/**\nError type raised by [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) when\ngiven an invalid replacement.\n*/\nclass ReplaceError extends Error {\n}\n/*\nReplaceError = function(this: any, message: string) {\n let err = Error.call(this, message)\n ;(err as any).__proto__ = ReplaceError.prototype\n return err\n} as any\n\nReplaceError.prototype = Object.create(Error.prototype)\nReplaceError.prototype.constructor = ReplaceError\nReplaceError.prototype.name = \"ReplaceError\"\n*/\n/**\nA slice represents a piece cut out of a larger document. It\nstores not only a fragment, but also the depth up to which nodes on\nboth side are ‘open’ (cut through).\n*/\nclass Slice {\n /**\n Create a slice. When specifying a non-zero open depth, you must\n make sure that there are nodes of at least that depth at the\n appropriate side of the fragment—i.e. if the fragment is an\n empty paragraph node, `openStart` and `openEnd` can't be greater\n than 1.\n \n It is not necessary for the content of open nodes to conform to\n the schema's content constraints, though it should be a valid\n start/end/middle for such a node, depending on which sides are\n open.\n */\n constructor(\n /**\n The slice's content.\n */\n content, \n /**\n The open depth at the start of the fragment.\n */\n openStart, \n /**\n The open depth at the end.\n */\n openEnd) {\n this.content = content;\n this.openStart = openStart;\n this.openEnd = openEnd;\n }\n /**\n The size this slice would add when inserted into a document.\n */\n get size() {\n return this.content.size - this.openStart - this.openEnd;\n }\n /**\n @internal\n */\n insertAt(pos, fragment) {\n let content = insertInto(this.content, pos + this.openStart, fragment);\n return content && new Slice(content, this.openStart, this.openEnd);\n }\n /**\n @internal\n */\n removeBetween(from, to) {\n return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd);\n }\n /**\n Tests whether this slice is equal to another slice.\n */\n eq(other) {\n return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;\n }\n /**\n @internal\n */\n toString() {\n return this.content + \"(\" + this.openStart + \",\" + this.openEnd + \")\";\n }\n /**\n Convert a slice to a JSON-serializable representation.\n */\n toJSON() {\n if (!this.content.size)\n return null;\n let json = { content: this.content.toJSON() };\n if (this.openStart > 0)\n json.openStart = this.openStart;\n if (this.openEnd > 0)\n json.openEnd = this.openEnd;\n return json;\n }\n /**\n Deserialize a slice from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n return Slice.empty;\n let openStart = json.openStart || 0, openEnd = json.openEnd || 0;\n if (typeof openStart != \"number\" || typeof openEnd != \"number\")\n throw new RangeError(\"Invalid input for Slice.fromJSON\");\n return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);\n }\n /**\n Create a slice from a fragment by taking the maximum possible\n open value on both side of the fragment.\n */\n static maxOpen(fragment, openIsolating = true) {\n let openStart = 0, openEnd = 0;\n for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)\n openStart++;\n for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)\n openEnd++;\n return new Slice(fragment, openStart, openEnd);\n }\n}\n/**\nThe empty slice.\n*/\nSlice.empty = new Slice(Fragment.empty, 0, 0);\nfunction removeRange(content, from, to) {\n let { index, offset } = content.findIndex(from), child = content.maybeChild(index);\n let { index: indexTo, offset: offsetTo } = content.findIndex(to);\n if (offset == from || child.isText) {\n if (offsetTo != to && !content.child(indexTo).isText)\n throw new RangeError(\"Removing non-flat range\");\n return content.cut(0, from).append(content.cut(to));\n }\n if (index != indexTo)\n throw new RangeError(\"Removing non-flat range\");\n return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)));\n}\nfunction insertInto(content, dist, insert, parent) {\n let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);\n if (offset == dist || child.isText) {\n if (parent && !parent.canReplace(index, index, insert))\n return null;\n return content.cut(0, dist).append(insert).append(content.cut(dist));\n }\n let inner = insertInto(child.content, dist - offset - 1, insert, child);\n return inner && content.replaceChild(index, child.copy(inner));\n}\nfunction replace($from, $to, slice) {\n if (slice.openStart > $from.depth)\n throw new ReplaceError(\"Inserted content deeper than insertion position\");\n if ($from.depth - slice.openStart != $to.depth - slice.openEnd)\n throw new ReplaceError(\"Inconsistent open depths\");\n return replaceOuter($from, $to, slice, 0);\n}\nfunction replaceOuter($from, $to, slice, depth) {\n let index = $from.index(depth), node = $from.node(depth);\n if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {\n let inner = replaceOuter($from, $to, slice, depth + 1);\n return node.copy(node.content.replaceChild(index, inner));\n }\n else if (!slice.content.size) {\n return close(node, replaceTwoWay($from, $to, depth));\n }\n else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case\n let parent = $from.parent, content = parent.content;\n return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)));\n }\n else {\n let { start, end } = prepareSliceForReplace(slice, $from);\n return close(node, replaceThreeWay($from, start, end, $to, depth));\n }\n}\nfunction checkJoin(main, sub) {\n if (!sub.type.compatibleContent(main.type))\n throw new ReplaceError(\"Cannot join \" + sub.type.name + \" onto \" + main.type.name);\n}\nfunction joinable($before, $after, depth) {\n let node = $before.node(depth);\n checkJoin(node, $after.node(depth));\n return node;\n}\nfunction addNode(child, target) {\n let last = target.length - 1;\n if (last >= 0 && child.isText && child.sameMarkup(target[last]))\n target[last] = child.withText(target[last].text + child.text);\n else\n target.push(child);\n}\nfunction addRange($start, $end, depth, target) {\n let node = ($end || $start).node(depth);\n let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;\n if ($start) {\n startIndex = $start.index(depth);\n if ($start.depth > depth) {\n startIndex++;\n }\n else if ($start.textOffset) {\n addNode($start.nodeAfter, target);\n startIndex++;\n }\n }\n for (let i = startIndex; i < endIndex; i++)\n addNode(node.child(i), target);\n if ($end && $end.depth == depth && $end.textOffset)\n addNode($end.nodeBefore, target);\n}\nfunction close(node, content) {\n node.type.checkContent(content);\n return node.copy(content);\n}\nfunction replaceThreeWay($from, $start, $end, $to, depth) {\n let openStart = $from.depth > depth && joinable($from, $start, depth + 1);\n let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);\n let content = [];\n addRange(null, $from, depth, content);\n if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {\n checkJoin(openStart, openEnd);\n addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);\n }\n else {\n if (openStart)\n addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);\n addRange($start, $end, depth, content);\n if (openEnd)\n addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction replaceTwoWay($from, $to, depth) {\n let content = [];\n addRange(null, $from, depth, content);\n if ($from.depth > depth) {\n let type = joinable($from, $to, depth + 1);\n addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);\n }\n addRange($to, null, depth, content);\n return new Fragment(content);\n}\nfunction prepareSliceForReplace(slice, $along) {\n let extra = $along.depth - slice.openStart, parent = $along.node(extra);\n let node = parent.copy(slice.content);\n for (let i = extra - 1; i >= 0; i--)\n node = $along.node(i).copy(Fragment.from(node));\n return { start: node.resolveNoCache(slice.openStart + extra),\n end: node.resolveNoCache(node.content.size - slice.openEnd - extra) };\n}\n\n/**\nYou can [_resolve_](https://prosemirror.net/docs/ref/#model.Node.resolve) a position to get more\ninformation about it. Objects of this class represent such a\nresolved position, providing various pieces of context\ninformation, and some helper methods.\n\nThroughout this interface, methods that take an optional `depth`\nparameter will interpret undefined as `this.depth` and negative\nnumbers as `this.depth + value`.\n*/\nclass ResolvedPos {\n /**\n @internal\n */\n constructor(\n /**\n The position that was resolved.\n */\n pos, \n /**\n @internal\n */\n path, \n /**\n The offset this position has into its parent node.\n */\n parentOffset) {\n this.pos = pos;\n this.path = path;\n this.parentOffset = parentOffset;\n this.depth = path.length / 3 - 1;\n }\n /**\n @internal\n */\n resolveDepth(val) {\n if (val == null)\n return this.depth;\n if (val < 0)\n return this.depth + val;\n return val;\n }\n /**\n The parent node that the position points into. Note that even if\n a position points into a text node, that node is not considered\n the parent—text nodes are ‘flat’ in this model, and have no content.\n */\n get parent() { return this.node(this.depth); }\n /**\n The root node in which the position was resolved.\n */\n get doc() { return this.node(0); }\n /**\n The ancestor node at the given level. `p.node(p.depth)` is the\n same as `p.parent`.\n */\n node(depth) { return this.path[this.resolveDepth(depth) * 3]; }\n /**\n The index into the ancestor at the given level. If this points\n at the 3rd node in the 2nd paragraph on the top level, for\n example, `p.index(0)` is 1 and `p.index(1)` is 2.\n */\n index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1]; }\n /**\n The index pointing after this position into the ancestor at the\n given level.\n */\n indexAfter(depth) {\n depth = this.resolveDepth(depth);\n return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);\n }\n /**\n The (absolute) position at the start of the node at the given\n level.\n */\n start(depth) {\n depth = this.resolveDepth(depth);\n return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n }\n /**\n The (absolute) position at the end of the node at the given\n level.\n */\n end(depth) {\n depth = this.resolveDepth(depth);\n return this.start(depth) + this.node(depth).content.size;\n }\n /**\n The (absolute) position directly before the wrapping node at the\n given level, or, when `depth` is `this.depth + 1`, the original\n position.\n */\n before(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position before the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];\n }\n /**\n The (absolute) position directly after the wrapping node at the\n given level, or the original position when `depth` is `this.depth + 1`.\n */\n after(depth) {\n depth = this.resolveDepth(depth);\n if (!depth)\n throw new RangeError(\"There is no position after the top-level node\");\n return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;\n }\n /**\n When this position points into a text node, this returns the\n distance between the position and the start of the text node.\n Will be zero for positions that point between nodes.\n */\n get textOffset() { return this.pos - this.path[this.path.length - 1]; }\n /**\n Get the node directly after the position, if any. If the position\n points into a text node, only the part of that node after the\n position is returned.\n */\n get nodeAfter() {\n let parent = this.parent, index = this.index(this.depth);\n if (index == parent.childCount)\n return null;\n let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);\n return dOff ? parent.child(index).cut(dOff) : child;\n }\n /**\n Get the node directly before the position, if any. If the\n position points into a text node, only the part of that node\n before the position is returned.\n */\n get nodeBefore() {\n let index = this.index(this.depth);\n let dOff = this.pos - this.path[this.path.length - 1];\n if (dOff)\n return this.parent.child(index).cut(0, dOff);\n return index == 0 ? null : this.parent.child(index - 1);\n }\n /**\n Get the position at the given index in the parent node at the\n given depth (which defaults to `this.depth`).\n */\n posAtIndex(index, depth) {\n depth = this.resolveDepth(depth);\n let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;\n for (let i = 0; i < index; i++)\n pos += node.child(i).nodeSize;\n return pos;\n }\n /**\n Get the marks at this position, factoring in the surrounding\n marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the\n position is at the start of a non-empty node, the marks of the\n node after it (if any) are returned.\n */\n marks() {\n let parent = this.parent, index = this.index();\n // In an empty parent, return the empty array\n if (parent.content.size == 0)\n return Mark.none;\n // When inside a text node, just return the text node's marks\n if (this.textOffset)\n return parent.child(index).marks;\n let main = parent.maybeChild(index - 1), other = parent.maybeChild(index);\n // If the `after` flag is true of there is no node before, make\n // the node after this position the main reference.\n if (!main) {\n let tmp = main;\n main = other;\n other = tmp;\n }\n // Use all marks in the main node, except those that have\n // `inclusive` set to false and are not present in the other node.\n let marks = main.marks;\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n Get the marks after the current position, if any, except those\n that are non-inclusive and not present at position `$end`. This\n is mostly useful for getting the set of marks to preserve after a\n deletion. Will return `null` if this position is at the end of\n its parent node or its parent node isn't a textblock (in which\n case no marks should be preserved).\n */\n marksAcross($end) {\n let after = this.parent.maybeChild(this.index());\n if (!after || !after.isInline)\n return null;\n let marks = after.marks, next = $end.parent.maybeChild($end.index());\n for (var i = 0; i < marks.length; i++)\n if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))\n marks = marks[i--].removeFromSet(marks);\n return marks;\n }\n /**\n The depth up to which this position and the given (non-resolved)\n position share the same parent nodes.\n */\n sharedDepth(pos) {\n for (let depth = this.depth; depth > 0; depth--)\n if (this.start(depth) <= pos && this.end(depth) >= pos)\n return depth;\n return 0;\n }\n /**\n Returns a range based on the place where this position and the\n given position diverge around block content. If both point into\n the same textblock, for example, a range around that textblock\n will be returned. If they point into different blocks, the range\n around those blocks in their shared ancestor is returned. You can\n pass in an optional predicate that will be called with a parent\n node to see if a range into that parent is acceptable.\n */\n blockRange(other = this, pred) {\n if (other.pos < this.pos)\n return other.blockRange(this);\n for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)\n if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))\n return new NodeRange(this, other, d);\n return null;\n }\n /**\n Query whether the given position shares the same parent node.\n */\n sameParent(other) {\n return this.pos - this.parentOffset == other.pos - other.parentOffset;\n }\n /**\n Return the greater of this and the given position.\n */\n max(other) {\n return other.pos > this.pos ? other : this;\n }\n /**\n Return the smaller of this and the given position.\n */\n min(other) {\n return other.pos < this.pos ? other : this;\n }\n /**\n @internal\n */\n toString() {\n let str = \"\";\n for (let i = 1; i <= this.depth; i++)\n str += (str ? \"/\" : \"\") + this.node(i).type.name + \"_\" + this.index(i - 1);\n return str + \":\" + this.parentOffset;\n }\n /**\n @internal\n */\n static resolve(doc, pos) {\n if (!(pos >= 0 && pos <= doc.content.size))\n throw new RangeError(\"Position \" + pos + \" out of range\");\n let path = [];\n let start = 0, parentOffset = pos;\n for (let node = doc;;) {\n let { index, offset } = node.content.findIndex(parentOffset);\n let rem = parentOffset - offset;\n path.push(node, index, start + offset);\n if (!rem)\n break;\n node = node.child(index);\n if (node.isText)\n break;\n parentOffset = rem - 1;\n start += offset + 1;\n }\n return new ResolvedPos(pos, path, parentOffset);\n }\n /**\n @internal\n */\n static resolveCached(doc, pos) {\n let cache = resolveCache.get(doc);\n if (cache) {\n for (let i = 0; i < cache.elts.length; i++) {\n let elt = cache.elts[i];\n if (elt.pos == pos)\n return elt;\n }\n }\n else {\n resolveCache.set(doc, cache = new ResolveCache);\n }\n let result = cache.elts[cache.i] = ResolvedPos.resolve(doc, pos);\n cache.i = (cache.i + 1) % resolveCacheSize;\n return result;\n }\n}\nclass ResolveCache {\n constructor() {\n this.elts = [];\n this.i = 0;\n }\n}\nconst resolveCacheSize = 12, resolveCache = new WeakMap();\n/**\nRepresents a flat range of content, i.e. one that starts and\nends in the same node.\n*/\nclass NodeRange {\n /**\n Construct a node range. `$from` and `$to` should point into the\n same node until at least the given `depth`, since a node range\n denotes an adjacent set of nodes in a single parent node.\n */\n constructor(\n /**\n A resolved position along the start of the content. May have a\n `depth` greater than this object's `depth` property, since\n these are the positions that were used to compute the range,\n not re-resolved positions directly at its boundaries.\n */\n $from, \n /**\n A position along the end of the content. See\n caveat for [`$from`](https://prosemirror.net/docs/ref/#model.NodeRange.$from).\n */\n $to, \n /**\n The depth of the node that this range points into.\n */\n depth) {\n this.$from = $from;\n this.$to = $to;\n this.depth = depth;\n }\n /**\n The position at the start of the range.\n */\n get start() { return this.$from.before(this.depth + 1); }\n /**\n The position at the end of the range.\n */\n get end() { return this.$to.after(this.depth + 1); }\n /**\n The parent node that the range points into.\n */\n get parent() { return this.$from.node(this.depth); }\n /**\n The start index of the range in the parent node.\n */\n get startIndex() { return this.$from.index(this.depth); }\n /**\n The end index of the range in the parent node.\n */\n get endIndex() { return this.$to.indexAfter(this.depth); }\n}\n\nconst emptyAttrs = Object.create(null);\n/**\nThis class represents a node in the tree that makes up a\nProseMirror document. So a document is an instance of `Node`, with\nchildren that are also instances of `Node`.\n\nNodes are persistent data structures. Instead of changing them, you\ncreate new ones with the content you want. Old ones keep pointing\nat the old document shape. This is made cheaper by sharing\nstructure between the old and new data as much as possible, which a\ntree shape like this (without back pointers) makes easy.\n\n**Do not** directly mutate the properties of a `Node` object. See\n[the guide](https://prosemirror.net/docs/guide/#doc) for more information.\n*/\nclass Node {\n /**\n @internal\n */\n constructor(\n /**\n The type of node that this is.\n */\n type, \n /**\n An object mapping attribute names to values. The kind of\n attributes allowed and required are\n [determined](https://prosemirror.net/docs/ref/#model.NodeSpec.attrs) by the node type.\n */\n attrs, \n // A fragment holding the node's children.\n content, \n /**\n The marks (things like whether it is emphasized or part of a\n link) applied to this node.\n */\n marks = Mark.none) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.content = content || Fragment.empty;\n }\n /**\n The array of this node's child nodes.\n */\n get children() { return this.content.content; }\n /**\n The size of this node, as defined by the integer-based [indexing\n scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the\n amount of characters. For other leaf nodes, it is one. For\n non-leaf nodes, it is the size of the content plus two (the\n start and end token).\n */\n get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size; }\n /**\n The number of children that the node has.\n */\n get childCount() { return this.content.childCount; }\n /**\n Get the child node at the given index. Raises an error when the\n index is out of range.\n */\n child(index) { return this.content.child(index); }\n /**\n Get the child node at the given index, if it exists.\n */\n maybeChild(index) { return this.content.maybeChild(index); }\n /**\n Call `f` for every child node, passing the node, its offset\n into this parent node, and its index.\n */\n forEach(f) { this.content.forEach(f); }\n /**\n Invoke a callback for all descendant nodes recursively between\n the given two positions that are relative to start of this\n node's content. The callback is invoked with the node, its\n position relative to the original node (method receiver),\n its parent node, and its child index. When the callback returns\n false for a given node, that node's children will not be\n recursed over. The last parameter can be used to specify a\n starting position to count from.\n */\n nodesBetween(from, to, f, startPos = 0) {\n this.content.nodesBetween(from, to, f, startPos, this);\n }\n /**\n Call the given callback for every descendant node. Doesn't\n descend into a node when the callback returns `false`.\n */\n descendants(f) {\n this.nodesBetween(0, this.content.size, f);\n }\n /**\n Concatenates all the text nodes found in this fragment and its\n children.\n */\n get textContent() {\n return (this.isLeaf && this.type.spec.leafText)\n ? this.type.spec.leafText(this)\n : this.textBetween(0, this.content.size, \"\");\n }\n /**\n Get all text between positions `from` and `to`. When\n `blockSeparator` is given, it will be inserted to separate text\n from different block nodes. If `leafText` is given, it'll be\n inserted for every non-text leaf node encountered, otherwise\n [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.\n */\n textBetween(from, to, blockSeparator, leafText) {\n return this.content.textBetween(from, to, blockSeparator, leafText);\n }\n /**\n Returns this node's first child, or `null` if there are no\n children.\n */\n get firstChild() { return this.content.firstChild; }\n /**\n Returns this node's last child, or `null` if there are no\n children.\n */\n get lastChild() { return this.content.lastChild; }\n /**\n Test whether two nodes represent the same piece of document.\n */\n eq(other) {\n return this == other || (this.sameMarkup(other) && this.content.eq(other.content));\n }\n /**\n Compare the markup (type, attributes, and marks) of this node to\n those of another. Returns `true` if both have the same markup.\n */\n sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }\n /**\n Check whether this node's markup correspond to the given type,\n attributes, and marks.\n */\n hasMarkup(type, attrs, marks) {\n return this.type == type &&\n compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) &&\n Mark.sameSet(this.marks, marks || Mark.none);\n }\n /**\n Create a new node with the same markup as this node, containing\n the given content (or empty, if no content is given).\n */\n copy(content = null) {\n if (content == this.content)\n return this;\n return new Node(this.type, this.attrs, content, this.marks);\n }\n /**\n Create a copy of this node, with the given set of marks instead\n of the node's own marks.\n */\n mark(marks) {\n return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks);\n }\n /**\n Create a copy of this node with only the content between the\n given positions. If `to` is not given, it defaults to the end of\n the node.\n */\n cut(from, to = this.content.size) {\n if (from == 0 && to == this.content.size)\n return this;\n return this.copy(this.content.cut(from, to));\n }\n /**\n Cut out the part of the document between the given positions, and\n return it as a `Slice` object.\n */\n slice(from, to = this.content.size, includeParents = false) {\n if (from == to)\n return Slice.empty;\n let $from = this.resolve(from), $to = this.resolve(to);\n let depth = includeParents ? 0 : $from.sharedDepth(to);\n let start = $from.start(depth), node = $from.node(depth);\n let content = node.content.cut($from.pos - start, $to.pos - start);\n return new Slice(content, $from.depth - depth, $to.depth - depth);\n }\n /**\n Replace the part of the document between the given positions with\n the given slice. The slice must 'fit', meaning its open sides\n must be able to connect to the surrounding content, and its\n content nodes must be valid children for the node they are placed\n into. If any of this is violated, an error of type\n [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.\n */\n replace(from, to, slice) {\n return replace(this.resolve(from), this.resolve(to), slice);\n }\n /**\n Find the node directly after the given position.\n */\n nodeAt(pos) {\n for (let node = this;;) {\n let { index, offset } = node.content.findIndex(pos);\n node = node.maybeChild(index);\n if (!node)\n return null;\n if (offset == pos || node.isText)\n return node;\n pos -= offset + 1;\n }\n }\n /**\n Find the (direct) child node after the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childAfter(pos) {\n let { index, offset } = this.content.findIndex(pos);\n return { node: this.content.maybeChild(index), index, offset };\n }\n /**\n Find the (direct) child node before the given offset, if any,\n and return it along with its index and offset relative to this\n node.\n */\n childBefore(pos) {\n if (pos == 0)\n return { node: null, index: 0, offset: 0 };\n let { index, offset } = this.content.findIndex(pos);\n if (offset < pos)\n return { node: this.content.child(index), index, offset };\n let node = this.content.child(index - 1);\n return { node, index: index - 1, offset: offset - node.nodeSize };\n }\n /**\n Resolve the given position in the document, returning an\n [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.\n */\n resolve(pos) { return ResolvedPos.resolveCached(this, pos); }\n /**\n @internal\n */\n resolveNoCache(pos) { return ResolvedPos.resolve(this, pos); }\n /**\n Test whether a given mark or mark type occurs in this document\n between the two given positions.\n */\n rangeHasMark(from, to, type) {\n let found = false;\n if (to > from)\n this.nodesBetween(from, to, node => {\n if (type.isInSet(node.marks))\n found = true;\n return !found;\n });\n return found;\n }\n /**\n True when this is a block (non-inline node)\n */\n get isBlock() { return this.type.isBlock; }\n /**\n True when this is a textblock node, a block node with inline\n content.\n */\n get isTextblock() { return this.type.isTextblock; }\n /**\n True when this node allows inline content.\n */\n get inlineContent() { return this.type.inlineContent; }\n /**\n True when this is an inline node (a text node or a node that can\n appear among text).\n */\n get isInline() { return this.type.isInline; }\n /**\n True when this is a text node.\n */\n get isText() { return this.type.isText; }\n /**\n True when this is a leaf node.\n */\n get isLeaf() { return this.type.isLeaf; }\n /**\n True when this is an atom, i.e. when it does not have directly\n editable content. This is usually the same as `isLeaf`, but can\n be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)\n on a node's spec (typically used when the node is displayed as\n an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).\n */\n get isAtom() { return this.type.isAtom; }\n /**\n Return a string representation of this node for debugging\n purposes.\n */\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n let name = this.type.name;\n if (this.content.size)\n name += \"(\" + this.content.toStringInner() + \")\";\n return wrapMarks(this.marks, name);\n }\n /**\n Get the content match in this node at the given index.\n */\n contentMatchAt(index) {\n let match = this.type.contentMatch.matchFragment(this.content, 0, index);\n if (!match)\n throw new Error(\"Called contentMatchAt on a node with invalid content\");\n return match;\n }\n /**\n Test whether replacing the range between `from` and `to` (by\n child index) with the given replacement fragment (which defaults\n to the empty fragment) would leave the node's content valid. You\n can optionally pass `start` and `end` indices into the\n replacement fragment.\n */\n canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {\n let one = this.contentMatchAt(from).matchFragment(replacement, start, end);\n let two = one && one.matchFragment(this.content, to);\n if (!two || !two.validEnd)\n return false;\n for (let i = start; i < end; i++)\n if (!this.type.allowsMarks(replacement.child(i).marks))\n return false;\n return true;\n }\n /**\n Test whether replacing the range `from` to `to` (by index) with\n a node of the given type would leave the node's content valid.\n */\n canReplaceWith(from, to, type, marks) {\n if (marks && !this.type.allowsMarks(marks))\n return false;\n let start = this.contentMatchAt(from).matchType(type);\n let end = start && start.matchFragment(this.content, to);\n return end ? end.validEnd : false;\n }\n /**\n Test whether the given node's content could be appended to this\n node. If that node is empty, this will only return true if there\n is at least one node type that can appear in both nodes (to avoid\n merging completely incompatible nodes).\n */\n canAppend(other) {\n if (other.content.size)\n return this.canReplace(this.childCount, this.childCount, other.content);\n else\n return this.type.compatibleContent(other.type);\n }\n /**\n Check whether this node and its descendants conform to the\n schema, and raise an exception when they do not.\n */\n check() {\n this.type.checkContent(this.content);\n this.type.checkAttrs(this.attrs);\n let copy = Mark.none;\n for (let i = 0; i < this.marks.length; i++) {\n let mark = this.marks[i];\n mark.type.checkAttrs(mark.attrs);\n copy = mark.addToSet(copy);\n }\n if (!Mark.sameSet(copy, this.marks))\n throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`);\n this.content.forEach(node => node.check());\n }\n /**\n Return a JSON-serializeable representation of this node.\n */\n toJSON() {\n let obj = { type: this.type.name };\n for (let _ in this.attrs) {\n obj.attrs = this.attrs;\n break;\n }\n if (this.content.size)\n obj.content = this.content.toJSON();\n if (this.marks.length)\n obj.marks = this.marks.map(n => n.toJSON());\n return obj;\n }\n /**\n Deserialize a node from its JSON representation.\n */\n static fromJSON(schema, json) {\n if (!json)\n throw new RangeError(\"Invalid input for Node.fromJSON\");\n let marks = undefined;\n if (json.marks) {\n if (!Array.isArray(json.marks))\n throw new RangeError(\"Invalid mark data for Node.fromJSON\");\n marks = json.marks.map(schema.markFromJSON);\n }\n if (json.type == \"text\") {\n if (typeof json.text != \"string\")\n throw new RangeError(\"Invalid text node in JSON\");\n return schema.text(json.text, marks);\n }\n let content = Fragment.fromJSON(schema, json.content);\n let node = schema.nodeType(json.type).create(json.attrs, content, marks);\n node.type.checkAttrs(node.attrs);\n return node;\n }\n}\nNode.prototype.text = undefined;\nclass TextNode extends Node {\n /**\n @internal\n */\n constructor(type, attrs, content, marks) {\n super(type, attrs, null, marks);\n if (!content)\n throw new RangeError(\"Empty text nodes are not allowed\");\n this.text = content;\n }\n toString() {\n if (this.type.spec.toDebugString)\n return this.type.spec.toDebugString(this);\n return wrapMarks(this.marks, JSON.stringify(this.text));\n }\n get textContent() { return this.text; }\n textBetween(from, to) { return this.text.slice(from, to); }\n get nodeSize() { return this.text.length; }\n mark(marks) {\n return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks);\n }\n withText(text) {\n if (text == this.text)\n return this;\n return new TextNode(this.type, this.attrs, text, this.marks);\n }\n cut(from = 0, to = this.text.length) {\n if (from == 0 && to == this.text.length)\n return this;\n return this.withText(this.text.slice(from, to));\n }\n eq(other) {\n return this.sameMarkup(other) && this.text == other.text;\n }\n toJSON() {\n let base = super.toJSON();\n base.text = this.text;\n return base;\n }\n}\nfunction wrapMarks(marks, str) {\n for (let i = marks.length - 1; i >= 0; i--)\n str = marks[i].type.name + \"(\" + str + \")\";\n return str;\n}\n\n/**\nInstances of this class represent a match state of a node type's\n[content expression](https://prosemirror.net/docs/ref/#model.NodeSpec.content), and can be used to\nfind out whether further content matches here, and whether a given\nposition is a valid end of the node.\n*/\nclass ContentMatch {\n /**\n @internal\n */\n constructor(\n /**\n True when this match state represents a valid end of the node.\n */\n validEnd) {\n this.validEnd = validEnd;\n /**\n @internal\n */\n this.next = [];\n /**\n @internal\n */\n this.wrapCache = [];\n }\n /**\n @internal\n */\n static parse(string, nodeTypes) {\n let stream = new TokenStream(string, nodeTypes);\n if (stream.next == null)\n return ContentMatch.empty;\n let expr = parseExpr(stream);\n if (stream.next)\n stream.err(\"Unexpected trailing text\");\n let match = dfa(nfa(expr));\n checkForDeadEnds(match, stream);\n return match;\n }\n /**\n Match a node type, returning a match after that node if\n successful.\n */\n matchType(type) {\n for (let i = 0; i < this.next.length; i++)\n if (this.next[i].type == type)\n return this.next[i].next;\n return null;\n }\n /**\n Try to match a fragment. Returns the resulting match when\n successful.\n */\n matchFragment(frag, start = 0, end = frag.childCount) {\n let cur = this;\n for (let i = start; cur && i < end; i++)\n cur = cur.matchType(frag.child(i).type);\n return cur;\n }\n /**\n @internal\n */\n get inlineContent() {\n return this.next.length != 0 && this.next[0].type.isInline;\n }\n /**\n Get the first matching node type at this match position that can\n be generated.\n */\n get defaultType() {\n for (let i = 0; i < this.next.length; i++) {\n let { type } = this.next[i];\n if (!(type.isText || type.hasRequiredAttrs()))\n return type;\n }\n return null;\n }\n /**\n @internal\n */\n compatible(other) {\n for (let i = 0; i < this.next.length; i++)\n for (let j = 0; j < other.next.length; j++)\n if (this.next[i].type == other.next[j].type)\n return true;\n return false;\n }\n /**\n Try to match the given fragment, and if that fails, see if it can\n be made to match by inserting nodes in front of it. When\n successful, return a fragment of inserted nodes (which may be\n empty if nothing had to be inserted). When `toEnd` is true, only\n return a fragment if the resulting match goes to the end of the\n content expression.\n */\n fillBefore(after, toEnd = false, startIndex = 0) {\n let seen = [this];\n function search(match, types) {\n let finished = match.matchFragment(after, startIndex);\n if (finished && (!toEnd || finished.validEnd))\n return Fragment.from(types.map(tp => tp.createAndFill()));\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {\n seen.push(next);\n let found = search(next, types.concat(type));\n if (found)\n return found;\n }\n }\n return null;\n }\n return search(this, []);\n }\n /**\n Find a set of wrapping node types that would allow a node of the\n given type to appear at this position. The result may be empty\n (when it fits directly) and will be null when no such wrapping\n exists.\n */\n findWrapping(target) {\n for (let i = 0; i < this.wrapCache.length; i += 2)\n if (this.wrapCache[i] == target)\n return this.wrapCache[i + 1];\n let computed = this.computeWrapping(target);\n this.wrapCache.push(target, computed);\n return computed;\n }\n /**\n @internal\n */\n computeWrapping(target) {\n let seen = Object.create(null), active = [{ match: this, type: null, via: null }];\n while (active.length) {\n let current = active.shift(), match = current.match;\n if (match.matchType(target)) {\n let result = [];\n for (let obj = current; obj.type; obj = obj.via)\n result.push(obj.type);\n return result.reverse();\n }\n for (let i = 0; i < match.next.length; i++) {\n let { type, next } = match.next[i];\n if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {\n active.push({ match: type.contentMatch, type, via: current });\n seen[type.name] = true;\n }\n }\n }\n return null;\n }\n /**\n The number of outgoing edges this node has in the finite\n automaton that describes the content expression.\n */\n get edgeCount() {\n return this.next.length;\n }\n /**\n Get the _n_​th outgoing edge from this node in the finite\n automaton that describes the content expression.\n */\n edge(n) {\n if (n >= this.next.length)\n throw new RangeError(`There's no ${n}th edge in this content match`);\n return this.next[n];\n }\n /**\n @internal\n */\n toString() {\n let seen = [];\n function scan(m) {\n seen.push(m);\n for (let i = 0; i < m.next.length; i++)\n if (seen.indexOf(m.next[i].next) == -1)\n scan(m.next[i].next);\n }\n scan(this);\n return seen.map((m, i) => {\n let out = i + (m.validEnd ? \"*\" : \" \") + \" \";\n for (let i = 0; i < m.next.length; i++)\n out += (i ? \", \" : \"\") + m.next[i].type.name + \"->\" + seen.indexOf(m.next[i].next);\n return out;\n }).join(\"\\n\");\n }\n}\n/**\n@internal\n*/\nContentMatch.empty = new ContentMatch(true);\nclass TokenStream {\n constructor(string, nodeTypes) {\n this.string = string;\n this.nodeTypes = nodeTypes;\n this.inline = null;\n this.pos = 0;\n this.tokens = string.split(/\\s*(?=\\b|\\W|$)/);\n if (this.tokens[this.tokens.length - 1] == \"\")\n this.tokens.pop();\n if (this.tokens[0] == \"\")\n this.tokens.shift();\n }\n get next() { return this.tokens[this.pos]; }\n eat(tok) { return this.next == tok && (this.pos++ || true); }\n err(str) { throw new SyntaxError(str + \" (in content expression '\" + this.string + \"')\"); }\n}\nfunction parseExpr(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSeq(stream));\n } while (stream.eat(\"|\"));\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n}\nfunction parseExprSeq(stream) {\n let exprs = [];\n do {\n exprs.push(parseExprSubscript(stream));\n } while (stream.next && stream.next != \")\" && stream.next != \"|\");\n return exprs.length == 1 ? exprs[0] : { type: \"seq\", exprs };\n}\nfunction parseExprSubscript(stream) {\n let expr = parseExprAtom(stream);\n for (;;) {\n if (stream.eat(\"+\"))\n expr = { type: \"plus\", expr };\n else if (stream.eat(\"*\"))\n expr = { type: \"star\", expr };\n else if (stream.eat(\"?\"))\n expr = { type: \"opt\", expr };\n else if (stream.eat(\"{\"))\n expr = parseExprRange(stream, expr);\n else\n break;\n }\n return expr;\n}\nfunction parseNum(stream) {\n if (/\\D/.test(stream.next))\n stream.err(\"Expected number, got '\" + stream.next + \"'\");\n let result = Number(stream.next);\n stream.pos++;\n return result;\n}\nfunction parseExprRange(stream, expr) {\n let min = parseNum(stream), max = min;\n if (stream.eat(\",\")) {\n if (stream.next != \"}\")\n max = parseNum(stream);\n else\n max = -1;\n }\n if (!stream.eat(\"}\"))\n stream.err(\"Unclosed braced range\");\n return { type: \"range\", min, max, expr };\n}\nfunction resolveName(stream, name) {\n let types = stream.nodeTypes, type = types[name];\n if (type)\n return [type];\n let result = [];\n for (let typeName in types) {\n let type = types[typeName];\n if (type.isInGroup(name))\n result.push(type);\n }\n if (result.length == 0)\n stream.err(\"No node type or group '\" + name + \"' found\");\n return result;\n}\nfunction parseExprAtom(stream) {\n if (stream.eat(\"(\")) {\n let expr = parseExpr(stream);\n if (!stream.eat(\")\"))\n stream.err(\"Missing closing paren\");\n return expr;\n }\n else if (!/\\W/.test(stream.next)) {\n let exprs = resolveName(stream, stream.next).map(type => {\n if (stream.inline == null)\n stream.inline = type.isInline;\n else if (stream.inline != type.isInline)\n stream.err(\"Mixing inline and block content\");\n return { type: \"name\", value: type };\n });\n stream.pos++;\n return exprs.length == 1 ? exprs[0] : { type: \"choice\", exprs };\n }\n else {\n stream.err(\"Unexpected token '\" + stream.next + \"'\");\n }\n}\n// Construct an NFA from an expression as returned by the parser. The\n// NFA is represented as an array of states, which are themselves\n// arrays of edges, which are `{term, to}` objects. The first state is\n// the entry state and the last node is the success state.\n//\n// Note that unlike typical NFAs, the edge ordering in this one is\n// significant, in that it is used to contruct filler content when\n// necessary.\nfunction nfa(expr) {\n let nfa = [[]];\n connect(compile(expr, 0), node());\n return nfa;\n function node() { return nfa.push([]) - 1; }\n function edge(from, to, term) {\n let edge = { term, to };\n nfa[from].push(edge);\n return edge;\n }\n function connect(edges, to) {\n edges.forEach(edge => edge.to = to);\n }\n function compile(expr, from) {\n if (expr.type == \"choice\") {\n return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []);\n }\n else if (expr.type == \"seq\") {\n for (let i = 0;; i++) {\n let next = compile(expr.exprs[i], from);\n if (i == expr.exprs.length - 1)\n return next;\n connect(next, from = node());\n }\n }\n else if (expr.type == \"star\") {\n let loop = node();\n edge(from, loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"plus\") {\n let loop = node();\n connect(compile(expr.expr, from), loop);\n connect(compile(expr.expr, loop), loop);\n return [edge(loop)];\n }\n else if (expr.type == \"opt\") {\n return [edge(from)].concat(compile(expr.expr, from));\n }\n else if (expr.type == \"range\") {\n let cur = from;\n for (let i = 0; i < expr.min; i++) {\n let next = node();\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n if (expr.max == -1) {\n connect(compile(expr.expr, cur), cur);\n }\n else {\n for (let i = expr.min; i < expr.max; i++) {\n let next = node();\n edge(cur, next);\n connect(compile(expr.expr, cur), next);\n cur = next;\n }\n }\n return [edge(cur)];\n }\n else if (expr.type == \"name\") {\n return [edge(from, undefined, expr.value)];\n }\n else {\n throw new Error(\"Unknown expr type\");\n }\n }\n}\nfunction cmp(a, b) { return b - a; }\n// Get the set of nodes reachable by null edges from `node`. Omit\n// nodes with only a single null-out-edge, since they may lead to\n// needless duplicated nodes.\nfunction nullFrom(nfa, node) {\n let result = [];\n scan(node);\n return result.sort(cmp);\n function scan(node) {\n let edges = nfa[node];\n if (edges.length == 1 && !edges[0].term)\n return scan(edges[0].to);\n result.push(node);\n for (let i = 0; i < edges.length; i++) {\n let { term, to } = edges[i];\n if (!term && result.indexOf(to) == -1)\n scan(to);\n }\n }\n}\n// Compiles an NFA as produced by `nfa` into a DFA, modeled as a set\n// of state objects (`ContentMatch` instances) with transitions\n// between them.\nfunction dfa(nfa) {\n let labeled = Object.create(null);\n return explore(nullFrom(nfa, 0));\n function explore(states) {\n let out = [];\n states.forEach(node => {\n nfa[node].forEach(({ term, to }) => {\n if (!term)\n return;\n let set;\n for (let i = 0; i < out.length; i++)\n if (out[i][0] == term)\n set = out[i][1];\n nullFrom(nfa, to).forEach(node => {\n if (!set)\n out.push([term, set = []]);\n if (set.indexOf(node) == -1)\n set.push(node);\n });\n });\n });\n let state = labeled[states.join(\",\")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1);\n for (let i = 0; i < out.length; i++) {\n let states = out[i][1].sort(cmp);\n state.next.push({ type: out[i][0], next: labeled[states.join(\",\")] || explore(states) });\n }\n return state;\n }\n}\nfunction checkForDeadEnds(match, stream) {\n for (let i = 0, work = [match]; i < work.length; i++) {\n let state = work[i], dead = !state.validEnd, nodes = [];\n for (let j = 0; j < state.next.length; j++) {\n let { type, next } = state.next[j];\n nodes.push(type.name);\n if (dead && !(type.isText || type.hasRequiredAttrs()))\n dead = false;\n if (work.indexOf(next) == -1)\n work.push(next);\n }\n if (dead)\n stream.err(\"Only non-generatable nodes (\" + nodes.join(\", \") + \") in a required position (see https://prosemirror.net/docs/guide/#generatable)\");\n }\n}\n\n// For node types where all attrs have a default value (or which don't\n// have any attributes), build up a single reusable default attribute\n// object, and use it for all nodes that don't specify specific\n// attributes.\nfunction defaultAttrs(attrs) {\n let defaults = Object.create(null);\n for (let attrName in attrs) {\n let attr = attrs[attrName];\n if (!attr.hasDefault)\n return null;\n defaults[attrName] = attr.default;\n }\n return defaults;\n}\nfunction computeAttrs(attrs, value) {\n let built = Object.create(null);\n for (let name in attrs) {\n let given = value && value[name];\n if (given === undefined) {\n let attr = attrs[name];\n if (attr.hasDefault)\n given = attr.default;\n else\n throw new RangeError(\"No value supplied for attribute \" + name);\n }\n built[name] = given;\n }\n return built;\n}\nfunction checkAttrs(attrs, values, type, name) {\n for (let name in values)\n if (!(name in attrs))\n throw new RangeError(`Unsupported attribute ${name} for ${type} of type ${name}`);\n for (let name in attrs) {\n let attr = attrs[name];\n if (attr.validate)\n attr.validate(values[name]);\n }\n}\nfunction initAttrs(typeName, attrs) {\n let result = Object.create(null);\n if (attrs)\n for (let name in attrs)\n result[name] = new Attribute(typeName, name, attrs[name]);\n return result;\n}\n/**\nNode types are objects allocated once per `Schema` and used to\n[tag](https://prosemirror.net/docs/ref/#model.Node.type) `Node` instances. They contain information\nabout the node type, such as its name and what kind of node it\nrepresents.\n*/\nclass NodeType {\n /**\n @internal\n */\n constructor(\n /**\n The name the node type has in this schema.\n */\n name, \n /**\n A link back to the `Schema` the node type belongs to.\n */\n schema, \n /**\n The spec that this type is based on\n */\n spec) {\n this.name = name;\n this.schema = schema;\n this.spec = spec;\n /**\n The set of marks allowed in this node. `null` means all marks\n are allowed.\n */\n this.markSet = null;\n this.groups = spec.group ? spec.group.split(\" \") : [];\n this.attrs = initAttrs(name, spec.attrs);\n this.defaultAttrs = defaultAttrs(this.attrs);\n this.contentMatch = null;\n this.inlineContent = null;\n this.isBlock = !(spec.inline || name == \"text\");\n this.isText = name == \"text\";\n }\n /**\n True if this is an inline type.\n */\n get isInline() { return !this.isBlock; }\n /**\n True if this is a textblock type, a block that contains inline\n content.\n */\n get isTextblock() { return this.isBlock && this.inlineContent; }\n /**\n True for node types that allow no content.\n */\n get isLeaf() { return this.contentMatch == ContentMatch.empty; }\n /**\n True when this node is an atom, i.e. when it does not have\n directly editable content.\n */\n get isAtom() { return this.isLeaf || !!this.spec.atom; }\n /**\n Return true when this node type is part of the given\n [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).\n */\n isInGroup(group) {\n return this.groups.indexOf(group) > -1;\n }\n /**\n The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.\n */\n get whitespace() {\n return this.spec.whitespace || (this.spec.code ? \"pre\" : \"normal\");\n }\n /**\n Tells you whether this node type has any required attributes.\n */\n hasRequiredAttrs() {\n for (let n in this.attrs)\n if (this.attrs[n].isRequired)\n return true;\n return false;\n }\n /**\n Indicates whether this node allows some of the same content as\n the given node type.\n */\n compatibleContent(other) {\n return this == other || this.contentMatch.compatible(other.contentMatch);\n }\n /**\n @internal\n */\n computeAttrs(attrs) {\n if (!attrs && this.defaultAttrs)\n return this.defaultAttrs;\n else\n return computeAttrs(this.attrs, attrs);\n }\n /**\n Create a `Node` of this type. The given attributes are\n checked and defaulted (you can pass `null` to use the type's\n defaults entirely, if no required attributes exist). `content`\n may be a `Fragment`, a node, an array of nodes, or\n `null`. Similarly `marks` may be `null` to default to the empty\n set of marks.\n */\n create(attrs = null, content, marks) {\n if (this.isText)\n throw new Error(\"NodeType.create can't construct text nodes\");\n return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content\n against the node type's content restrictions, and throw an error\n if it doesn't match.\n */\n createChecked(attrs = null, content, marks) {\n content = Fragment.from(content);\n this.checkContent(content);\n return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));\n }\n /**\n Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is\n necessary to add nodes to the start or end of the given fragment\n to make it fit the node. If no fitting wrapping can be found,\n return null. Note that, due to the fact that required nodes can\n always be created, this will always succeed if you pass null or\n `Fragment.empty` as content.\n */\n createAndFill(attrs = null, content, marks) {\n attrs = this.computeAttrs(attrs);\n content = Fragment.from(content);\n if (content.size) {\n let before = this.contentMatch.fillBefore(content);\n if (!before)\n return null;\n content = before.append(content);\n }\n let matched = this.contentMatch.matchFragment(content);\n let after = matched && matched.fillBefore(Fragment.empty, true);\n if (!after)\n return null;\n return new Node(this, attrs, content.append(after), Mark.setFrom(marks));\n }\n /**\n Returns true if the given fragment is valid content for this node\n type.\n */\n validContent(content) {\n let result = this.contentMatch.matchFragment(content);\n if (!result || !result.validEnd)\n return false;\n for (let i = 0; i < content.childCount; i++)\n if (!this.allowsMarks(content.child(i).marks))\n return false;\n return true;\n }\n /**\n Throws a RangeError if the given fragment is not valid content for this\n node type.\n @internal\n */\n checkContent(content) {\n if (!this.validContent(content))\n throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"node\", this.name);\n }\n /**\n Check whether the given mark type is allowed in this node.\n */\n allowsMarkType(markType) {\n return this.markSet == null || this.markSet.indexOf(markType) > -1;\n }\n /**\n Test whether the given set of marks are allowed in this node.\n */\n allowsMarks(marks) {\n if (this.markSet == null)\n return true;\n for (let i = 0; i < marks.length; i++)\n if (!this.allowsMarkType(marks[i].type))\n return false;\n return true;\n }\n /**\n Removes the marks that are not allowed in this node from the given set.\n */\n allowedMarks(marks) {\n if (this.markSet == null)\n return marks;\n let copy;\n for (let i = 0; i < marks.length; i++) {\n if (!this.allowsMarkType(marks[i].type)) {\n if (!copy)\n copy = marks.slice(0, i);\n }\n else if (copy) {\n copy.push(marks[i]);\n }\n }\n return !copy ? marks : copy.length ? copy : Mark.none;\n }\n /**\n @internal\n */\n static compile(nodes, schema) {\n let result = Object.create(null);\n nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec));\n let topType = schema.spec.topNode || \"doc\";\n if (!result[topType])\n throw new RangeError(\"Schema is missing its top node type ('\" + topType + \"')\");\n if (!result.text)\n throw new RangeError(\"Every schema needs a 'text' type\");\n for (let _ in result.text.attrs)\n throw new RangeError(\"The text node type should not have attributes\");\n return result;\n }\n}\nfunction validateType(typeName, attrName, type) {\n let types = type.split(\"|\");\n return (value) => {\n let name = value === null ? \"null\" : typeof value;\n if (types.indexOf(name) < 0)\n throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);\n };\n}\n// Attribute descriptors\nclass Attribute {\n constructor(typeName, attrName, options) {\n this.hasDefault = Object.prototype.hasOwnProperty.call(options, \"default\");\n this.default = options.default;\n this.validate = typeof options.validate == \"string\" ? validateType(typeName, attrName, options.validate) : options.validate;\n }\n get isRequired() {\n return !this.hasDefault;\n }\n}\n// Marks\n/**\nLike nodes, marks (which are associated with nodes to signify\nthings like emphasis or being part of a link) are\n[tagged](https://prosemirror.net/docs/ref/#model.Mark.type) with type objects, which are\ninstantiated once per `Schema`.\n*/\nclass MarkType {\n /**\n @internal\n */\n constructor(\n /**\n The name of the mark type.\n */\n name, \n /**\n @internal\n */\n rank, \n /**\n The schema that this mark type instance is part of.\n */\n schema, \n /**\n The spec on which the type is based.\n */\n spec) {\n this.name = name;\n this.rank = rank;\n this.schema = schema;\n this.spec = spec;\n this.attrs = initAttrs(name, spec.attrs);\n this.excluded = null;\n let defaults = defaultAttrs(this.attrs);\n this.instance = defaults ? new Mark(this, defaults) : null;\n }\n /**\n Create a mark of this type. `attrs` may be `null` or an object\n containing only some of the mark's attributes. The others, if\n they have defaults, will be added.\n */\n create(attrs = null) {\n if (!attrs && this.instance)\n return this.instance;\n return new Mark(this, computeAttrs(this.attrs, attrs));\n }\n /**\n @internal\n */\n static compile(marks, schema) {\n let result = Object.create(null), rank = 0;\n marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec));\n return result;\n }\n /**\n When there is a mark of this type in the given set, a new set\n without it is returned. Otherwise, the input set is returned.\n */\n removeFromSet(set) {\n for (var i = 0; i < set.length; i++)\n if (set[i].type == this) {\n set = set.slice(0, i).concat(set.slice(i + 1));\n i--;\n }\n return set;\n }\n /**\n Tests whether there is a mark of this type in the given set.\n */\n isInSet(set) {\n for (let i = 0; i < set.length; i++)\n if (set[i].type == this)\n return set[i];\n }\n /**\n @internal\n */\n checkAttrs(attrs) {\n checkAttrs(this.attrs, attrs, \"mark\", this.name);\n }\n /**\n Queries whether a given mark type is\n [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.\n */\n excludes(other) {\n return this.excluded.indexOf(other) > -1;\n }\n}\n/**\nA document schema. Holds [node](https://prosemirror.net/docs/ref/#model.NodeType) and [mark\ntype](https://prosemirror.net/docs/ref/#model.MarkType) objects for the nodes and marks that may\noccur in conforming documents, and provides functionality for\ncreating and deserializing such documents.\n\nWhen given, the type parameters provide the names of the nodes and\nmarks in this schema.\n*/\nclass Schema {\n /**\n Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).\n */\n constructor(spec) {\n /**\n The [linebreak\n replacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement) node defined\n in this schema, if any.\n */\n this.linebreakReplacement = null;\n /**\n An object for storing whatever values modules may want to\n compute and cache per schema. (If you want to store something\n in it, try to use property names unlikely to clash.)\n */\n this.cached = Object.create(null);\n let instanceSpec = this.spec = {};\n for (let prop in spec)\n instanceSpec[prop] = spec[prop];\n instanceSpec.nodes = OrderedMap.from(spec.nodes),\n instanceSpec.marks = OrderedMap.from(spec.marks || {}),\n this.nodes = NodeType.compile(this.spec.nodes, this);\n this.marks = MarkType.compile(this.spec.marks, this);\n let contentExprCache = Object.create(null);\n for (let prop in this.nodes) {\n if (prop in this.marks)\n throw new RangeError(prop + \" can not be both a node and a mark\");\n let type = this.nodes[prop], contentExpr = type.spec.content || \"\", markExpr = type.spec.marks;\n type.contentMatch = contentExprCache[contentExpr] ||\n (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));\n type.inlineContent = type.contentMatch.inlineContent;\n if (type.spec.linebreakReplacement) {\n if (this.linebreakReplacement)\n throw new RangeError(\"Multiple linebreak nodes defined\");\n if (!type.isInline || !type.isLeaf)\n throw new RangeError(\"Linebreak replacement nodes must be inline leaf nodes\");\n this.linebreakReplacement = type;\n }\n type.markSet = markExpr == \"_\" ? null :\n markExpr ? gatherMarks(this, markExpr.split(\" \")) :\n markExpr == \"\" || !type.inlineContent ? [] : null;\n }\n for (let prop in this.marks) {\n let type = this.marks[prop], excl = type.spec.excludes;\n type.excluded = excl == null ? [type] : excl == \"\" ? [] : gatherMarks(this, excl.split(\" \"));\n }\n this.nodeFromJSON = json => Node.fromJSON(this, json);\n this.markFromJSON = json => Mark.fromJSON(this, json);\n this.topNodeType = this.nodes[this.spec.topNode || \"doc\"];\n this.cached.wrappings = Object.create(null);\n }\n /**\n Create a node in this schema. The `type` may be a string or a\n `NodeType` instance. Attributes will be extended with defaults,\n `content` may be a `Fragment`, `null`, a `Node`, or an array of\n nodes.\n */\n node(type, attrs = null, content, marks) {\n if (typeof type == \"string\")\n type = this.nodeType(type);\n else if (!(type instanceof NodeType))\n throw new RangeError(\"Invalid node type: \" + type);\n else if (type.schema != this)\n throw new RangeError(\"Node type from different schema used (\" + type.name + \")\");\n return type.createChecked(attrs, content, marks);\n }\n /**\n Create a text node in the schema. Empty text nodes are not\n allowed.\n */\n text(text, marks) {\n let type = this.nodes.text;\n return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks));\n }\n /**\n Create a mark with the given type and attributes.\n */\n mark(type, attrs) {\n if (typeof type == \"string\")\n type = this.marks[type];\n return type.create(attrs);\n }\n /**\n @internal\n */\n nodeType(name) {\n let found = this.nodes[name];\n if (!found)\n throw new RangeError(\"Unknown node type: \" + name);\n return found;\n }\n}\nfunction gatherMarks(schema, marks) {\n let found = [];\n for (let i = 0; i < marks.length; i++) {\n let name = marks[i], mark = schema.marks[name], ok = mark;\n if (mark) {\n found.push(mark);\n }\n else {\n for (let prop in schema.marks) {\n let mark = schema.marks[prop];\n if (name == \"_\" || (mark.spec.group && mark.spec.group.split(\" \").indexOf(name) > -1))\n found.push(ok = mark);\n }\n }\n if (!ok)\n throw new SyntaxError(\"Unknown mark type: '\" + marks[i] + \"'\");\n }\n return found;\n}\n\nfunction isTagRule(rule) { return rule.tag != null; }\nfunction isStyleRule(rule) { return rule.style != null; }\n/**\nA DOM parser represents a strategy for parsing DOM content into a\nProseMirror document conforming to a given schema. Its behavior is\ndefined by an array of [rules](https://prosemirror.net/docs/ref/#model.ParseRule).\n*/\nclass DOMParser {\n /**\n Create a parser that targets the given schema, using the given\n parsing rules.\n */\n constructor(\n /**\n The schema into which the parser parses.\n */\n schema, \n /**\n The set of [parse rules](https://prosemirror.net/docs/ref/#model.ParseRule) that the parser\n uses, in order of precedence.\n */\n rules) {\n this.schema = schema;\n this.rules = rules;\n /**\n @internal\n */\n this.tags = [];\n /**\n @internal\n */\n this.styles = [];\n let matchedStyles = this.matchedStyles = [];\n rules.forEach(rule => {\n if (isTagRule(rule)) {\n this.tags.push(rule);\n }\n else if (isStyleRule(rule)) {\n let prop = /[^=]*/.exec(rule.style)[0];\n if (matchedStyles.indexOf(prop) < 0)\n matchedStyles.push(prop);\n this.styles.push(rule);\n }\n });\n // Only normalize list elements when lists in the schema can't directly contain themselves\n this.normalizeLists = !this.tags.some(r => {\n if (!/^(ul|ol)\\b/.test(r.tag) || !r.node)\n return false;\n let node = schema.nodes[r.node];\n return node.contentMatch.matchType(node);\n });\n }\n /**\n Parse a document from the content of a DOM node.\n */\n parse(dom, options = {}) {\n let context = new ParseContext(this, options, false);\n context.addAll(dom, Mark.none, options.from, options.to);\n return context.finish();\n }\n /**\n Parses the content of the given DOM node, like\n [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of\n options. But unlike that method, which produces a whole node,\n this one returns a slice that is open at the sides, meaning that\n the schema constraints aren't applied to the start of nodes to\n the left of the input and the end of nodes at the end.\n */\n parseSlice(dom, options = {}) {\n let context = new ParseContext(this, options, true);\n context.addAll(dom, Mark.none, options.from, options.to);\n return Slice.maxOpen(context.finish());\n }\n /**\n @internal\n */\n matchTag(dom, context, after) {\n for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {\n let rule = this.tags[i];\n if (matches(dom, rule.tag) &&\n (rule.namespace === undefined || dom.namespaceURI == rule.namespace) &&\n (!rule.context || context.matchesContext(rule.context))) {\n if (rule.getAttrs) {\n let result = rule.getAttrs(dom);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n }\n /**\n @internal\n */\n matchStyle(prop, value, context, after) {\n for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {\n let rule = this.styles[i], style = rule.style;\n if (style.indexOf(prop) != 0 ||\n rule.context && !context.matchesContext(rule.context) ||\n // Test that the style string either precisely matches the prop,\n // or has an '=' sign after the prop, followed by the given\n // value.\n style.length > prop.length &&\n (style.charCodeAt(prop.length) != 61 || style.slice(prop.length + 1) != value))\n continue;\n if (rule.getAttrs) {\n let result = rule.getAttrs(value);\n if (result === false)\n continue;\n rule.attrs = result || undefined;\n }\n return rule;\n }\n }\n /**\n @internal\n */\n static schemaRules(schema) {\n let result = [];\n function insert(rule) {\n let priority = rule.priority == null ? 50 : rule.priority, i = 0;\n for (; i < result.length; i++) {\n let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;\n if (nextPriority < priority)\n break;\n }\n result.splice(i, 0, rule);\n }\n for (let name in schema.marks) {\n let rules = schema.marks[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.mark || rule.ignore || rule.clearMark))\n rule.mark = name;\n });\n }\n for (let name in schema.nodes) {\n let rules = schema.nodes[name].spec.parseDOM;\n if (rules)\n rules.forEach(rule => {\n insert(rule = copy(rule));\n if (!(rule.node || rule.ignore || rule.mark))\n rule.node = name;\n });\n }\n return result;\n }\n /**\n Construct a DOM parser using the parsing rules listed in a\n schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by\n [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).\n */\n static fromSchema(schema) {\n return schema.cached.domParser ||\n (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema)));\n }\n}\nconst blockTags = {\n address: true, article: true, aside: true, blockquote: true, canvas: true,\n dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true,\n footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true,\n h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true,\n output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true\n};\nconst ignoreTags = {\n head: true, noscript: true, object: true, script: true, style: true, title: true\n};\nconst listTags = { ol: true, ul: true };\n// Using a bitfield for node context options\nconst OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4;\nfunction wsOptionsFor(type, preserveWhitespace, base) {\n if (preserveWhitespace != null)\n return (preserveWhitespace ? OPT_PRESERVE_WS : 0) |\n (preserveWhitespace === \"full\" ? OPT_PRESERVE_WS_FULL : 0);\n return type && type.whitespace == \"pre\" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base & ~OPT_OPEN_LEFT;\n}\nclass NodeContext {\n constructor(type, attrs, marks, solid, match, options) {\n this.type = type;\n this.attrs = attrs;\n this.marks = marks;\n this.solid = solid;\n this.options = options;\n this.content = [];\n // Marks applied to the node's children\n this.activeMarks = Mark.none;\n this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);\n }\n findWrapping(node) {\n if (!this.match) {\n if (!this.type)\n return [];\n let fill = this.type.contentMatch.fillBefore(Fragment.from(node));\n if (fill) {\n this.match = this.type.contentMatch.matchFragment(fill);\n }\n else {\n let start = this.type.contentMatch, wrap;\n if (wrap = start.findWrapping(node.type)) {\n this.match = start;\n return wrap;\n }\n else {\n return null;\n }\n }\n }\n return this.match.findWrapping(node.type);\n }\n finish(openEnd) {\n if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace\n let last = this.content[this.content.length - 1], m;\n if (last && last.isText && (m = /[ \\t\\r\\n\\u000c]+$/.exec(last.text))) {\n let text = last;\n if (last.text.length == m[0].length)\n this.content.pop();\n else\n this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length));\n }\n }\n let content = Fragment.from(this.content);\n if (!openEnd && this.match)\n content = content.append(this.match.fillBefore(Fragment.empty, true));\n return this.type ? this.type.create(this.attrs, content, this.marks) : content;\n }\n inlineContext(node) {\n if (this.type)\n return this.type.inlineContent;\n if (this.content.length)\n return this.content[0].isInline;\n return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());\n }\n}\nclass ParseContext {\n constructor(\n // The parser we are using.\n parser, \n // The options passed to this parse.\n options, isOpen) {\n this.parser = parser;\n this.options = options;\n this.isOpen = isOpen;\n this.open = 0;\n this.localPreserveWS = false;\n let topNode = options.topNode, topContext;\n let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);\n if (topNode)\n topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);\n else if (isOpen)\n topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);\n else\n topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);\n this.nodes = [topContext];\n this.find = options.findPositions;\n this.needsBlock = false;\n }\n get top() {\n return this.nodes[this.open];\n }\n // Add a DOM node to the content. Text is inserted as text node,\n // otherwise, the node is passed to `addElement` or, if it has a\n // `style` attribute, `addElementWithStyles`.\n addDOM(dom, marks) {\n if (dom.nodeType == 3)\n this.addTextNode(dom, marks);\n else if (dom.nodeType == 1)\n this.addElement(dom, marks);\n }\n addTextNode(dom, marks) {\n let value = dom.nodeValue;\n let top = this.top, preserveWS = (top.options & OPT_PRESERVE_WS_FULL) ? \"full\"\n : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;\n let { schema } = this.parser;\n if (preserveWS === \"full\" ||\n top.inlineContext(dom) ||\n /[^ \\t\\r\\n\\u000c]/.test(value)) {\n if (!preserveWS) {\n value = value.replace(/[ \\t\\r\\n\\u000c]+/g, \" \");\n // If this starts with whitespace, and there is no node before it, or\n // a hard break, or a text node that ends with whitespace, strip the\n // leading space.\n if (/^[ \\t\\r\\n\\u000c]/.test(value) && this.open == this.nodes.length - 1) {\n let nodeBefore = top.content[top.content.length - 1];\n let domNodeBefore = dom.previousSibling;\n if (!nodeBefore ||\n (domNodeBefore && domNodeBefore.nodeName == 'BR') ||\n (nodeBefore.isText && /[ \\t\\r\\n\\u000c]$/.test(nodeBefore.text)))\n value = value.slice(1);\n }\n }\n else if (preserveWS === \"full\") {\n value = value.replace(/\\r\\n?/g, \"\\n\");\n }\n else if (schema.linebreakReplacement && /[\\r\\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {\n let lines = value.split(/\\r?\\n|\\r/);\n for (let i = 0; i < lines.length; i++) {\n if (i)\n this.insertNode(schema.linebreakReplacement.create(), marks, true);\n if (lines[i])\n this.insertNode(schema.text(lines[i]), marks, !/\\S/.test(lines[i]));\n }\n value = \"\";\n }\n else {\n value = value.replace(/\\r?\\n|\\r/g, \" \");\n }\n if (value)\n this.insertNode(schema.text(value), marks, !/\\S/.test(value));\n this.findInText(dom);\n }\n else {\n this.findInside(dom);\n }\n }\n // Try to find a handler for the given tag and use that to parse. If\n // none is found, the element's content nodes are added directly.\n addElement(dom, marks, matchAfter) {\n let outerWS = this.localPreserveWS, top = this.top;\n if (dom.tagName == \"PRE\" || /pre/.test(dom.style && dom.style.whiteSpace))\n this.localPreserveWS = true;\n let name = dom.nodeName.toLowerCase(), ruleID;\n if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)\n normalizeList(dom);\n let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) ||\n (ruleID = this.parser.matchTag(dom, this, matchAfter));\n out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {\n this.findInside(dom);\n this.ignoreFallback(dom, marks);\n }\n else if (!rule || rule.skip || rule.closeParent) {\n if (rule && rule.closeParent)\n this.open = Math.max(0, this.open - 1);\n else if (rule && rule.skip.nodeType)\n dom = rule.skip;\n let sync, oldNeedsBlock = this.needsBlock;\n if (blockTags.hasOwnProperty(name)) {\n if (top.content.length && top.content[0].isInline && this.open) {\n this.open--;\n top = this.top;\n }\n sync = true;\n if (!top.type)\n this.needsBlock = true;\n }\n else if (!dom.firstChild) {\n this.leafFallback(dom, marks);\n break out;\n }\n let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);\n if (innerMarks)\n this.addAll(dom, innerMarks);\n if (sync)\n this.sync(top);\n this.needsBlock = oldNeedsBlock;\n }\n else {\n let innerMarks = this.readStyles(dom, marks);\n if (innerMarks)\n this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : undefined);\n }\n this.localPreserveWS = outerWS;\n }\n // Called for leaf DOM nodes that would otherwise be ignored\n leafFallback(dom, marks) {\n if (dom.nodeName == \"BR\" && this.top.type && this.top.type.inlineContent)\n this.addTextNode(dom.ownerDocument.createTextNode(\"\\n\"), marks);\n }\n // Called for ignored nodes\n ignoreFallback(dom, marks) {\n // Ignored BR nodes should at least create an inline context\n if (dom.nodeName == \"BR\" && (!this.top.type || !this.top.type.inlineContent))\n this.findPlace(this.parser.schema.text(\"-\"), marks, true);\n }\n // Run any style parser associated with the node's styles. Either\n // return an updated array of marks, or null to indicate some of the\n // styles had a rule with `ignore` set.\n readStyles(dom, marks) {\n let styles = dom.style;\n // Because many properties will only show up in 'normalized' form\n // in `style.item` (i.e. text-decoration becomes\n // text-decoration-line, text-decoration-color, etc), we directly\n // query the styles mentioned in our rules instead of iterating\n // over the items.\n if (styles && styles.length)\n for (let i = 0; i < this.parser.matchedStyles.length; i++) {\n let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name);\n if (value)\n for (let after = undefined;;) {\n let rule = this.parser.matchStyle(name, value, this, after);\n if (!rule)\n break;\n if (rule.ignore)\n return null;\n if (rule.clearMark)\n marks = marks.filter(m => !rule.clearMark(m));\n else\n marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));\n if (rule.consuming === false)\n after = rule;\n else\n break;\n }\n }\n return marks;\n }\n // Look up a handler for the given node. If none are found, return\n // false. Otherwise, apply it, use its return value to drive the way\n // the node's content is wrapped, and return true.\n addElementByRule(dom, rule, marks, continueAfter) {\n let sync, nodeType;\n if (rule.node) {\n nodeType = this.parser.schema.nodes[rule.node];\n if (!nodeType.isLeaf) {\n let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);\n if (inner) {\n sync = true;\n marks = inner;\n }\n }\n else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == \"BR\")) {\n this.leafFallback(dom, marks);\n }\n }\n else {\n let markType = this.parser.schema.marks[rule.mark];\n marks = marks.concat(markType.create(rule.attrs));\n }\n let startIn = this.top;\n if (nodeType && nodeType.isLeaf) {\n this.findInside(dom);\n }\n else if (continueAfter) {\n this.addElement(dom, marks, continueAfter);\n }\n else if (rule.getContent) {\n this.findInside(dom);\n rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node, marks, false));\n }\n else {\n let contentDOM = dom;\n if (typeof rule.contentElement == \"string\")\n contentDOM = dom.querySelector(rule.contentElement);\n else if (typeof rule.contentElement == \"function\")\n contentDOM = rule.contentElement(dom);\n else if (rule.contentElement)\n contentDOM = rule.contentElement;\n this.findAround(dom, contentDOM, true);\n this.addAll(contentDOM, marks);\n this.findAround(dom, contentDOM, false);\n }\n if (sync && this.sync(startIn))\n this.open--;\n }\n // Add all child nodes between `startIndex` and `endIndex` (or the\n // whole node, if not given). If `sync` is passed, use it to\n // synchronize after every block element.\n addAll(parent, marks, startIndex, endIndex) {\n let index = startIndex || 0;\n for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {\n this.findAtPoint(parent, index);\n this.addDOM(dom, marks);\n }\n this.findAtPoint(parent, index);\n }\n // Try to find a way to fit the given node type into the current\n // context. May add intermediate wrappers and/or leave non-solid\n // nodes that we're in.\n findPlace(node, marks, cautious) {\n let route, sync;\n for (let depth = this.open, penalty = 0; depth >= 0; depth--) {\n let cx = this.nodes[depth];\n let found = cx.findWrapping(node);\n if (found && (!route || route.length > found.length + penalty)) {\n route = found;\n sync = cx;\n if (!found.length)\n break;\n }\n if (cx.solid) {\n if (cautious)\n break;\n penalty += 2;\n }\n }\n if (!route)\n return null;\n this.sync(sync);\n for (let i = 0; i < route.length; i++)\n marks = this.enterInner(route[i], null, marks, false);\n return marks;\n }\n // Try to insert the given node, adjusting the context when needed.\n insertNode(node, marks, cautious) {\n if (node.isInline && this.needsBlock && !this.top.type) {\n let block = this.textblockFromContext();\n if (block)\n marks = this.enterInner(block, null, marks);\n }\n let innerMarks = this.findPlace(node, marks, cautious);\n if (innerMarks) {\n this.closeExtra();\n let top = this.top;\n if (top.match)\n top.match = top.match.matchType(node.type);\n let nodeMarks = Mark.none;\n for (let m of innerMarks.concat(node.marks))\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))\n nodeMarks = m.addToSet(nodeMarks);\n top.content.push(node.mark(nodeMarks));\n return true;\n }\n return false;\n }\n // Try to start a node of the given type, adjusting the context when\n // necessary.\n enter(type, attrs, marks, preserveWS) {\n let innerMarks = this.findPlace(type.create(attrs), marks, false);\n if (innerMarks)\n innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);\n return innerMarks;\n }\n // Open a node of the given type\n enterInner(type, attrs, marks, solid = false, preserveWS) {\n this.closeExtra();\n let top = this.top;\n top.match = top.match && top.match.matchType(type);\n let options = wsOptionsFor(type, preserveWS, top.options);\n if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0)\n options |= OPT_OPEN_LEFT;\n let applyMarks = Mark.none;\n marks = marks.filter(m => {\n if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {\n applyMarks = m.addToSet(applyMarks);\n return false;\n }\n return true;\n });\n this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));\n this.open++;\n return marks;\n }\n // Make sure all nodes above this.open are finished and added to\n // their parents\n closeExtra(openEnd = false) {\n let i = this.nodes.length - 1;\n if (i > this.open) {\n for (; i > this.open; i--)\n this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));\n this.nodes.length = this.open + 1;\n }\n }\n finish() {\n this.open = 0;\n this.closeExtra(this.isOpen);\n return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));\n }\n sync(to) {\n for (let i = this.open; i >= 0; i--) {\n if (this.nodes[i] == to) {\n this.open = i;\n return true;\n }\n else if (this.localPreserveWS) {\n this.nodes[i].options |= OPT_PRESERVE_WS;\n }\n }\n return false;\n }\n get currentPos() {\n this.closeExtra();\n let pos = 0;\n for (let i = this.open; i >= 0; i--) {\n let content = this.nodes[i].content;\n for (let j = content.length - 1; j >= 0; j--)\n pos += content[j].nodeSize;\n if (i)\n pos++;\n }\n return pos;\n }\n findAtPoint(parent, offset) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == parent && this.find[i].offset == offset)\n this.find[i].pos = this.currentPos;\n }\n }\n findInside(parent) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))\n this.find[i].pos = this.currentPos;\n }\n }\n findAround(parent, content, before) {\n if (parent != content && this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {\n let pos = content.compareDocumentPosition(this.find[i].node);\n if (pos & (before ? 2 : 4))\n this.find[i].pos = this.currentPos;\n }\n }\n }\n findInText(textNode) {\n if (this.find)\n for (let i = 0; i < this.find.length; i++) {\n if (this.find[i].node == textNode)\n this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);\n }\n }\n // Determines whether the given context string matches this context.\n matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n }\n else {\n let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type\n : option && depth >= minDepth ? option.node(depth - minDepth).type\n : null;\n if (!next || (next.name != part && !next.isInGroup(part)))\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }\n textblockFromContext() {\n let $context = this.options.context;\n if ($context)\n for (let d = $context.depth; d >= 0; d--) {\n let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;\n if (deflt && deflt.isTextblock && deflt.defaultAttrs)\n return deflt;\n }\n for (let name in this.parser.schema.nodes) {\n let type = this.parser.schema.nodes[name];\n if (type.isTextblock && type.defaultAttrs)\n return type;\n }\n }\n}\n// Kludge to work around directly nested list nodes produced by some\n// tools and allowed by browsers to mean that the nested list is\n// actually part of the list item above it.\nfunction normalizeList(dom) {\n for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {\n let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;\n if (name && listTags.hasOwnProperty(name) && prevItem) {\n prevItem.appendChild(child);\n child = prevItem;\n }\n else if (name == \"li\") {\n prevItem = child;\n }\n else if (name) {\n prevItem = null;\n }\n }\n}\n// Apply a CSS selector.\nfunction matches(dom, selector) {\n return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);\n}\nfunction copy(obj) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n return copy;\n}\n// Used when finding a mark at the top level of a fragment parse.\n// Checks whether it would be reasonable to apply a given mark type to\n// a given node, by looking at the way the mark occurs in the schema.\nfunction markMayApply(markType, nodeType) {\n let nodes = nodeType.schema.nodes;\n for (let name in nodes) {\n let parent = nodes[name];\n if (!parent.allowsMarkType(markType))\n continue;\n let seen = [], scan = (match) => {\n seen.push(match);\n for (let i = 0; i < match.edgeCount; i++) {\n let { type, next } = match.edge(i);\n if (type == nodeType)\n return true;\n if (seen.indexOf(next) < 0 && scan(next))\n return true;\n }\n };\n if (scan(parent.contentMatch))\n return true;\n }\n}\n\n/**\nA DOM serializer knows how to convert ProseMirror nodes and\nmarks of various types to DOM nodes.\n*/\nclass DOMSerializer {\n /**\n Create a serializer. `nodes` should map node names to functions\n that take a node and return a description of the corresponding\n DOM. `marks` does the same for mark names, but also gets an\n argument that tells it whether the mark's content is block or\n inline content (for typical use, it'll always be inline). A mark\n serializer may be `null` to indicate that marks of that type\n should not be serialized.\n */\n constructor(\n /**\n The node serialization functions.\n */\n nodes, \n /**\n The mark serialization functions.\n */\n marks) {\n this.nodes = nodes;\n this.marks = marks;\n }\n /**\n Serialize the content of this fragment to a DOM fragment. When\n not in the browser, the `document` option, containing a DOM\n document, should be passed so that the serializer can create\n nodes.\n */\n serializeFragment(fragment, options = {}, target) {\n if (!target)\n target = doc(options).createDocumentFragment();\n let top = target, active = [];\n fragment.forEach(node => {\n if (active.length || node.marks.length) {\n let keep = 0, rendered = 0;\n while (keep < active.length && rendered < node.marks.length) {\n let next = node.marks[rendered];\n if (!this.marks[next.type.name]) {\n rendered++;\n continue;\n }\n if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)\n break;\n keep++;\n rendered++;\n }\n while (keep < active.length)\n top = active.pop()[1];\n while (rendered < node.marks.length) {\n let add = node.marks[rendered++];\n let markDOM = this.serializeMark(add, node.isInline, options);\n if (markDOM) {\n active.push([add, top]);\n top.appendChild(markDOM.dom);\n top = markDOM.contentDOM || markDOM.dom;\n }\n }\n }\n top.appendChild(this.serializeNodeInner(node, options));\n });\n return target;\n }\n /**\n @internal\n */\n serializeNodeInner(node, options) {\n let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);\n if (contentDOM) {\n if (node.isLeaf)\n throw new RangeError(\"Content hole not allowed in a leaf node spec\");\n this.serializeFragment(node.content, options, contentDOM);\n }\n return dom;\n }\n /**\n Serialize this node to a DOM node. This can be useful when you\n need to serialize a part of a document, as opposed to the whole\n document. To serialize a whole document, use\n [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on\n its [content](https://prosemirror.net/docs/ref/#model.Node.content).\n */\n serializeNode(node, options = {}) {\n let dom = this.serializeNodeInner(node, options);\n for (let i = node.marks.length - 1; i >= 0; i--) {\n let wrap = this.serializeMark(node.marks[i], node.isInline, options);\n if (wrap) {\n (wrap.contentDOM || wrap.dom).appendChild(dom);\n dom = wrap.dom;\n }\n }\n return dom;\n }\n /**\n @internal\n */\n serializeMark(mark, inline, options = {}) {\n let toDOM = this.marks[mark.type.name];\n return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);\n }\n static renderSpec(doc, structure, xmlNS = null, blockArraysIn) {\n return renderSpec(doc, structure, xmlNS, blockArraysIn);\n }\n /**\n Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)\n properties in a schema's node and mark specs.\n */\n static fromSchema(schema) {\n return schema.cached.domSerializer ||\n (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));\n }\n /**\n Gather the serializers in a schema's node specs into an object.\n This can be useful as a base to build a custom serializer from.\n */\n static nodesFromSchema(schema) {\n let result = gatherToDOM(schema.nodes);\n if (!result.text)\n result.text = node => node.text;\n return result;\n }\n /**\n Gather the serializers in a schema's mark specs into an object.\n */\n static marksFromSchema(schema) {\n return gatherToDOM(schema.marks);\n }\n}\nfunction gatherToDOM(obj) {\n let result = {};\n for (let name in obj) {\n let toDOM = obj[name].spec.toDOM;\n if (toDOM)\n result[name] = toDOM;\n }\n return result;\n}\nfunction doc(options) {\n return options.document || window.document;\n}\nconst suspiciousAttributeCache = new WeakMap();\nfunction suspiciousAttributes(attrs) {\n let value = suspiciousAttributeCache.get(attrs);\n if (value === undefined)\n suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));\n return value;\n}\nfunction suspiciousAttributesInner(attrs) {\n let result = null;\n function scan(value) {\n if (value && typeof value == \"object\") {\n if (Array.isArray(value)) {\n if (typeof value[0] == \"string\") {\n if (!result)\n result = [];\n result.push(value);\n }\n else {\n for (let i = 0; i < value.length; i++)\n scan(value[i]);\n }\n }\n else {\n for (let prop in value)\n scan(value[prop]);\n }\n }\n }\n scan(attrs);\n return result;\n}\nfunction renderSpec(doc, structure, xmlNS, blockArraysIn) {\n if (typeof structure == \"string\")\n return { dom: doc.createTextNode(structure) };\n if (structure.nodeType != null)\n return { dom: structure };\n if (structure.dom && structure.dom.nodeType != null)\n return structure;\n let tagName = structure[0], suspicious;\n if (typeof tagName != \"string\")\n throw new RangeError(\"Invalid array passed to renderSpec\");\n if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) &&\n suspicious.indexOf(structure) > -1)\n throw new RangeError(\"Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.\");\n let space = tagName.indexOf(\" \");\n if (space > 0) {\n xmlNS = tagName.slice(0, space);\n tagName = tagName.slice(space + 1);\n }\n let contentDOM;\n let dom = (xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName));\n let attrs = structure[1], start = 1;\n if (attrs && typeof attrs == \"object\" && attrs.nodeType == null && !Array.isArray(attrs)) {\n start = 2;\n for (let name in attrs)\n if (attrs[name] != null) {\n let space = name.indexOf(\" \");\n if (space > 0)\n dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]);\n else if (name == \"style\" && dom.style)\n dom.style.cssText = attrs[name];\n else\n dom.setAttribute(name, attrs[name]);\n }\n }\n for (let i = start; i < structure.length; i++) {\n let child = structure[i];\n if (child === 0) {\n if (i < structure.length - 1 || i > start)\n throw new RangeError(\"Content hole must be the only child of its parent node\");\n return { dom, contentDOM: dom };\n }\n else {\n let { dom: inner, contentDOM: innerContent } = renderSpec(doc, child, xmlNS, blockArraysIn);\n dom.appendChild(inner);\n if (innerContent) {\n if (contentDOM)\n throw new RangeError(\"Multiple content holes\");\n contentDOM = innerContent;\n }\n }\n }\n return { dom, contentDOM };\n}\n\nexport { ContentMatch, DOMParser, DOMSerializer, Fragment, Mark, MarkType, Node, NodeRange, NodeType, ReplaceError, ResolvedPos, Schema, Slice };\n", "import { ReplaceError, Slice, Fragment, MarkType, Mark } from 'prosemirror-model';\n\n// Recovery values encode a range index and an offset. They are\n// represented as numbers, because tons of them will be created when\n// mapping, for example, a large number of decorations. The number's\n// lower 16 bits provide the index, the remaining bits the offset.\n//\n// Note: We intentionally don't use bit shift operators to en- and\n// decode these, since those clip to 32 bits, which we might in rare\n// cases want to overflow. A 64-bit float can represent 48-bit\n// integers precisely.\nconst lower16 = 0xffff;\nconst factor16 = Math.pow(2, 16);\nfunction makeRecover(index, offset) { return index + offset * factor16; }\nfunction recoverIndex(value) { return value & lower16; }\nfunction recoverOffset(value) { return (value - (value & lower16)) / factor16; }\nconst DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8;\n/**\nAn object representing a mapped position with extra\ninformation.\n*/\nclass MapResult {\n /**\n @internal\n */\n constructor(\n /**\n The mapped version of the position.\n */\n pos, \n /**\n @internal\n */\n delInfo, \n /**\n @internal\n */\n recover) {\n this.pos = pos;\n this.delInfo = delInfo;\n this.recover = recover;\n }\n /**\n Tells you whether the position was deleted, that is, whether the\n step removed the token on the side queried (via the `assoc`)\n argument from the document.\n */\n get deleted() { return (this.delInfo & DEL_SIDE) > 0; }\n /**\n Tells you whether the token before the mapped position was deleted.\n */\n get deletedBefore() { return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; }\n /**\n True when the token after the mapped position was deleted.\n */\n get deletedAfter() { return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; }\n /**\n Tells whether any of the steps mapped through deletes across the\n position (including both the token before and after the\n position).\n */\n get deletedAcross() { return (this.delInfo & DEL_ACROSS) > 0; }\n}\n/**\nA map describing the deletions and insertions made by a step, which\ncan be used to find the correspondence between positions in the\npre-step version of a document and the same position in the\npost-step version.\n*/\nclass StepMap {\n /**\n Create a position map. The modifications to the document are\n represented as an array of numbers, in which each group of three\n represents a modified chunk as `[start, oldSize, newSize]`.\n */\n constructor(\n /**\n @internal\n */\n ranges, \n /**\n @internal\n */\n inverted = false) {\n this.ranges = ranges;\n this.inverted = inverted;\n if (!ranges.length && StepMap.empty)\n return StepMap.empty;\n }\n /**\n @internal\n */\n recover(value) {\n let diff = 0, index = recoverIndex(value);\n if (!this.inverted)\n for (let i = 0; i < index; i++)\n diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];\n return this.ranges[index * 3] + diff + recoverOffset(value);\n }\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n map(pos, assoc = 1) { return this._map(pos, assoc, true); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;\n if (pos <= end) {\n let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;\n let result = start + diff + (side < 0 ? 0 : newSize);\n if (simple)\n return result;\n let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);\n let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;\n if (assoc < 0 ? pos != start : pos != end)\n del |= DEL_SIDE;\n return new MapResult(result, del, recover);\n }\n diff += newSize - oldSize;\n }\n return simple ? pos + diff : new MapResult(pos + diff, 0, null);\n }\n /**\n @internal\n */\n touches(pos, recover) {\n let diff = 0, index = recoverIndex(recover);\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i] - (this.inverted ? diff : 0);\n if (start > pos)\n break;\n let oldSize = this.ranges[i + oldIndex], end = start + oldSize;\n if (pos <= end && i == index * 3)\n return true;\n diff += this.ranges[i + newIndex] - oldSize;\n }\n return false;\n }\n /**\n Calls the given function on each of the changed ranges included in\n this map.\n */\n forEach(f) {\n let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;\n for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {\n let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);\n let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];\n f(oldStart, oldStart + oldSize, newStart, newStart + newSize);\n diff += newSize - oldSize;\n }\n }\n /**\n Create an inverted version of this map. The result can be used to\n map positions in the post-step document to the pre-step document.\n */\n invert() {\n return new StepMap(this.ranges, !this.inverted);\n }\n /**\n @internal\n */\n toString() {\n return (this.inverted ? \"-\" : \"\") + JSON.stringify(this.ranges);\n }\n /**\n Create a map that moves all positions by offset `n` (which may be\n negative). This can be useful when applying steps meant for a\n sub-document to a larger document, or vice-versa.\n */\n static offset(n) {\n return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);\n }\n}\n/**\nA StepMap that contains no changed ranges.\n*/\nStepMap.empty = new StepMap([]);\n/**\nA mapping represents a pipeline of zero or more [step\nmaps](https://prosemirror.net/docs/ref/#transform.StepMap). It has special provisions for losslessly\nhandling mapping positions through a series of steps in which some\nsteps are inverted versions of earlier steps. (This comes up when\n‘[rebasing](https://prosemirror.net/docs/guide/#transform.rebasing)’ steps for\ncollaboration or history management.)\n*/\nclass Mapping {\n /**\n Create a new mapping with the given position maps.\n */\n constructor(maps, \n /**\n @internal\n */\n mirror, \n /**\n The starting position in the `maps` array, used when `map` or\n `mapResult` is called.\n */\n from = 0, \n /**\n The end position in the `maps` array.\n */\n to = maps ? maps.length : 0) {\n this.mirror = mirror;\n this.from = from;\n this.to = to;\n this._maps = maps || [];\n this.ownData = !(maps || mirror);\n }\n /**\n The step maps in this mapping.\n */\n get maps() { return this._maps; }\n /**\n Create a mapping that maps only through a part of this one.\n */\n slice(from = 0, to = this.maps.length) {\n return new Mapping(this._maps, this.mirror, from, to);\n }\n /**\n Add a step map to the end of this mapping. If `mirrors` is\n given, it should be the index of the step map that is the mirror\n image of this one.\n */\n appendMap(map, mirrors) {\n if (!this.ownData) {\n this._maps = this._maps.slice();\n this.mirror = this.mirror && this.mirror.slice();\n this.ownData = true;\n }\n this.to = this._maps.push(map);\n if (mirrors != null)\n this.setMirror(this._maps.length - 1, mirrors);\n }\n /**\n Add all the step maps in a given mapping to this one (preserving\n mirroring information).\n */\n appendMapping(mapping) {\n for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : undefined);\n }\n }\n /**\n Finds the offset of the step map that mirrors the map at the\n given offset, in this mapping (as per the second argument to\n `appendMap`).\n */\n getMirror(n) {\n if (this.mirror)\n for (let i = 0; i < this.mirror.length; i++)\n if (this.mirror[i] == n)\n return this.mirror[i + (i % 2 ? -1 : 1)];\n }\n /**\n @internal\n */\n setMirror(n, m) {\n if (!this.mirror)\n this.mirror = [];\n this.mirror.push(n, m);\n }\n /**\n Append the inverse of the given mapping to this one.\n */\n appendMappingInverted(mapping) {\n for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) {\n let mirr = mapping.getMirror(i);\n this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : undefined);\n }\n }\n /**\n Create an inverted version of this mapping.\n */\n invert() {\n let inverse = new Mapping;\n inverse.appendMappingInverted(this);\n return inverse;\n }\n /**\n Map a position through this mapping.\n */\n map(pos, assoc = 1) {\n if (this.mirror)\n return this._map(pos, assoc, true);\n for (let i = this.from; i < this.to; i++)\n pos = this._maps[i].map(pos, assoc);\n return pos;\n }\n /**\n Map a position through this mapping, returning a mapping\n result.\n */\n mapResult(pos, assoc = 1) { return this._map(pos, assoc, false); }\n /**\n @internal\n */\n _map(pos, assoc, simple) {\n let delInfo = 0;\n for (let i = this.from; i < this.to; i++) {\n let map = this._maps[i], result = map.mapResult(pos, assoc);\n if (result.recover != null) {\n let corr = this.getMirror(i);\n if (corr != null && corr > i && corr < this.to) {\n i = corr;\n pos = this._maps[corr].recover(result.recover);\n continue;\n }\n }\n delInfo |= result.delInfo;\n pos = result.pos;\n }\n return simple ? pos : new MapResult(pos, delInfo, null);\n }\n}\n\nconst stepsByID = Object.create(null);\n/**\nA step object represents an atomic change. It generally applies\nonly to the document it was created for, since the positions\nstored in it will only make sense for that document.\n\nNew steps are defined by creating classes that extend `Step`,\noverriding the `apply`, `invert`, `map`, `getMap` and `fromJSON`\nmethods, and registering your class with a unique\nJSON-serialization identifier using\n[`Step.jsonID`](https://prosemirror.net/docs/ref/#transform.Step^jsonID).\n*/\nclass Step {\n /**\n Get the step map that represents the changes made by this step,\n and which can be used to transform between positions in the old\n and the new document.\n */\n getMap() { return StepMap.empty; }\n /**\n Try to merge this step with another one, to be applied directly\n after it. Returns the merged step when possible, null if the\n steps can't be merged.\n */\n merge(other) { return null; }\n /**\n Deserialize a step from its JSON representation. Will call\n through to the step class' own implementation of this method.\n */\n static fromJSON(schema, json) {\n if (!json || !json.stepType)\n throw new RangeError(\"Invalid input for Step.fromJSON\");\n let type = stepsByID[json.stepType];\n if (!type)\n throw new RangeError(`No step type ${json.stepType} defined`);\n return type.fromJSON(schema, json);\n }\n /**\n To be able to serialize steps to JSON, each step needs a string\n ID to attach to its JSON representation. Use this method to\n register an ID for your step classes. Try to pick something\n that's unlikely to clash with steps from other modules.\n */\n static jsonID(id, stepClass) {\n if (id in stepsByID)\n throw new RangeError(\"Duplicate use of step JSON ID \" + id);\n stepsByID[id] = stepClass;\n stepClass.prototype.jsonID = id;\n return stepClass;\n }\n}\n/**\nThe result of [applying](https://prosemirror.net/docs/ref/#transform.Step.apply) a step. Contains either a\nnew document or a failure value.\n*/\nclass StepResult {\n /**\n @internal\n */\n constructor(\n /**\n The transformed document, if successful.\n */\n doc, \n /**\n The failure message, if unsuccessful.\n */\n failed) {\n this.doc = doc;\n this.failed = failed;\n }\n /**\n Create a successful step result.\n */\n static ok(doc) { return new StepResult(doc, null); }\n /**\n Create a failed step result.\n */\n static fail(message) { return new StepResult(null, message); }\n /**\n Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given\n arguments. Create a successful result if it succeeds, and a\n failed one if it throws a `ReplaceError`.\n */\n static fromReplace(doc, from, to, slice) {\n try {\n return StepResult.ok(doc.replace(from, to, slice));\n }\n catch (e) {\n if (e instanceof ReplaceError)\n return StepResult.fail(e.message);\n throw e;\n }\n }\n}\n\nfunction mapFragment(fragment, f, parent) {\n let mapped = [];\n for (let i = 0; i < fragment.childCount; i++) {\n let child = fragment.child(i);\n if (child.content.size)\n child = child.copy(mapFragment(child.content, f, child));\n if (child.isInline)\n child = f(child, parent, i);\n mapped.push(child);\n }\n return Fragment.fromArray(mapped);\n}\n/**\nAdd a mark to all inline content between two positions.\n*/\nclass AddMarkStep extends Step {\n /**\n Create a mark step.\n */\n constructor(\n /**\n The start of the marked range.\n */\n from, \n /**\n The end of the marked range.\n */\n to, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to), $from = doc.resolve(this.from);\n let parent = $from.node($from.sharedDepth(this.to));\n let slice = new Slice(mapFragment(oldSlice.content, (node, parent) => {\n if (!node.isAtom || !parent.type.allowsMarkType(this.mark.type))\n return node;\n return node.mark(this.mark.addToSet(node.marks));\n }, parent), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new RemoveMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new AddMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof AddMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"addMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for AddMarkStep.fromJSON\");\n return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addMark\", AddMarkStep);\n/**\nRemove a mark from all inline content between two positions.\n*/\nclass RemoveMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The start of the unmarked range.\n */\n from, \n /**\n The end of the unmarked range.\n */\n to, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.from = from;\n this.to = to;\n this.mark = mark;\n }\n apply(doc) {\n let oldSlice = doc.slice(this.from, this.to);\n let slice = new Slice(mapFragment(oldSlice.content, node => {\n return node.mark(this.mark.removeFromSet(node.marks));\n }, doc), oldSlice.openStart, oldSlice.openEnd);\n return StepResult.fromReplace(doc, this.from, this.to, slice);\n }\n invert() {\n return new AddMarkStep(this.from, this.to, this.mark);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deleted && to.deleted || from.pos >= to.pos)\n return null;\n return new RemoveMarkStep(from.pos, to.pos, this.mark);\n }\n merge(other) {\n if (other instanceof RemoveMarkStep &&\n other.mark.eq(this.mark) &&\n this.from <= other.to && this.to >= other.from)\n return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);\n return null;\n }\n toJSON() {\n return { stepType: \"removeMark\", mark: this.mark.toJSON(),\n from: this.from, to: this.to };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for RemoveMarkStep.fromJSON\");\n return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeMark\", RemoveMarkStep);\n/**\nAdd a mark to a specific node.\n*/\nclass AddNodeMarkStep extends Step {\n /**\n Create a node mark step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to add.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (node) {\n let newSet = this.mark.addToSet(node.marks);\n if (newSet.length == node.marks.length) {\n for (let i = 0; i < node.marks.length; i++)\n if (!node.marks[i].isInSet(newSet))\n return new AddNodeMarkStep(this.pos, node.marks[i]);\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n }\n return new RemoveNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"addNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for AddNodeMarkStep.fromJSON\");\n return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"addNodeMark\", AddNodeMarkStep);\n/**\nRemove a mark from a specific node.\n*/\nclass RemoveNodeMarkStep extends Step {\n /**\n Create a mark-removing step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The mark to remove.\n */\n mark) {\n super();\n this.pos = pos;\n this.mark = mark;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at mark step's position\");\n let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n invert(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node || !this.mark.isInSet(node.marks))\n return this;\n return new AddNodeMarkStep(this.pos, this.mark);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark);\n }\n toJSON() {\n return { stepType: \"removeNodeMark\", pos: this.pos, mark: this.mark.toJSON() };\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\")\n throw new RangeError(\"Invalid input for RemoveNodeMarkStep.fromJSON\");\n return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));\n }\n}\nStep.jsonID(\"removeNodeMark\", RemoveNodeMarkStep);\n\n/**\nReplace a part of the document with a slice of new content.\n*/\nclass ReplaceStep extends Step {\n /**\n The given `slice` should fit the 'gap' between `from` and\n `to`—the depths must line up, and the surrounding nodes must be\n able to be joined with the open sides of the slice. When\n `structure` is true, the step will fail if the content between\n from and to is not just a sequence of closing and then opening\n tokens (this is to guard against rebased replace steps\n overwriting something they weren't supposed to).\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The slice to insert.\n */\n slice, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.slice = slice;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && contentBetween(doc, this.from, this.to))\n return StepResult.fail(\"Structure replace would overwrite content\");\n return StepResult.fromReplace(doc, this.from, this.to, this.slice);\n }\n getMap() {\n return new StepMap([this.from, this.to - this.from, this.slice.size]);\n }\n invert(doc) {\n return new ReplaceStep(this.from, this.from + this.slice.size, doc.slice(this.from, this.to));\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n if (from.deletedAcross && to.deletedAcross)\n return null;\n return new ReplaceStep(from.pos, Math.max(from.pos, to.pos), this.slice, this.structure);\n }\n merge(other) {\n if (!(other instanceof ReplaceStep) || other.structure || this.structure)\n return null;\n if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);\n return new ReplaceStep(this.from, this.to + (other.to - other.from), slice, this.structure);\n }\n else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {\n let slice = this.slice.size + other.slice.size == 0 ? Slice.empty\n : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);\n return new ReplaceStep(other.from, this.to, slice, this.structure);\n }\n else {\n return null;\n }\n }\n toJSON() {\n let json = { stepType: \"replace\", from: this.from, to: this.to };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\")\n throw new RangeError(\"Invalid input for ReplaceStep.fromJSON\");\n return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);\n }\n}\nStep.jsonID(\"replace\", ReplaceStep);\n/**\nReplace a part of the document with a slice of content, but\npreserve a range of the replaced content by moving it into the\nslice.\n*/\nclass ReplaceAroundStep extends Step {\n /**\n Create a replace-around step with the given range and gap.\n `insert` should be the point in the slice into which the content\n of the gap should be moved. `structure` has the same meaning as\n it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.\n */\n constructor(\n /**\n The start position of the replaced range.\n */\n from, \n /**\n The end position of the replaced range.\n */\n to, \n /**\n The start of preserved range.\n */\n gapFrom, \n /**\n The end of preserved range.\n */\n gapTo, \n /**\n The slice to insert.\n */\n slice, \n /**\n The position in the slice where the preserved range should be\n inserted.\n */\n insert, \n /**\n @internal\n */\n structure = false) {\n super();\n this.from = from;\n this.to = to;\n this.gapFrom = gapFrom;\n this.gapTo = gapTo;\n this.slice = slice;\n this.insert = insert;\n this.structure = structure;\n }\n apply(doc) {\n if (this.structure && (contentBetween(doc, this.from, this.gapFrom) ||\n contentBetween(doc, this.gapTo, this.to)))\n return StepResult.fail(\"Structure gap-replace would overwrite content\");\n let gap = doc.slice(this.gapFrom, this.gapTo);\n if (gap.openStart || gap.openEnd)\n return StepResult.fail(\"Gap is not a flat range\");\n let inserted = this.slice.insertAt(this.insert, gap.content);\n if (!inserted)\n return StepResult.fail(\"Content does not fit in gap\");\n return StepResult.fromReplace(doc, this.from, this.to, inserted);\n }\n getMap() {\n return new StepMap([this.from, this.gapFrom - this.from, this.insert,\n this.gapTo, this.to - this.gapTo, this.slice.size - this.insert]);\n }\n invert(doc) {\n let gap = this.gapTo - this.gapFrom;\n return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);\n }\n map(mapping) {\n let from = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);\n let gapFrom = this.from == this.gapFrom ? from.pos : mapping.map(this.gapFrom, -1);\n let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);\n if ((from.deletedAcross && to.deletedAcross) || gapFrom < from.pos || gapTo > to.pos)\n return null;\n return new ReplaceAroundStep(from.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);\n }\n toJSON() {\n let json = { stepType: \"replaceAround\", from: this.from, to: this.to,\n gapFrom: this.gapFrom, gapTo: this.gapTo, insert: this.insert };\n if (this.slice.size)\n json.slice = this.slice.toJSON();\n if (this.structure)\n json.structure = true;\n return json;\n }\n /**\n @internal\n */\n static fromJSON(schema, json) {\n if (typeof json.from != \"number\" || typeof json.to != \"number\" ||\n typeof json.gapFrom != \"number\" || typeof json.gapTo != \"number\" || typeof json.insert != \"number\")\n throw new RangeError(\"Invalid input for ReplaceAroundStep.fromJSON\");\n return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);\n }\n}\nStep.jsonID(\"replaceAround\", ReplaceAroundStep);\nfunction contentBetween(doc, from, to) {\n let $from = doc.resolve(from), dist = to - from, depth = $from.depth;\n while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {\n depth--;\n dist--;\n }\n if (dist > 0) {\n let next = $from.node(depth).maybeChild($from.indexAfter(depth));\n while (dist > 0) {\n if (!next || next.isLeaf)\n return true;\n next = next.firstChild;\n dist--;\n }\n }\n return false;\n}\n\nfunction addMark(tr, from, to, mark) {\n let removed = [], added = [];\n let removing, adding;\n tr.doc.nodesBetween(from, to, (node, pos, parent) => {\n if (!node.isInline)\n return;\n let marks = node.marks;\n if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {\n let start = Math.max(pos, from), end = Math.min(pos + node.nodeSize, to);\n let newSet = mark.addToSet(marks);\n for (let i = 0; i < marks.length; i++) {\n if (!marks[i].isInSet(newSet)) {\n if (removing && removing.to == start && removing.mark.eq(marks[i]))\n removing.to = end;\n else\n removed.push(removing = new RemoveMarkStep(start, end, marks[i]));\n }\n }\n if (adding && adding.to == start)\n adding.to = end;\n else\n added.push(adding = new AddMarkStep(start, end, mark));\n }\n });\n removed.forEach(s => tr.step(s));\n added.forEach(s => tr.step(s));\n}\nfunction removeMark(tr, from, to, mark) {\n let matched = [], step = 0;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isInline)\n return;\n step++;\n let toRemove = null;\n if (mark instanceof MarkType) {\n let set = node.marks, found;\n while (found = mark.isInSet(set)) {\n (toRemove || (toRemove = [])).push(found);\n set = found.removeFromSet(set);\n }\n }\n else if (mark) {\n if (mark.isInSet(node.marks))\n toRemove = [mark];\n }\n else {\n toRemove = node.marks;\n }\n if (toRemove && toRemove.length) {\n let end = Math.min(pos + node.nodeSize, to);\n for (let i = 0; i < toRemove.length; i++) {\n let style = toRemove[i], found;\n for (let j = 0; j < matched.length; j++) {\n let m = matched[j];\n if (m.step == step - 1 && style.eq(matched[j].style))\n found = m;\n }\n if (found) {\n found.to = end;\n found.step = step;\n }\n else {\n matched.push({ style, from: Math.max(pos, from), to: end, step });\n }\n }\n }\n });\n matched.forEach(m => tr.step(new RemoveMarkStep(m.from, m.to, m.style)));\n}\nfunction clearIncompatible(tr, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {\n let node = tr.doc.nodeAt(pos);\n let replSteps = [], cur = pos + 1;\n for (let i = 0; i < node.childCount; i++) {\n let child = node.child(i), end = cur + child.nodeSize;\n let allowed = match.matchType(child.type);\n if (!allowed) {\n replSteps.push(new ReplaceStep(cur, end, Slice.empty));\n }\n else {\n match = allowed;\n for (let j = 0; j < child.marks.length; j++)\n if (!parentType.allowsMarkType(child.marks[j].type))\n tr.step(new RemoveMarkStep(cur, end, child.marks[j]));\n if (clearNewlines && child.isText && parentType.whitespace != \"pre\") {\n let m, newline = /\\r?\\n|\\r/g, slice;\n while (m = newline.exec(child.text)) {\n if (!slice)\n slice = new Slice(Fragment.from(parentType.schema.text(\" \", parentType.allowedMarks(child.marks))), 0, 0);\n replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice));\n }\n }\n }\n cur = end;\n }\n if (!match.validEnd) {\n let fill = match.fillBefore(Fragment.empty, true);\n tr.replace(cur, cur, new Slice(fill, 0, 0));\n }\n for (let i = replSteps.length - 1; i >= 0; i--)\n tr.step(replSteps[i]);\n}\n\nfunction canCut(node, start, end) {\n return (start == 0 || node.canReplace(start, node.childCount)) &&\n (end == node.childCount || node.canReplace(0, end));\n}\n/**\nTry to find a target depth to which the content in the given range\ncan be lifted. Will not go across\n[isolating](https://prosemirror.net/docs/ref/#model.NodeSpec.isolating) parent nodes.\n*/\nfunction liftTarget(range) {\n let parent = range.parent;\n let content = parent.content.cutByIndex(range.startIndex, range.endIndex);\n for (let depth = range.depth, contentBefore = 0, contentAfter = 0;; --depth) {\n let node = range.$from.node(depth);\n let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;\n if (depth < range.depth && node.canReplace(index, endIndex, content))\n return depth;\n if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))\n break;\n if (index)\n contentBefore = 1;\n if (endIndex < node.childCount)\n contentAfter = 1;\n }\n return null;\n}\nfunction lift(tr, range, target) {\n let { $from, $to, depth } = range;\n let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);\n let start = gapStart, end = gapEnd;\n let before = Fragment.empty, openStart = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $from.index(d) > 0) {\n splitting = true;\n before = Fragment.from($from.node(d).copy(before));\n openStart++;\n }\n else {\n start--;\n }\n let after = Fragment.empty, openEnd = 0;\n for (let d = depth, splitting = false; d > target; d--)\n if (splitting || $to.after(d + 1) < $to.end(d)) {\n splitting = true;\n after = Fragment.from($to.node(d).copy(after));\n openEnd++;\n }\n else {\n end++;\n }\n tr.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));\n}\n/**\nTry to find a valid way to wrap the content in the given range in a\nnode of the given type. May introduce extra nodes around and inside\nthe wrapper node, if necessary. Returns null if no valid wrapping\ncould be found. When `innerRange` is given, that range's content is\nused as the content to fit into the wrapping, instead of the\ncontent of `range`.\n*/\nfunction findWrapping(range, nodeType, attrs = null, innerRange = range) {\n let around = findWrappingOutside(range, nodeType);\n let inner = around && findWrappingInside(innerRange, nodeType);\n if (!inner)\n return null;\n return around.map(withAttrs)\n .concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));\n}\nfunction withAttrs(type) { return { type, attrs: null }; }\nfunction findWrappingOutside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let around = parent.contentMatchAt(startIndex).findWrapping(type);\n if (!around)\n return null;\n let outer = around.length ? around[0] : type;\n return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;\n}\nfunction findWrappingInside(range, type) {\n let { parent, startIndex, endIndex } = range;\n let inner = parent.child(startIndex);\n let inside = type.contentMatch.findWrapping(inner.type);\n if (!inside)\n return null;\n let lastType = inside.length ? inside[inside.length - 1] : type;\n let innerMatch = lastType.contentMatch;\n for (let i = startIndex; innerMatch && i < endIndex; i++)\n innerMatch = innerMatch.matchType(parent.child(i).type);\n if (!innerMatch || !innerMatch.validEnd)\n return null;\n return inside;\n}\nfunction wrap(tr, range, wrappers) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--) {\n if (content.size) {\n let match = wrappers[i].type.contentMatch.matchFragment(content);\n if (!match || !match.validEnd)\n throw new RangeError(\"Wrapper type given to Transform.wrap does not form valid content of its parent wrapper\");\n }\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n }\n let start = range.start, end = range.end;\n tr.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));\n}\nfunction setBlockType(tr, from, to, type, attrs) {\n if (!type.isTextblock)\n throw new RangeError(\"Type given to setBlockType should be a textblock\");\n let mapFrom = tr.steps.length;\n tr.doc.nodesBetween(from, to, (node, pos) => {\n let attrsHere = typeof attrs == \"function\" ? attrs(node) : attrs;\n if (node.isTextblock && !node.hasMarkup(type, attrsHere) &&\n canChangeType(tr.doc, tr.mapping.slice(mapFrom).map(pos), type)) {\n let convertNewlines = null;\n if (type.schema.linebreakReplacement) {\n let pre = type.whitespace == \"pre\", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n // Ensure all markup that isn't allowed in the new node type is cleared\n if (convertNewlines === false)\n replaceLinebreaks(tr, node, pos, mapFrom);\n clearIncompatible(tr, tr.mapping.slice(mapFrom).map(pos, 1), type, undefined, convertNewlines === null);\n let mapping = tr.mapping.slice(mapFrom);\n let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);\n tr.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));\n if (convertNewlines === true)\n replaceNewlines(tr, node, pos, mapFrom);\n return false;\n }\n });\n}\nfunction replaceNewlines(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.isText) {\n let m, newline = /\\r?\\n|\\r/g;\n while (m = newline.exec(child.text)) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);\n tr.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());\n }\n }\n });\n}\nfunction replaceLinebreaks(tr, node, pos, mapFrom) {\n node.forEach((child, offset) => {\n if (child.type == child.type.schema.linebreakReplacement) {\n let start = tr.mapping.slice(mapFrom).map(pos + 1 + offset);\n tr.replaceWith(start, start + 1, node.type.schema.text(\"\\n\"));\n }\n });\n}\nfunction canChangeType(doc, pos, type) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return $pos.parent.canReplaceWith(index, index + 1, type);\n}\n/**\nChange the type, attributes, and/or marks of the node at `pos`.\nWhen `type` isn't given, the existing node type is preserved,\n*/\nfunction setNodeMarkup(tr, pos, type, attrs, marks) {\n let node = tr.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at given position\");\n if (!type)\n type = node.type;\n let newNode = type.create(attrs, null, marks || node.marks);\n if (node.isLeaf)\n return tr.replaceWith(pos, pos + node.nodeSize, newNode);\n if (!type.validContent(node.content))\n throw new RangeError(\"Invalid content for node type \" + type.name);\n tr.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));\n}\n/**\nCheck whether splitting at the given position is allowed.\n*/\nfunction canSplit(doc, pos, depth = 1, typesAfter) {\n let $pos = doc.resolve(pos), base = $pos.depth - depth;\n let innerType = (typesAfter && typesAfter[typesAfter.length - 1]) || $pos.parent;\n if (base < 0 || $pos.parent.type.spec.isolating ||\n !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) ||\n !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))\n return false;\n for (let d = $pos.depth - 1, i = depth - 2; d > base; d--, i--) {\n let node = $pos.node(d), index = $pos.index(d);\n if (node.type.spec.isolating)\n return false;\n let rest = node.content.cutByIndex(index, node.childCount);\n let overrideChild = typesAfter && typesAfter[i + 1];\n if (overrideChild)\n rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));\n let after = (typesAfter && typesAfter[i]) || node;\n if (!node.canReplace(index + 1, node.childCount) || !after.type.validContent(rest))\n return false;\n }\n let index = $pos.indexAfter(base);\n let baseType = typesAfter && typesAfter[0];\n return $pos.node(base).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base + 1).type);\n}\nfunction split(tr, pos, depth = 1, typesAfter) {\n let $pos = tr.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;\n for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) {\n before = Fragment.from($pos.node(d).copy(before));\n let typeAfter = typesAfter && typesAfter[i];\n after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));\n }\n tr.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));\n}\n/**\nTest whether the blocks before and after a given position can be\njoined.\n*/\nfunction canJoin(doc, pos) {\n let $pos = doc.resolve(pos), index = $pos.index();\n return joinable($pos.nodeBefore, $pos.nodeAfter) &&\n $pos.parent.canReplace(index, index + 1);\n}\nfunction canAppendWithSubstitutedLinebreaks(a, b) {\n if (!b.content.size)\n a.type.compatibleContent(b.type);\n let match = a.contentMatchAt(a.childCount);\n let { linebreakReplacement } = a.type.schema;\n for (let i = 0; i < b.childCount; i++) {\n let child = b.child(i);\n let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type;\n match = match.matchType(type);\n if (!match)\n return false;\n if (!a.type.allowsMarks(child.marks))\n return false;\n }\n return match.validEnd;\n}\nfunction joinable(a, b) {\n return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b));\n}\n/**\nFind an ancestor of the given position that can be joined to the\nblock before (or after if `dir` is positive). Returns the joinable\npoint, if any.\n*/\nfunction joinPoint(doc, pos, dir = -1) {\n let $pos = doc.resolve(pos);\n for (let d = $pos.depth;; d--) {\n let before, after, index = $pos.index(d);\n if (d == $pos.depth) {\n before = $pos.nodeBefore;\n after = $pos.nodeAfter;\n }\n else if (dir > 0) {\n before = $pos.node(d + 1);\n index++;\n after = $pos.node(d).maybeChild(index);\n }\n else {\n before = $pos.node(d).maybeChild(index - 1);\n after = $pos.node(d + 1);\n }\n if (before && !before.isTextblock && joinable(before, after) &&\n $pos.node(d).canReplace(index, index + 1))\n return pos;\n if (d == 0)\n break;\n pos = dir < 0 ? $pos.before(d) : $pos.after(d);\n }\n}\nfunction join(tr, pos, depth) {\n let convertNewlines = null;\n let { linebreakReplacement } = tr.doc.type.schema;\n let $before = tr.doc.resolve(pos - depth), beforeType = $before.node().type;\n if (linebreakReplacement && beforeType.inlineContent) {\n let pre = beforeType.whitespace == \"pre\";\n let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);\n if (pre && !supportLinebreak)\n convertNewlines = false;\n else if (!pre && supportLinebreak)\n convertNewlines = true;\n }\n let mapFrom = tr.steps.length;\n if (convertNewlines === false) {\n let $after = tr.doc.resolve(pos + depth);\n replaceLinebreaks(tr, $after.node(), $after.before(), mapFrom);\n }\n if (beforeType.inlineContent)\n clearIncompatible(tr, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);\n let mapping = tr.mapping.slice(mapFrom), start = mapping.map(pos - depth);\n tr.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));\n if (convertNewlines === true) {\n let $full = tr.doc.resolve(start);\n replaceNewlines(tr, $full.node(), $full.before(), tr.steps.length);\n }\n return tr;\n}\n/**\nTry to find a point where a node of the given type can be inserted\nnear `pos`, by searching up the node hierarchy when `pos` itself\nisn't a valid place but is at the start or end of a node. Return\nnull if no position was found.\n*/\nfunction insertPoint(doc, pos, nodeType) {\n let $pos = doc.resolve(pos);\n if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))\n return pos;\n if ($pos.parentOffset == 0)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.index(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.before(d + 1);\n if (index > 0)\n return null;\n }\n if ($pos.parentOffset == $pos.parent.content.size)\n for (let d = $pos.depth - 1; d >= 0; d--) {\n let index = $pos.indexAfter(d);\n if ($pos.node(d).canReplaceWith(index, index, nodeType))\n return $pos.after(d + 1);\n if (index < $pos.node(d).childCount)\n return null;\n }\n return null;\n}\n/**\nFinds a position at or around the given position where the given\nslice can be inserted. Will look at parent nodes' nearest boundary\nand try there, even if the original position wasn't directly at the\nstart or end of that node. Returns null when no position was found.\n*/\nfunction dropPoint(doc, pos, slice) {\n let $pos = doc.resolve(pos);\n if (!slice.content.size)\n return pos;\n let content = slice.content;\n for (let i = 0; i < slice.openStart; i++)\n content = content.firstChild.content;\n for (let pass = 1; pass <= (slice.openStart == 0 && slice.size ? 2 : 1); pass++) {\n for (let d = $pos.depth; d >= 0; d--) {\n let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;\n let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);\n let parent = $pos.node(d), fits = false;\n if (pass == 1) {\n fits = parent.canReplace(insertPos, insertPos, content);\n }\n else {\n let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);\n fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);\n }\n if (fits)\n return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);\n }\n }\n return null;\n}\n\n/**\n‘Fit’ a slice into a given position in the document, producing a\n[step](https://prosemirror.net/docs/ref/#transform.Step) that inserts it. Will return null if\nthere's no meaningful way to insert the slice here, or inserting it\nwould be a no-op (an empty slice over an empty range).\n*/\nfunction replaceStep(doc, from, to = from, slice = Slice.empty) {\n if (from == to && !slice.size)\n return null;\n let $from = doc.resolve(from), $to = doc.resolve(to);\n // Optimization -- avoid work if it's obvious that it's not needed.\n if (fitsTrivially($from, $to, slice))\n return new ReplaceStep(from, to, slice);\n return new Fitter($from, $to, slice).fit();\n}\nfunction fitsTrivially($from, $to, slice) {\n return !slice.openStart && !slice.openEnd && $from.start() == $to.start() &&\n $from.parent.canReplace($from.index(), $to.index(), slice.content);\n}\n// Algorithm for 'placing' the elements of a slice into a gap:\n//\n// We consider the content of each node that is open to the left to be\n// independently placeable. I.e. in , when the\n// paragraph on the left is open, \"foo\" can be placed (somewhere on\n// the left side of the replacement gap) independently from p(\"bar\").\n//\n// This class tracks the state of the placement progress in the\n// following properties:\n//\n// - `frontier` holds a stack of `{type, match}` objects that\n// represent the open side of the replacement. It starts at\n// `$from`, then moves forward as content is placed, and is finally\n// reconciled with `$to`.\n//\n// - `unplaced` is a slice that represents the content that hasn't\n// been placed yet.\n//\n// - `placed` is a fragment of placed content. Its open-start value\n// is implicit in `$from`, and its open-end value in `frontier`.\nclass Fitter {\n constructor($from, $to, unplaced) {\n this.$from = $from;\n this.$to = $to;\n this.unplaced = unplaced;\n this.frontier = [];\n this.placed = Fragment.empty;\n for (let i = 0; i <= $from.depth; i++) {\n let node = $from.node(i);\n this.frontier.push({\n type: node.type,\n match: node.contentMatchAt($from.indexAfter(i))\n });\n }\n for (let i = $from.depth; i > 0; i--)\n this.placed = Fragment.from($from.node(i).copy(this.placed));\n }\n get depth() { return this.frontier.length - 1; }\n fit() {\n // As long as there's unplaced content, try to place some of it.\n // If that fails, either increase the open score of the unplaced\n // slice, or drop nodes from it, and then try again.\n while (this.unplaced.size) {\n let fit = this.findFittable();\n if (fit)\n this.placeNodes(fit);\n else\n this.openMore() || this.dropNode();\n }\n // When there's inline content directly after the frontier _and_\n // directly after `this.$to`, we must generate a `ReplaceAround`\n // step that pulls that content into the node after the frontier.\n // That means the fitting must be done to the end of the textblock\n // node after `this.$to`, not `this.$to` itself.\n let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;\n let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));\n if (!$to)\n return null;\n // If closing to `$to` succeeded, create a step\n let content = this.placed, openStart = $from.depth, openEnd = $to.depth;\n while (openStart && openEnd && content.childCount == 1) { // Normalize by dropping open parent nodes\n content = content.firstChild.content;\n openStart--;\n openEnd--;\n }\n let slice = new Slice(content, openStart, openEnd);\n if (moveInline > -1)\n return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice, placedSize);\n if (slice.size || $from.pos != this.$to.pos) // Don't generate no-op steps\n return new ReplaceStep($from.pos, $to.pos, slice);\n return null;\n }\n // Find a position on the start spine of `this.unplaced` that has\n // content that can be moved somewhere on the frontier. Returns two\n // depths, one for the slice and one for the frontier.\n findFittable() {\n let startDepth = this.unplaced.openStart;\n for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {\n let node = cur.firstChild;\n if (cur.childCount > 1)\n openEnd = 0;\n if (node.type.spec.isolating && openEnd <= d) {\n startDepth = d;\n break;\n }\n cur = node.content;\n }\n // Only try wrapping nodes (pass 2) after finding a place without\n // wrapping failed.\n for (let pass = 1; pass <= 2; pass++) {\n for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {\n let fragment, parent = null;\n if (sliceDepth) {\n parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;\n fragment = parent.content;\n }\n else {\n fragment = this.unplaced.content;\n }\n let first = fragment.firstChild;\n for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {\n let { type, match } = this.frontier[frontierDepth], wrap, inject = null;\n // In pass 1, if the next node matches, or there is no next\n // node but the parents look compatible, we've found a\n // place.\n if (pass == 1 && (first ? match.matchType(first.type) || (inject = match.fillBefore(Fragment.from(first), false))\n : parent && type.compatibleContent(parent.type)))\n return { sliceDepth, frontierDepth, parent, inject };\n // In pass 2, look for a set of wrapping nodes that make\n // `first` fit here.\n else if (pass == 2 && first && (wrap = match.findWrapping(first.type)))\n return { sliceDepth, frontierDepth, parent, wrap };\n // Don't continue looking further up if the parent node\n // would fit here.\n if (parent && match.matchType(parent.type))\n break;\n }\n }\n }\n }\n openMore() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (!inner.childCount || inner.firstChild.isLeaf)\n return false;\n this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0));\n return true;\n }\n dropNode() {\n let { content, openStart, openEnd } = this.unplaced;\n let inner = contentAt(content, openStart);\n if (inner.childCount <= 1 && openStart > 0) {\n let openAtEnd = content.size - openStart <= openStart + inner.size;\n this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);\n }\n else {\n this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);\n }\n }\n // Move content from the unplaced slice at `sliceDepth` to the\n // frontier node at `frontierDepth`. Close that frontier node when\n // applicable.\n placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap }) {\n while (this.depth > frontierDepth)\n this.closeFrontierNode();\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n this.openFrontierNode(wrap[i]);\n let slice = this.unplaced, fragment = parent ? parent.content : slice.content;\n let openStart = slice.openStart - sliceDepth;\n let taken = 0, add = [];\n let { match, type } = this.frontier[frontierDepth];\n if (inject) {\n for (let i = 0; i < inject.childCount; i++)\n add.push(inject.child(i));\n match = match.matchFragment(inject);\n }\n // Computes the amount of (end) open nodes at the end of the\n // fragment. When 0, the parent is open, but no more. When\n // negative, nothing is open.\n let openEndCount = (fragment.size + sliceDepth) - (slice.content.size - slice.openEnd);\n // Scan over the fragment, fitting as many child nodes as\n // possible.\n while (taken < fragment.childCount) {\n let next = fragment.child(taken), matches = match.matchType(next.type);\n if (!matches)\n break;\n taken++;\n if (taken > 1 || openStart == 0 || next.content.size) { // Drop empty open nodes\n match = matches;\n add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));\n }\n }\n let toEnd = taken == fragment.childCount;\n if (!toEnd)\n openEndCount = -1;\n this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));\n this.frontier[frontierDepth].match = match;\n // If the parent types match, and the entire node was moved, and\n // it's not open, close this frontier node right away.\n if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)\n this.closeFrontierNode();\n // Add new frontier nodes for any open nodes at the end.\n for (let i = 0, cur = fragment; i < openEndCount; i++) {\n let node = cur.lastChild;\n this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });\n cur = node.content;\n }\n // Update `this.unplaced`. Drop the entire node from which we\n // placed it we got to its end, otherwise just drop the placed\n // nodes.\n this.unplaced = !toEnd ? new Slice(dropFromFragment(slice.content, sliceDepth, taken), slice.openStart, slice.openEnd)\n : sliceDepth == 0 ? Slice.empty\n : new Slice(dropFromFragment(slice.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice.openEnd : sliceDepth - 1);\n }\n mustMoveInline() {\n if (!this.$to.parent.isTextblock)\n return -1;\n let top = this.frontier[this.depth], level;\n if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) ||\n (this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth))\n return -1;\n let { depth } = this.$to, after = this.$to.after(depth);\n while (depth > 1 && after == this.$to.end(--depth))\n ++after;\n return after;\n }\n findCloseLevel($to) {\n scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {\n let { match, type } = this.frontier[i];\n let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));\n let fit = contentAfterFits($to, i, type, match, dropInner);\n if (!fit)\n continue;\n for (let d = i - 1; d >= 0; d--) {\n let { match, type } = this.frontier[d];\n let matches = contentAfterFits($to, d, type, match, true);\n if (!matches || matches.childCount)\n continue scan;\n }\n return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };\n }\n }\n close($to) {\n let close = this.findCloseLevel($to);\n if (!close)\n return null;\n while (this.depth > close.depth)\n this.closeFrontierNode();\n if (close.fit.childCount)\n this.placed = addToFragment(this.placed, close.depth, close.fit);\n $to = close.move;\n for (let d = close.depth + 1; d <= $to.depth; d++) {\n let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d));\n this.openFrontierNode(node.type, node.attrs, add);\n }\n return $to;\n }\n openFrontierNode(type, attrs = null, content) {\n let top = this.frontier[this.depth];\n top.match = top.match.matchType(type);\n this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));\n this.frontier.push({ type, match: type.contentMatch });\n }\n closeFrontierNode() {\n let open = this.frontier.pop();\n let add = open.match.fillBefore(Fragment.empty, true);\n if (add.childCount)\n this.placed = addToFragment(this.placed, this.frontier.length, add);\n }\n}\nfunction dropFromFragment(fragment, depth, count) {\n if (depth == 0)\n return fragment.cutByIndex(count, fragment.childCount);\n return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));\n}\nfunction addToFragment(fragment, depth, content) {\n if (depth == 0)\n return fragment.append(content);\n return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));\n}\nfunction contentAt(fragment, depth) {\n for (let i = 0; i < depth; i++)\n fragment = fragment.firstChild.content;\n return fragment;\n}\nfunction closeNodeStart(node, openStart, openEnd) {\n if (openStart <= 0)\n return node;\n let frag = node.content;\n if (openStart > 1)\n frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));\n if (openStart > 0) {\n frag = node.type.contentMatch.fillBefore(frag).append(frag);\n if (openEnd <= 0)\n frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));\n }\n return node.copy(frag);\n}\nfunction contentAfterFits($to, depth, type, match, open) {\n let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth);\n if (index == node.childCount && !type.compatibleContent(node.type))\n return null;\n let fit = match.fillBefore(node.content, true, index);\n return fit && !invalidMarks(type, node.content, index) ? fit : null;\n}\nfunction invalidMarks(type, fragment, start) {\n for (let i = start; i < fragment.childCount; i++)\n if (!type.allowsMarks(fragment.child(i).marks))\n return true;\n return false;\n}\nfunction definesContent(type) {\n return type.spec.defining || type.spec.definingForContent;\n}\nfunction replaceRange(tr, from, to, slice) {\n if (!slice.size)\n return tr.deleteRange(from, to);\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n if (fitsTrivially($from, $to, slice))\n return tr.step(new ReplaceStep(from, to, slice));\n let targetDepths = coveredDepths($from, $to);\n // Can't replace the whole document, so remove 0 if it's present\n if (targetDepths[targetDepths.length - 1] == 0)\n targetDepths.pop();\n // Negative numbers represent not expansion over the whole node at\n // that depth, but replacing from $from.before(-D) to $to.pos.\n let preferredTarget = -($from.depth + 1);\n targetDepths.unshift(preferredTarget);\n // This loop picks a preferred target depth, if one of the covering\n // depths is not outside of a defining node, and adds negative\n // depths for any depth that has $from at its start and does not\n // cross a defining node.\n for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {\n let spec = $from.node(d).type.spec;\n if (spec.defining || spec.definingAsContext || spec.isolating)\n break;\n if (targetDepths.indexOf(d) > -1)\n preferredTarget = d;\n else if ($from.before(d) == pos)\n targetDepths.splice(1, 0, -d);\n }\n // Try to fit each possible depth of the slice into each possible\n // target depth, starting with the preferred depths.\n let preferredTargetIndex = targetDepths.indexOf(preferredTarget);\n let leftNodes = [], preferredDepth = slice.openStart;\n for (let content = slice.content, i = 0;; i++) {\n let node = content.firstChild;\n leftNodes.push(node);\n if (i == slice.openStart)\n break;\n content = node.content;\n }\n // Back up preferredDepth to cover defining textblocks directly\n // above it, possibly skipping a non-defining textblock.\n for (let d = preferredDepth - 1; d >= 0; d--) {\n let leftNode = leftNodes[d], def = definesContent(leftNode.type);\n if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))\n preferredDepth = d;\n else if (def || !leftNode.type.isTextblock)\n break;\n }\n for (let j = slice.openStart; j >= 0; j--) {\n let openDepth = (j + preferredDepth + 1) % (slice.openStart + 1);\n let insert = leftNodes[openDepth];\n if (!insert)\n continue;\n for (let i = 0; i < targetDepths.length; i++) {\n // Loop over possible expansion levels, starting with the\n // preferred one\n let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;\n if (targetDepth < 0) {\n expand = false;\n targetDepth = -targetDepth;\n }\n let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);\n if (parent.canReplaceWith(index, index, insert.type, insert.marks))\n return tr.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice.content, 0, slice.openStart, openDepth), openDepth, slice.openEnd));\n }\n }\n let startSteps = tr.steps.length;\n for (let i = targetDepths.length - 1; i >= 0; i--) {\n tr.replace(from, to, slice);\n if (tr.steps.length > startSteps)\n break;\n let depth = targetDepths[i];\n if (depth < 0)\n continue;\n from = $from.before(depth);\n to = $to.after(depth);\n }\n}\nfunction closeFragment(fragment, depth, oldOpen, newOpen, parent) {\n if (depth < oldOpen) {\n let first = fragment.firstChild;\n fragment = fragment.replaceChild(0, first.copy(closeFragment(first.content, depth + 1, oldOpen, newOpen, first)));\n }\n if (depth > newOpen) {\n let match = parent.contentMatchAt(0);\n let start = match.fillBefore(fragment).append(fragment);\n fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));\n }\n return fragment;\n}\nfunction replaceRangeWith(tr, from, to, node) {\n if (!node.isInline && from == to && tr.doc.resolve(from).parent.content.size) {\n let point = insertPoint(tr.doc, from, node.type);\n if (point != null)\n from = to = point;\n }\n tr.replaceRange(from, to, new Slice(Fragment.from(node), 0, 0));\n}\nfunction deleteRange(tr, from, to) {\n let $from = tr.doc.resolve(from), $to = tr.doc.resolve(to);\n let covered = coveredDepths($from, $to);\n for (let i = 0; i < covered.length; i++) {\n let depth = covered[i], last = i == covered.length - 1;\n if ((last && depth == 0) || $from.node(depth).type.contentMatch.validEnd)\n return tr.delete($from.start(depth), $to.end(depth));\n if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))\n return tr.delete($from.before(depth), $to.after(depth));\n }\n for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {\n if (from - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d &&\n $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))\n return tr.delete($from.before(d), to);\n }\n tr.delete(from, to);\n}\n// Returns an array of all depths for which $from - $to spans the\n// whole content of the nodes at that depth.\nfunction coveredDepths($from, $to) {\n let result = [], minDepth = Math.min($from.depth, $to.depth);\n for (let d = minDepth; d >= 0; d--) {\n let start = $from.start(d);\n if (start < $from.pos - ($from.depth - d) ||\n $to.end(d) > $to.pos + ($to.depth - d) ||\n $from.node(d).type.spec.isolating ||\n $to.node(d).type.spec.isolating)\n break;\n if (start == $to.start(d) ||\n (d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent &&\n d && $to.start(d - 1) == start - 1))\n result.push(d);\n }\n return result;\n}\n\n/**\nUpdate an attribute in a specific node.\n*/\nclass AttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The position of the target node.\n */\n pos, \n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.pos = pos;\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let node = doc.nodeAt(this.pos);\n if (!node)\n return StepResult.fail(\"No node at attribute step's position\");\n let attrs = Object.create(null);\n for (let name in node.attrs)\n attrs[name] = node.attrs[name];\n attrs[this.attr] = this.value;\n let updated = node.type.create(attrs, null, node.marks);\n return StepResult.fromReplace(doc, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new AttrStep(this.pos, this.attr, doc.nodeAt(this.pos).attrs[this.attr]);\n }\n map(mapping) {\n let pos = mapping.mapResult(this.pos, 1);\n return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value);\n }\n toJSON() {\n return { stepType: \"attr\", pos: this.pos, attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.pos != \"number\" || typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for AttrStep.fromJSON\");\n return new AttrStep(json.pos, json.attr, json.value);\n }\n}\nStep.jsonID(\"attr\", AttrStep);\n/**\nUpdate an attribute in the doc node.\n*/\nclass DocAttrStep extends Step {\n /**\n Construct an attribute step.\n */\n constructor(\n /**\n The attribute to set.\n */\n attr, \n // The attribute's new value.\n value) {\n super();\n this.attr = attr;\n this.value = value;\n }\n apply(doc) {\n let attrs = Object.create(null);\n for (let name in doc.attrs)\n attrs[name] = doc.attrs[name];\n attrs[this.attr] = this.value;\n let updated = doc.type.create(attrs, doc.content, doc.marks);\n return StepResult.ok(updated);\n }\n getMap() {\n return StepMap.empty;\n }\n invert(doc) {\n return new DocAttrStep(this.attr, doc.attrs[this.attr]);\n }\n map(mapping) {\n return this;\n }\n toJSON() {\n return { stepType: \"docAttr\", attr: this.attr, value: this.value };\n }\n static fromJSON(schema, json) {\n if (typeof json.attr != \"string\")\n throw new RangeError(\"Invalid input for DocAttrStep.fromJSON\");\n return new DocAttrStep(json.attr, json.value);\n }\n}\nStep.jsonID(\"docAttr\", DocAttrStep);\n\n/**\n@internal\n*/\nlet TransformError = class extends Error {\n};\nTransformError = function TransformError(message) {\n let err = Error.call(this, message);\n err.__proto__ = TransformError.prototype;\n return err;\n};\nTransformError.prototype = Object.create(Error.prototype);\nTransformError.prototype.constructor = TransformError;\nTransformError.prototype.name = \"TransformError\";\n/**\nAbstraction to build up and track an array of\n[steps](https://prosemirror.net/docs/ref/#transform.Step) representing a document transformation.\n\nMost transforming methods return the `Transform` object itself, so\nthat they can be chained.\n*/\nclass Transform {\n /**\n Create a transform that starts with the given document.\n */\n constructor(\n /**\n The current document (the result of applying the steps in the\n transform).\n */\n doc) {\n this.doc = doc;\n /**\n The steps in this transform.\n */\n this.steps = [];\n /**\n The documents before each of the steps.\n */\n this.docs = [];\n /**\n A mapping with the maps for each of the steps in this transform.\n */\n this.mapping = new Mapping;\n }\n /**\n The starting document.\n */\n get before() { return this.docs.length ? this.docs[0] : this.doc; }\n /**\n Apply a new step in this transform, saving the result. Throws an\n error when the step fails.\n */\n step(step) {\n let result = this.maybeStep(step);\n if (result.failed)\n throw new TransformError(result.failed);\n return this;\n }\n /**\n Try to apply a step in this transformation, ignoring it if it\n fails. Returns the step result.\n */\n maybeStep(step) {\n let result = step.apply(this.doc);\n if (!result.failed)\n this.addStep(step, result.doc);\n return result;\n }\n /**\n True when the document has been changed (when there are any\n steps).\n */\n get docChanged() {\n return this.steps.length > 0;\n }\n /**\n Return a single range, in post-transform document positions,\n that covers all content changed by this transform. Returns null\n if no replacements are made. Note that this will ignore changes\n that add/remove marks without replacing the underlying content.\n */\n changedRange() {\n let from = 1e9, to = -1e9;\n for (let i = 0; i < this.mapping.maps.length; i++) {\n let map = this.mapping.maps[i];\n if (i) {\n from = map.map(from, 1);\n to = map.map(to, -1);\n }\n map.forEach((_f, _t, fromB, toB) => {\n from = Math.min(from, fromB);\n to = Math.max(to, toB);\n });\n }\n return from == 1e9 ? null : { from, to };\n }\n /**\n @internal\n */\n addStep(step, doc) {\n this.docs.push(this.doc);\n this.steps.push(step);\n this.mapping.appendMap(step.getMap());\n this.doc = doc;\n }\n /**\n Replace the part of the document between `from` and `to` with the\n given `slice`.\n */\n replace(from, to = from, slice = Slice.empty) {\n let step = replaceStep(this.doc, from, to, slice);\n if (step)\n this.step(step);\n return this;\n }\n /**\n Replace the given range with the given content, which may be a\n fragment, node, or array of nodes.\n */\n replaceWith(from, to, content) {\n return this.replace(from, to, new Slice(Fragment.from(content), 0, 0));\n }\n /**\n Delete the content between the given positions.\n */\n delete(from, to) {\n return this.replace(from, to, Slice.empty);\n }\n /**\n Insert the given content at the given position.\n */\n insert(pos, content) {\n return this.replaceWith(pos, pos, content);\n }\n /**\n Replace a range of the document with a given slice, using\n `from`, `to`, and the slice's\n [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather\n than fixed start and end points. This method may grow the\n replaced area or close open nodes in the slice in order to get a\n fit that is more in line with WYSIWYG expectations, by dropping\n fully covered parent nodes of the replaced region when they are\n marked [non-defining as\n context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an\n open parent node from the slice that _is_ marked as [defining\n its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n \n This is the method, for example, to handle paste. The similar\n [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more\n primitive tool which will _not_ move the start and end of its given\n range, and is useful in situations where you need more precise\n control over what happens.\n */\n replaceRange(from, to, slice) {\n replaceRange(this, from, to, slice);\n return this;\n }\n /**\n Replace the given range with a node, but use `from` and `to` as\n hints, rather than precise positions. When from and to are the same\n and are at the start or end of a parent node in which the given\n node doesn't fit, this method may _move_ them out towards a parent\n that does allow the given node to be placed. When the given range\n completely covers a parent node, this method may completely replace\n that parent node.\n */\n replaceRangeWith(from, to, node) {\n replaceRangeWith(this, from, to, node);\n return this;\n }\n /**\n Delete the given range, expanding it to cover fully covered\n parent nodes until a valid replace is found.\n */\n deleteRange(from, to) {\n deleteRange(this, from, to);\n return this;\n }\n /**\n Split the content in the given range off from its parent, if there\n is sibling content before or after it, and move it up the tree to\n the depth specified by `target`. You'll probably want to use\n [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make\n sure the lift is valid.\n */\n lift(range, target) {\n lift(this, range, target);\n return this;\n }\n /**\n Join the blocks around the given position. If depth is 2, their\n last and first siblings are also joined, and so on.\n */\n join(pos, depth = 1) {\n join(this, pos, depth);\n return this;\n }\n /**\n Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.\n The wrappers are assumed to be valid in this position, and should\n probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).\n */\n wrap(range, wrappers) {\n wrap(this, range, wrappers);\n return this;\n }\n /**\n Set the type of all textblocks (partly) between `from` and `to` to\n the given node type with the given attributes.\n */\n setBlockType(from, to = from, type, attrs = null) {\n setBlockType(this, from, to, type, attrs);\n return this;\n }\n /**\n Change the type, attributes, and/or marks of the node at `pos`.\n When `type` isn't given, the existing node type is preserved,\n */\n setNodeMarkup(pos, type, attrs = null, marks) {\n setNodeMarkup(this, pos, type, attrs, marks);\n return this;\n }\n /**\n Set a single attribute on a given node to a new value.\n The `pos` addresses the document content. Use `setDocAttribute`\n to set attributes on the document itself.\n */\n setNodeAttribute(pos, attr, value) {\n this.step(new AttrStep(pos, attr, value));\n return this;\n }\n /**\n Set a single attribute on the document to a new value.\n */\n setDocAttribute(attr, value) {\n this.step(new DocAttrStep(attr, value));\n return this;\n }\n /**\n Add a mark to the node at position `pos`.\n */\n addNodeMark(pos, mark) {\n this.step(new AddNodeMarkStep(pos, mark));\n return this;\n }\n /**\n Remove a mark (or all marks of the given type) from the node at\n position `pos`.\n */\n removeNodeMark(pos, mark) {\n let node = this.doc.nodeAt(pos);\n if (!node)\n throw new RangeError(\"No node at position \" + pos);\n if (mark instanceof Mark) {\n if (mark.isInSet(node.marks))\n this.step(new RemoveNodeMarkStep(pos, mark));\n }\n else {\n let set = node.marks, found, steps = [];\n while (found = mark.isInSet(set)) {\n steps.push(new RemoveNodeMarkStep(pos, found));\n set = found.removeFromSet(set);\n }\n for (let i = steps.length - 1; i >= 0; i--)\n this.step(steps[i]);\n }\n return this;\n }\n /**\n Split the node at the given position, and optionally, if `depth` is\n greater than one, any number of nodes above that. By default, the\n parts split off will inherit the node type of the original node.\n This can be changed by passing an array of types and attributes to\n use after the split (with the outermost nodes coming first).\n */\n split(pos, depth = 1, typesAfter) {\n split(this, pos, depth, typesAfter);\n return this;\n }\n /**\n Add the given mark to the inline content between `from` and `to`.\n */\n addMark(from, to, mark) {\n addMark(this, from, to, mark);\n return this;\n }\n /**\n Remove marks from inline nodes between `from` and `to`. When\n `mark` is a single mark, remove precisely that mark. When it is\n a mark type, remove all marks of that type. When it is null,\n remove all marks of any type.\n */\n removeMark(from, to, mark) {\n removeMark(this, from, to, mark);\n return this;\n }\n /**\n Removes all marks and nodes from the content of the node at\n `pos` that don't match the given new parent node type. Accepts\n an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as\n third argument.\n */\n clearIncompatible(pos, parentType, match) {\n clearIncompatible(this, pos, parentType, match);\n return this;\n }\n}\n\nexport { AddMarkStep, AddNodeMarkStep, AttrStep, DocAttrStep, MapResult, Mapping, RemoveMarkStep, RemoveNodeMarkStep, ReplaceAroundStep, ReplaceStep, Step, StepMap, StepResult, Transform, TransformError, canJoin, canSplit, dropPoint, findWrapping, insertPoint, joinPoint, liftTarget, replaceStep };\n", "import { Slice, Fragment, Mark, Node } from 'prosemirror-model';\nimport { ReplaceStep, ReplaceAroundStep, Transform } from 'prosemirror-transform';\n\nconst classesById = Object.create(null);\n/**\nSuperclass for editor selections. Every selection type should\nextend this. Should not be instantiated directly.\n*/\nclass Selection {\n /**\n Initialize a selection with the head and anchor and ranges. If no\n ranges are given, constructs a single range across `$anchor` and\n `$head`.\n */\n constructor(\n /**\n The resolved anchor of the selection (the side that stays in\n place when the selection is modified).\n */\n $anchor, \n /**\n The resolved head of the selection (the side that moves when\n the selection is modified).\n */\n $head, ranges) {\n this.$anchor = $anchor;\n this.$head = $head;\n this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];\n }\n /**\n The selection's anchor, as an unresolved position.\n */\n get anchor() { return this.$anchor.pos; }\n /**\n The selection's head.\n */\n get head() { return this.$head.pos; }\n /**\n The lower bound of the selection's main range.\n */\n get from() { return this.$from.pos; }\n /**\n The upper bound of the selection's main range.\n */\n get to() { return this.$to.pos; }\n /**\n The resolved lower bound of the selection's main range.\n */\n get $from() {\n return this.ranges[0].$from;\n }\n /**\n The resolved upper bound of the selection's main range.\n */\n get $to() {\n return this.ranges[0].$to;\n }\n /**\n Indicates whether the selection contains any content.\n */\n get empty() {\n let ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++)\n if (ranges[i].$from.pos != ranges[i].$to.pos)\n return false;\n return true;\n }\n /**\n Get the content of this selection as a slice.\n */\n content() {\n return this.$from.doc.slice(this.from, this.to, true);\n }\n /**\n Replace the selection with a slice or, if no slice is given,\n delete the selection. Will append to the given transaction.\n */\n replace(tr, content = Slice.empty) {\n // Put the new selection at the position after the inserted\n // content. When that ended in an inline node, search backwards,\n // to get the position after that node. If not, search forward.\n let lastNode = content.content.lastChild, lastParent = null;\n for (let i = 0; i < content.openEnd; i++) {\n lastParent = lastNode;\n lastNode = lastNode.lastChild;\n }\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n tr.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);\n if (i == 0)\n selectionToInsertionEnd(tr, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);\n }\n }\n /**\n Replace the selection with the given node, appending the changes\n to the given transaction.\n */\n replaceWith(tr, node) {\n let mapFrom = tr.steps.length, ranges = this.ranges;\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i], mapping = tr.mapping.slice(mapFrom);\n let from = mapping.map($from.pos), to = mapping.map($to.pos);\n if (i) {\n tr.deleteRange(from, to);\n }\n else {\n tr.replaceRangeWith(from, to, node);\n selectionToInsertionEnd(tr, mapFrom, node.isInline ? -1 : 1);\n }\n }\n }\n /**\n Find a valid cursor or leaf node selection starting at the given\n position and searching back if `dir` is negative, and forward if\n positive. When `textOnly` is true, only consider cursor\n selections. Will return null when no valid selection position is\n found.\n */\n static findFrom($pos, dir, textOnly = false) {\n let inner = $pos.parent.inlineContent ? new TextSelection($pos)\n : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);\n if (inner)\n return inner;\n for (let depth = $pos.depth - 1; depth >= 0; depth--) {\n let found = dir < 0\n ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly)\n : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);\n if (found)\n return found;\n }\n return null;\n }\n /**\n Find a valid cursor or leaf node selection near the given\n position. Searches forward first by default, but if `bias` is\n negative, it will search backwards first.\n */\n static near($pos, bias = 1) {\n return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));\n }\n /**\n Find the cursor or leaf node selection closest to the start of\n the given document. Will return an\n [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position\n exists.\n */\n static atStart(doc) {\n return findSelectionIn(doc, doc, 0, 0, 1) || new AllSelection(doc);\n }\n /**\n Find the cursor or leaf node selection closest to the end of the\n given document.\n */\n static atEnd(doc) {\n return findSelectionIn(doc, doc, doc.content.size, doc.childCount, -1) || new AllSelection(doc);\n }\n /**\n Deserialize the JSON representation of a selection. Must be\n implemented for custom classes (as a static class method).\n */\n static fromJSON(doc, json) {\n if (!json || !json.type)\n throw new RangeError(\"Invalid input for Selection.fromJSON\");\n let cls = classesById[json.type];\n if (!cls)\n throw new RangeError(`No selection type ${json.type} defined`);\n return cls.fromJSON(doc, json);\n }\n /**\n To be able to deserialize selections from JSON, custom selection\n classes must register themselves with an ID string, so that they\n can be disambiguated. Try to pick something that's unlikely to\n clash with classes from other modules.\n */\n static jsonID(id, selectionClass) {\n if (id in classesById)\n throw new RangeError(\"Duplicate use of selection JSON ID \" + id);\n classesById[id] = selectionClass;\n selectionClass.prototype.jsonID = id;\n return selectionClass;\n }\n /**\n Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,\n which is a value that can be mapped without having access to a\n current document, and later resolved to a real selection for a\n given document again. (This is used mostly by the history to\n track and restore old selections.) The default implementation of\n this method just converts the selection to a text selection and\n returns the bookmark for that.\n */\n getBookmark() {\n return TextSelection.between(this.$anchor, this.$head).getBookmark();\n }\n}\nSelection.prototype.visible = true;\n/**\nRepresents a selected range in a document.\n*/\nclass SelectionRange {\n /**\n Create a range.\n */\n constructor(\n /**\n The lower bound of the range.\n */\n $from, \n /**\n The upper bound of the range.\n */\n $to) {\n this.$from = $from;\n this.$to = $to;\n }\n}\nlet warnedAboutTextSelection = false;\nfunction checkTextSelection($pos) {\n if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {\n warnedAboutTextSelection = true;\n console[\"warn\"](\"TextSelection endpoint not pointing into a node with inline content (\" + $pos.parent.type.name + \")\");\n }\n}\n/**\nA text selection represents a classical editor selection, with a\nhead (the moving side) and anchor (immobile side), both of which\npoint into textblock nodes. It can be empty (a regular cursor\nposition).\n*/\nclass TextSelection extends Selection {\n /**\n Construct a text selection between the given points.\n */\n constructor($anchor, $head = $anchor) {\n checkTextSelection($anchor);\n checkTextSelection($head);\n super($anchor, $head);\n }\n /**\n Returns a resolved position if this is a cursor selection (an\n empty text selection), and null otherwise.\n */\n get $cursor() { return this.$anchor.pos == this.$head.pos ? this.$head : null; }\n map(doc, mapping) {\n let $head = doc.resolve(mapping.map(this.head));\n if (!$head.parent.inlineContent)\n return Selection.near($head);\n let $anchor = doc.resolve(mapping.map(this.anchor));\n return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);\n }\n replace(tr, content = Slice.empty) {\n super.replace(tr, content);\n if (content == Slice.empty) {\n let marks = this.$from.marksAcross(this.$to);\n if (marks)\n tr.ensureMarks(marks);\n }\n }\n eq(other) {\n return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head;\n }\n getBookmark() {\n return new TextBookmark(this.anchor, this.head);\n }\n toJSON() {\n return { type: \"text\", anchor: this.anchor, head: this.head };\n }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid input for TextSelection.fromJSON\");\n return new TextSelection(doc.resolve(json.anchor), doc.resolve(json.head));\n }\n /**\n Create a text selection from non-resolved positions.\n */\n static create(doc, anchor, head = anchor) {\n let $anchor = doc.resolve(anchor);\n return new this($anchor, head == anchor ? $anchor : doc.resolve(head));\n }\n /**\n Return a text selection that spans the given positions or, if\n they aren't text positions, find a text selection near them.\n `bias` determines whether the method searches forward (default)\n or backwards (negative number) first. Will fall back to calling\n [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document\n doesn't contain a valid text position.\n */\n static between($anchor, $head, bias) {\n let dPos = $anchor.pos - $head.pos;\n if (!bias || dPos)\n bias = dPos >= 0 ? 1 : -1;\n if (!$head.parent.inlineContent) {\n let found = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);\n if (found)\n $head = found.$head;\n else\n return Selection.near($head, bias);\n }\n if (!$anchor.parent.inlineContent) {\n if (dPos == 0) {\n $anchor = $head;\n }\n else {\n $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;\n if (($anchor.pos < $head.pos) != (dPos < 0))\n $anchor = $head;\n }\n }\n return new TextSelection($anchor, $head);\n }\n}\nSelection.jsonID(\"text\", TextSelection);\nclass TextBookmark {\n constructor(anchor, head) {\n this.anchor = anchor;\n this.head = head;\n }\n map(mapping) {\n return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head));\n }\n resolve(doc) {\n return TextSelection.between(doc.resolve(this.anchor), doc.resolve(this.head));\n }\n}\n/**\nA node selection is a selection that points at a single node. All\nnodes marked [selectable](https://prosemirror.net/docs/ref/#model.NodeSpec.selectable) can be the\ntarget of a node selection. In such a selection, `from` and `to`\npoint directly before and after the selected node, `anchor` equals\n`from`, and `head` equals `to`..\n*/\nclass NodeSelection extends Selection {\n /**\n Create a node selection. Does not verify the validity of its\n argument.\n */\n constructor($pos) {\n let node = $pos.nodeAfter;\n let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);\n super($pos, $end);\n this.node = node;\n }\n map(doc, mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n let $pos = doc.resolve(pos);\n if (deleted)\n return Selection.near($pos);\n return new NodeSelection($pos);\n }\n content() {\n return new Slice(Fragment.from(this.node), 0, 0);\n }\n eq(other) {\n return other instanceof NodeSelection && other.anchor == this.anchor;\n }\n toJSON() {\n return { type: \"node\", anchor: this.anchor };\n }\n getBookmark() { return new NodeBookmark(this.anchor); }\n /**\n @internal\n */\n static fromJSON(doc, json) {\n if (typeof json.anchor != \"number\")\n throw new RangeError(\"Invalid input for NodeSelection.fromJSON\");\n return new NodeSelection(doc.resolve(json.anchor));\n }\n /**\n Create a node selection from non-resolved positions.\n */\n static create(doc, from) {\n return new NodeSelection(doc.resolve(from));\n }\n /**\n Determines whether the given node may be selected as a node\n selection.\n */\n static isSelectable(node) {\n return !node.isText && node.type.spec.selectable !== false;\n }\n}\nNodeSelection.prototype.visible = false;\nSelection.jsonID(\"node\", NodeSelection);\nclass NodeBookmark {\n constructor(anchor) {\n this.anchor = anchor;\n }\n map(mapping) {\n let { deleted, pos } = mapping.mapResult(this.anchor);\n return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos);\n }\n resolve(doc) {\n let $pos = doc.resolve(this.anchor), node = $pos.nodeAfter;\n if (node && NodeSelection.isSelectable(node))\n return new NodeSelection($pos);\n return Selection.near($pos);\n }\n}\n/**\nA selection type that represents selecting the whole document\n(which can not necessarily be expressed with a text selection, when\nthere are for example leaf block nodes at the start or end of the\ndocument).\n*/\nclass AllSelection extends Selection {\n /**\n Create an all-selection over the given document.\n */\n constructor(doc) {\n super(doc.resolve(0), doc.resolve(doc.content.size));\n }\n replace(tr, content = Slice.empty) {\n if (content == Slice.empty) {\n tr.delete(0, tr.doc.content.size);\n let sel = Selection.atStart(tr.doc);\n if (!sel.eq(tr.selection))\n tr.setSelection(sel);\n }\n else {\n super.replace(tr, content);\n }\n }\n toJSON() { return { type: \"all\" }; }\n /**\n @internal\n */\n static fromJSON(doc) { return new AllSelection(doc); }\n map(doc) { return new AllSelection(doc); }\n eq(other) { return other instanceof AllSelection; }\n getBookmark() { return AllBookmark; }\n}\nSelection.jsonID(\"all\", AllSelection);\nconst AllBookmark = {\n map() { return this; },\n resolve(doc) { return new AllSelection(doc); }\n};\n// FIXME we'll need some awareness of text direction when scanning for selections\n// Try to find a selection inside the given node. `pos` points at the\n// position where the search starts. When `text` is true, only return\n// text selections.\nfunction findSelectionIn(doc, node, pos, index, dir, text = false) {\n if (node.inlineContent)\n return TextSelection.create(doc, pos);\n for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n let child = node.child(i);\n if (!child.isAtom) {\n let inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n if (inner)\n return inner;\n }\n else if (!text && NodeSelection.isSelectable(child)) {\n return NodeSelection.create(doc, pos - (dir < 0 ? child.nodeSize : 0));\n }\n pos += child.nodeSize * dir;\n }\n return null;\n}\nfunction selectionToInsertionEnd(tr, startLen, bias) {\n let last = tr.steps.length - 1;\n if (last < startLen)\n return;\n let step = tr.steps[last];\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))\n return;\n let map = tr.mapping.maps[last], end;\n map.forEach((_from, _to, _newFrom, newTo) => { if (end == null)\n end = newTo; });\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias));\n}\n\nconst UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4;\n/**\nAn editor state transaction, which can be applied to a state to\ncreate an updated state. Use\n[`EditorState.tr`](https://prosemirror.net/docs/ref/#state.EditorState.tr) to create an instance.\n\nTransactions track changes to the document (they are a subclass of\n[`Transform`](https://prosemirror.net/docs/ref/#transform.Transform)), but also other state changes,\nlike selection updates and adjustments of the set of [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks). In addition, you can store\nmetadata properties in a transaction, which are extra pieces of\ninformation that client code or plugins can use to describe what a\ntransaction represents, so that they can update their [own\nstate](https://prosemirror.net/docs/ref/#state.StateField) accordingly.\n\nThe [editor view](https://prosemirror.net/docs/ref/#view.EditorView) uses a few metadata\nproperties: it will attach a property `\"pointer\"` with the value\n`true` to selection transactions directly caused by mouse or touch\ninput, a `\"composition\"` property holding an ID identifying the\ncomposition that caused it to transactions caused by composed DOM\ninput, and a `\"uiEvent\"` property of that may be `\"paste\"`,\n`\"cut\"`, or `\"drop\"`.\n*/\nclass Transaction extends Transform {\n /**\n @internal\n */\n constructor(state) {\n super(state.doc);\n // The step count for which the current selection is valid.\n this.curSelectionFor = 0;\n // Bitfield to track which aspects of the state were updated by\n // this transaction.\n this.updated = 0;\n // Object used to store metadata properties for the transaction.\n this.meta = Object.create(null);\n this.time = Date.now();\n this.curSelection = state.selection;\n this.storedMarks = state.storedMarks;\n }\n /**\n The transaction's current selection. This defaults to the editor\n selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the\n transaction, but can be overwritten with\n [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).\n */\n get selection() {\n if (this.curSelectionFor < this.steps.length) {\n this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));\n this.curSelectionFor = this.steps.length;\n }\n return this.curSelection;\n }\n /**\n Update the transaction's current selection. Will determine the\n selection that the editor gets when the transaction is applied.\n */\n setSelection(selection) {\n if (selection.$from.doc != this.doc)\n throw new RangeError(\"Selection passed to setSelection must point at the current document\");\n this.curSelection = selection;\n this.curSelectionFor = this.steps.length;\n this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;\n this.storedMarks = null;\n return this;\n }\n /**\n Whether the selection was explicitly updated by this transaction.\n */\n get selectionSet() {\n return (this.updated & UPDATED_SEL) > 0;\n }\n /**\n Set the current stored marks.\n */\n setStoredMarks(marks) {\n this.storedMarks = marks;\n this.updated |= UPDATED_MARKS;\n return this;\n }\n /**\n Make sure the current stored marks or, if that is null, the marks\n at the selection, match the given set of marks. Does nothing if\n this is already the case.\n */\n ensureMarks(marks) {\n if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))\n this.setStoredMarks(marks);\n return this;\n }\n /**\n Add a mark to the set of stored marks.\n */\n addStoredMark(mark) {\n return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Remove a mark or mark type from the set of stored marks.\n */\n removeStoredMark(mark) {\n return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));\n }\n /**\n Whether the stored marks were explicitly set for this transaction.\n */\n get storedMarksSet() {\n return (this.updated & UPDATED_MARKS) > 0;\n }\n /**\n @internal\n */\n addStep(step, doc) {\n super.addStep(step, doc);\n this.updated = this.updated & ~UPDATED_MARKS;\n this.storedMarks = null;\n }\n /**\n Update the timestamp for the transaction.\n */\n setTime(time) {\n this.time = time;\n return this;\n }\n /**\n Replace the current selection with the given slice.\n */\n replaceSelection(slice) {\n this.selection.replace(this, slice);\n return this;\n }\n /**\n Replace the selection with the given node. When `inheritMarks` is\n true and the content is inline, it inherits the marks from the\n place where it is inserted.\n */\n replaceSelectionWith(node, inheritMarks = true) {\n let selection = this.selection;\n if (inheritMarks)\n node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : (selection.$from.marksAcross(selection.$to) || Mark.none)));\n selection.replaceWith(this, node);\n return this;\n }\n /**\n Delete the selection.\n */\n deleteSelection() {\n this.selection.replace(this);\n return this;\n }\n /**\n Replace the given range, or the selection if no range is given,\n with a text node containing the given string.\n */\n insertText(text, from, to) {\n let schema = this.doc.type.schema;\n if (from == null) {\n if (!text)\n return this.deleteSelection();\n return this.replaceSelectionWith(schema.text(text), true);\n }\n else {\n if (to == null)\n to = from;\n if (!text)\n return this.deleteRange(from, to);\n let marks = this.storedMarks;\n if (!marks) {\n let $from = this.doc.resolve(from);\n marks = to == from ? $from.marks() : $from.marksAcross(this.doc.resolve(to));\n }\n this.replaceRangeWith(from, to, schema.text(text, marks));\n if (!this.selection.empty && this.selection.to == from + text.length)\n this.setSelection(Selection.near(this.selection.$to));\n return this;\n }\n }\n /**\n Store a metadata property in this transaction, keyed either by\n name or by plugin.\n */\n setMeta(key, value) {\n this.meta[typeof key == \"string\" ? key : key.key] = value;\n return this;\n }\n /**\n Retrieve a metadata property for a given name or plugin.\n */\n getMeta(key) {\n return this.meta[typeof key == \"string\" ? key : key.key];\n }\n /**\n Returns true if this transaction doesn't contain any metadata,\n and can thus safely be extended.\n */\n get isGeneric() {\n for (let _ in this.meta)\n return false;\n return true;\n }\n /**\n Indicate that the editor should scroll the selection into view\n when updated to the state produced by this transaction.\n */\n scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }\n /**\n True when this transaction has had `scrollIntoView` called on it.\n */\n get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }\n}\n\nfunction bind(f, self) {\n return !self || !f ? f : f.bind(self);\n}\nclass FieldDesc {\n constructor(name, desc, self) {\n this.name = name;\n this.init = bind(desc.init, self);\n this.apply = bind(desc.apply, self);\n }\n}\nconst baseFields = [\n new FieldDesc(\"doc\", {\n init(config) { return config.doc || config.schema.topNodeType.createAndFill(); },\n apply(tr) { return tr.doc; }\n }),\n new FieldDesc(\"selection\", {\n init(config, instance) { return config.selection || Selection.atStart(instance.doc); },\n apply(tr) { return tr.selection; }\n }),\n new FieldDesc(\"storedMarks\", {\n init(config) { return config.storedMarks || null; },\n apply(tr, _marks, _old, state) { return state.selection.$cursor ? tr.storedMarks : null; }\n }),\n new FieldDesc(\"scrollToSelection\", {\n init() { return 0; },\n apply(tr, prev) { return tr.scrolledIntoView ? prev + 1 : prev; }\n })\n];\n// Object wrapping the part of a state object that stays the same\n// across transactions. Stored in the state's `config` property.\nclass Configuration {\n constructor(schema, plugins) {\n this.schema = schema;\n this.plugins = [];\n this.pluginsByKey = Object.create(null);\n this.fields = baseFields.slice();\n if (plugins)\n plugins.forEach(plugin => {\n if (this.pluginsByKey[plugin.key])\n throw new RangeError(\"Adding different instances of a keyed plugin (\" + plugin.key + \")\");\n this.plugins.push(plugin);\n this.pluginsByKey[plugin.key] = plugin;\n if (plugin.spec.state)\n this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));\n });\n }\n}\n/**\nThe state of a ProseMirror editor is represented by an object of\nthis type. A state is a persistent data structure—it isn't\nupdated, but rather a new state value is computed from an old one\nusing the [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) method.\n\nA state holds a number of built-in fields, and plugins can\n[define](https://prosemirror.net/docs/ref/#state.PluginSpec.state) additional fields.\n*/\nclass EditorState {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n config) {\n this.config = config;\n }\n /**\n The schema of the state's document.\n */\n get schema() {\n return this.config.schema;\n }\n /**\n The plugins that are active in this state.\n */\n get plugins() {\n return this.config.plugins;\n }\n /**\n Apply the given transaction to produce a new state.\n */\n apply(tr) {\n return this.applyTransaction(tr).state;\n }\n /**\n @internal\n */\n filterTransaction(tr, ignore = -1) {\n for (let i = 0; i < this.config.plugins.length; i++)\n if (i != ignore) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr, this))\n return false;\n }\n return true;\n }\n /**\n Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that\n returns the precise transactions that were applied (which might\n be influenced by the [transaction\n hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of\n plugins) along with the new state.\n */\n applyTransaction(rootTr) {\n if (!this.filterTransaction(rootTr))\n return { state: this, transactions: [] };\n let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;\n // This loop repeatedly gives plugins a chance to respond to\n // transactions as new transactions are added, making sure to only\n // pass the transactions the plugin did not see before.\n for (;;) {\n let haveNew = false;\n for (let i = 0; i < this.config.plugins.length; i++) {\n let plugin = this.config.plugins[i];\n if (plugin.spec.appendTransaction) {\n let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;\n let tr = n < trs.length &&\n plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);\n if (tr && newState.filterTransaction(tr, i)) {\n tr.setMeta(\"appendedTransaction\", rootTr);\n if (!seen) {\n seen = [];\n for (let j = 0; j < this.config.plugins.length; j++)\n seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });\n }\n trs.push(tr);\n newState = newState.applyInner(tr);\n haveNew = true;\n }\n if (seen)\n seen[i] = { state: newState, n: trs.length };\n }\n }\n if (!haveNew)\n return { state: newState, transactions: trs };\n }\n }\n /**\n @internal\n */\n applyInner(tr) {\n if (!tr.before.eq(this.doc))\n throw new RangeError(\"Applying a mismatched transaction\");\n let newInstance = new EditorState(this.config), fields = this.config.fields;\n for (let i = 0; i < fields.length; i++) {\n let field = fields[i];\n newInstance[field.name] = field.apply(tr, this[field.name], this, newInstance);\n }\n return newInstance;\n }\n /**\n Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.\n */\n get tr() { return new Transaction(this); }\n /**\n Create a new state.\n */\n static create(config) {\n let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);\n let instance = new EditorState($config);\n for (let i = 0; i < $config.fields.length; i++)\n instance[$config.fields[i].name] = $config.fields[i].init(config, instance);\n return instance;\n }\n /**\n Create a new state based on this one, but with an adjusted set\n of active plugins. State fields that exist in both sets of\n plugins are kept unchanged. Those that no longer exist are\n dropped, and those that are new are initialized using their\n [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new\n configuration object..\n */\n reconfigure(config) {\n let $config = new Configuration(this.schema, config.plugins);\n let fields = $config.fields, instance = new EditorState($config);\n for (let i = 0; i < fields.length; i++) {\n let name = fields[i].name;\n instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);\n }\n return instance;\n }\n /**\n Serialize this state to JSON. If you want to serialize the state\n of plugins, pass an object mapping property names to use in the\n resulting JSON object to plugin objects. The argument may also be\n a string or number, in which case it is ignored, to support the\n way `JSON.stringify` calls `toString` methods.\n */\n toJSON(pluginFields) {\n let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };\n if (this.storedMarks)\n result.storedMarks = this.storedMarks.map(m => m.toJSON());\n if (pluginFields && typeof pluginFields == 'object')\n for (let prop in pluginFields) {\n if (prop == \"doc\" || prop == \"selection\")\n throw new RangeError(\"The JSON fields `doc` and `selection` are reserved\");\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (state && state.toJSON)\n result[prop] = state.toJSON.call(plugin, this[plugin.key]);\n }\n return result;\n }\n /**\n Deserialize a JSON representation of a state. `config` should\n have at least a `schema` field, and should contain array of\n plugins to initialize the state with. `pluginFields` can be used\n to deserialize the state of plugins, by associating plugin\n instances with the property names they use in the JSON object.\n */\n static fromJSON(config, json, pluginFields) {\n if (!json)\n throw new RangeError(\"Invalid input for EditorState.fromJSON\");\n if (!config.schema)\n throw new RangeError(\"Required config field 'schema' missing\");\n let $config = new Configuration(config.schema, config.plugins);\n let instance = new EditorState($config);\n $config.fields.forEach(field => {\n if (field.name == \"doc\") {\n instance.doc = Node.fromJSON(config.schema, json.doc);\n }\n else if (field.name == \"selection\") {\n instance.selection = Selection.fromJSON(instance.doc, json.selection);\n }\n else if (field.name == \"storedMarks\") {\n if (json.storedMarks)\n instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);\n }\n else {\n if (pluginFields)\n for (let prop in pluginFields) {\n let plugin = pluginFields[prop], state = plugin.spec.state;\n if (plugin.key == field.name && state && state.fromJSON &&\n Object.prototype.hasOwnProperty.call(json, prop)) {\n instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);\n return;\n }\n }\n instance[field.name] = field.init(config, instance);\n }\n });\n return instance;\n }\n}\n\nfunction bindProps(obj, self, target) {\n for (let prop in obj) {\n let val = obj[prop];\n if (val instanceof Function)\n val = val.bind(self);\n else if (prop == \"handleDOMEvents\")\n val = bindProps(val, self, {});\n target[prop] = val;\n }\n return target;\n}\n/**\nPlugins bundle functionality that can be added to an editor.\nThey are part of the [editor state](https://prosemirror.net/docs/ref/#state.EditorState) and\nmay influence that state and the view that contains it.\n*/\nclass Plugin {\n /**\n Create a plugin.\n */\n constructor(\n /**\n The plugin's [spec object](https://prosemirror.net/docs/ref/#state.PluginSpec).\n */\n spec) {\n this.spec = spec;\n /**\n The [props](https://prosemirror.net/docs/ref/#view.EditorProps) exported by this plugin.\n */\n this.props = {};\n if (spec.props)\n bindProps(spec.props, this, this.props);\n this.key = spec.key ? spec.key.key : createKey(\"plugin\");\n }\n /**\n Extract the plugin's state field from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\nconst keys = Object.create(null);\nfunction createKey(name) {\n if (name in keys)\n return name + \"$\" + ++keys[name];\n keys[name] = 0;\n return name + \"$\";\n}\n/**\nA key is used to [tag](https://prosemirror.net/docs/ref/#state.PluginSpec.key) plugins in a way\nthat makes it possible to find them, given an editor state.\nAssigning a key does mean only one plugin of that type can be\nactive in a state.\n*/\nclass PluginKey {\n /**\n Create a plugin key.\n */\n constructor(name = \"key\") { this.key = createKey(name); }\n /**\n Get the active plugin with this key, if any, from an editor\n state.\n */\n get(state) { return state.config.pluginsByKey[this.key]; }\n /**\n Get the plugin's state from an editor state.\n */\n getState(state) { return state[this.key]; }\n}\n\nexport { AllSelection, EditorState, NodeSelection, Plugin, PluginKey, Selection, SelectionRange, TextSelection, Transaction };\n", "import { liftTarget, replaceStep, ReplaceStep, canJoin, joinPoint, canSplit, ReplaceAroundStep, findWrapping } from 'prosemirror-transform';\nimport { Slice, Fragment } from 'prosemirror-model';\nimport { NodeSelection, Selection, TextSelection, AllSelection, SelectionRange } from 'prosemirror-state';\n\n/**\nDelete the selection, if there is one.\n*/\nconst deleteSelection = (state, dispatch) => {\n if (state.selection.empty)\n return false;\n if (dispatch)\n dispatch(state.tr.deleteSelection().scrollIntoView());\n return true;\n};\nfunction atBlockStart(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"backward\", state)\n : $cursor.parentOffset > 0))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and at the start of a textblock, try to\nreduce the distance between that block and the one before it—if\nthere's a block directly before it that can be joined, join them.\nIf not, try to move the selected block closer to the next one in\nthe document structure by lifting it out of its parent or moving it\ninto a parent of the previous block. Will use the view for accurate\n(bidi-aware) start-of-textblock detection if given.\n*/\nconst joinBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n // If there is no node before this, try to lift\n if (!$cut) {\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n let before = $cut.nodeBefore;\n // Apply the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, -1))\n return true;\n // If the node below has no content and the node above is\n // selectable, delete the node below and select the one above.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(before, \"end\") || NodeSelection.isSelectable(before))) {\n for (let depth = $cursor.depth;; depth--) {\n let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(before, \"end\")\n ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos, -1)), -1)\n : NodeSelection.create(tr.doc, $cut.pos - before.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n if (depth == 1 || $cursor.node(depth - 1).childCount > 1)\n break;\n }\n }\n // If the node before is an atom, delete it\n if (before.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nA more limited form of [`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward)\nthat only tries to join the current textblock to the one before\nit, if the cursor is at the start of a textblock.\n*/\nconst joinTextblockBackward = (state, dispatch, view) => {\n let $cursor = atBlockStart(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutBefore($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\n/**\nA more limited form of [`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward)\nthat only tries to join the current textblock to the one after\nit, if the cursor is at the end of a textblock.\n*/\nconst joinTextblockForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;\n};\nfunction joinTextblocksAround(state, $cut, dispatch) {\n let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;\n for (; !beforeText.isTextblock; beforePos--) {\n if (beforeText.type.spec.isolating)\n return false;\n let child = beforeText.lastChild;\n if (!child)\n return false;\n beforeText = child;\n }\n let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;\n for (; !afterText.isTextblock; afterPos++) {\n if (afterText.type.spec.isolating)\n return false;\n let child = afterText.firstChild;\n if (!child)\n return false;\n afterText = child;\n }\n let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);\n if (!step || step.from != beforePos ||\n step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)\n return false;\n if (dispatch) {\n let tr = state.tr.step(step);\n tr.setSelection(TextSelection.create(tr.doc, beforePos));\n dispatch(tr.scrollIntoView());\n }\n return true;\n}\nfunction textblockAt(node, side, only = false) {\n for (let scan = node; scan; scan = (side == \"start\" ? scan.firstChild : scan.lastChild)) {\n if (scan.isTextblock)\n return true;\n if (only && scan.childCount != 1)\n return false;\n }\n return false;\n}\n/**\nWhen the selection is empty and at the start of a textblock, select\nthe node before that textblock, if possible. This is intended to be\nbound to keys like backspace, after\n[`joinBackward`](https://prosemirror.net/docs/ref/#commands.joinBackward) or other deleting\ncommands, as a fall-back behavior when the schema doesn't allow\ndeletion at the selected point.\n*/\nconst selectNodeBackward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"backward\", state) : $head.parentOffset > 0)\n return false;\n $cut = findCutBefore($head);\n }\n let node = $cut && $cut.nodeBefore;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());\n return true;\n};\nfunction findCutBefore($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n if ($pos.index(i) > 0)\n return $pos.doc.resolve($pos.before(i + 1));\n if ($pos.node(i).type.spec.isolating)\n break;\n }\n return null;\n}\nfunction atBlockEnd(state, view) {\n let { $cursor } = state.selection;\n if (!$cursor || (view ? !view.endOfTextblock(\"forward\", state)\n : $cursor.parentOffset < $cursor.parent.content.size))\n return null;\n return $cursor;\n}\n/**\nIf the selection is empty and the cursor is at the end of a\ntextblock, try to reduce or remove the boundary between that block\nand the one after it, either by joining them or by moving the other\nblock closer to this one in the tree structure. Will use the view\nfor accurate start-of-textblock detection if given.\n*/\nconst joinForward = (state, dispatch, view) => {\n let $cursor = atBlockEnd(state, view);\n if (!$cursor)\n return false;\n let $cut = findCutAfter($cursor);\n // If there is no node after this, there's nothing to do\n if (!$cut)\n return false;\n let after = $cut.nodeAfter;\n // Try the joining algorithm\n if (deleteBarrier(state, $cut, dispatch, 1))\n return true;\n // If the node above has no content and the node below is\n // selectable, delete the node above and select the one below.\n if ($cursor.parent.content.size == 0 &&\n (textblockAt(after, \"start\") || NodeSelection.isSelectable(after))) {\n let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);\n if (delStep && delStep.slice.size < delStep.to - delStep.from) {\n if (dispatch) {\n let tr = state.tr.step(delStep);\n tr.setSelection(textblockAt(after, \"start\") ? Selection.findFrom(tr.doc.resolve(tr.mapping.map($cut.pos)), 1)\n : NodeSelection.create(tr.doc, tr.mapping.map($cut.pos)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n // If the next node is an atom, delete it\n if (after.isAtom && $cut.depth == $cursor.depth - 1) {\n if (dispatch)\n dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());\n return true;\n }\n return false;\n};\n/**\nWhen the selection is empty and at the end of a textblock, select\nthe node coming after that textblock, if possible. This is intended\nto be bound to keys like delete, after\n[`joinForward`](https://prosemirror.net/docs/ref/#commands.joinForward) and similar deleting\ncommands, to provide a fall-back behavior when the schema doesn't\nallow deletion at the selected point.\n*/\nconst selectNodeForward = (state, dispatch, view) => {\n let { $head, empty } = state.selection, $cut = $head;\n if (!empty)\n return false;\n if ($head.parent.isTextblock) {\n if (view ? !view.endOfTextblock(\"forward\", state) : $head.parentOffset < $head.parent.content.size)\n return false;\n $cut = findCutAfter($head);\n }\n let node = $cut && $cut.nodeAfter;\n if (!node || !NodeSelection.isSelectable(node))\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());\n return true;\n};\nfunction findCutAfter($pos) {\n if (!$pos.parent.type.spec.isolating)\n for (let i = $pos.depth - 1; i >= 0; i--) {\n let parent = $pos.node(i);\n if ($pos.index(i) + 1 < parent.childCount)\n return $pos.doc.resolve($pos.after(i + 1));\n if (parent.type.spec.isolating)\n break;\n }\n return null;\n}\n/**\nJoin the selected block or, if there is a text selection, the\nclosest ancestor block of the selection that can be joined, with\nthe sibling above it.\n*/\nconst joinUp = (state, dispatch) => {\n let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;\n if (nodeSel) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.from))\n return false;\n point = sel.from;\n }\n else {\n point = joinPoint(state.doc, sel.from, -1);\n if (point == null)\n return false;\n }\n if (dispatch) {\n let tr = state.tr.join(point);\n if (nodeSel)\n tr.setSelection(NodeSelection.create(tr.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nJoin the selected block, or the closest ancestor of the selection\nthat can be joined, with the sibling after it.\n*/\nconst joinDown = (state, dispatch) => {\n let sel = state.selection, point;\n if (sel instanceof NodeSelection) {\n if (sel.node.isTextblock || !canJoin(state.doc, sel.to))\n return false;\n point = sel.to;\n }\n else {\n point = joinPoint(state.doc, sel.to, 1);\n if (point == null)\n return false;\n }\n if (dispatch)\n dispatch(state.tr.join(point).scrollIntoView());\n return true;\n};\n/**\nLift the selected block, or the closest ancestor block of the\nselection that can be lifted, out of its parent node.\n*/\nconst lift = (state, dispatch) => {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nIf the selection is in a node whose type has a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, replace the\nselection with a newline character.\n*/\nconst newlineInCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n if (dispatch)\n dispatch(state.tr.insertText(\"\\n\").scrollIntoView());\n return true;\n};\nfunction defaultBlockAt(match) {\n for (let i = 0; i < match.edgeCount; i++) {\n let { type } = match.edge(i);\n if (type.isTextblock && !type.hasRequiredAttrs())\n return type;\n }\n return null;\n}\n/**\nWhen the selection is in a node with a truthy\n[`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) property in its spec, create a\ndefault block after the code block, and move the cursor there.\n*/\nconst exitCode = (state, dispatch) => {\n let { $head, $anchor } = state.selection;\n if (!$head.parent.type.spec.code || !$head.sameParent($anchor))\n return false;\n let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));\n if (!type || !above.canReplaceWith(after, after, type))\n return false;\n if (dispatch) {\n let pos = $head.after(), tr = state.tr.replaceWith(pos, pos, type.createAndFill());\n tr.setSelection(Selection.near(tr.doc.resolve(pos), 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf a block node is selected, create an empty paragraph before (if\nit is its parent's first child) or after it.\n*/\nconst createParagraphNear = (state, dispatch) => {\n let sel = state.selection, { $from, $to } = sel;\n if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)\n return false;\n let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));\n if (!type || !type.isTextblock)\n return false;\n if (dispatch) {\n let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;\n let tr = state.tr.insert(side, type.createAndFill());\n tr.setSelection(TextSelection.create(tr.doc, side + 1));\n dispatch(tr.scrollIntoView());\n }\n return true;\n};\n/**\nIf the cursor is in an empty textblock that can be lifted, lift the\nblock.\n*/\nconst liftEmptyBlock = (state, dispatch) => {\n let { $cursor } = state.selection;\n if (!$cursor || $cursor.parent.content.size)\n return false;\n if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {\n let before = $cursor.before();\n if (canSplit(state.doc, before)) {\n if (dispatch)\n dispatch(state.tr.split(before).scrollIntoView());\n return true;\n }\n }\n let range = $cursor.blockRange(), target = range && liftTarget(range);\n if (target == null)\n return false;\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n};\n/**\nCreate a variant of [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock) that uses\na custom function to determine the type of the newly split off block.\n*/\nfunction splitBlockAs(splitNode) {\n return (state, dispatch) => {\n let { $from, $to } = state.selection;\n if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(state.doc, $from.pos))\n return false;\n if (dispatch)\n dispatch(state.tr.split($from.pos).scrollIntoView());\n return true;\n }\n if (!$from.depth)\n return false;\n let types = [];\n let splitDepth, deflt, atEnd = false, atStart = false;\n for (let d = $from.depth;; d--) {\n let node = $from.node(d);\n if (node.isBlock) {\n atEnd = $from.end(d) == $from.pos + ($from.depth - d);\n atStart = $from.start(d) == $from.pos - ($from.depth - d);\n deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));\n let splitType = splitNode && splitNode($to.parent, atEnd, $from);\n types.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));\n splitDepth = d;\n break;\n }\n else {\n if (d == 1)\n return false;\n types.unshift(null);\n }\n }\n let tr = state.tr;\n if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)\n tr.deleteSelection();\n let splitPos = tr.mapping.map($from.pos);\n let can = canSplit(tr.doc, splitPos, types.length, types);\n if (!can) {\n types[0] = deflt ? { type: deflt } : null;\n can = canSplit(tr.doc, splitPos, types.length, types);\n }\n if (!can)\n return false;\n tr.split(splitPos, types.length, types);\n if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {\n let first = tr.mapping.map($from.before(splitDepth)), $first = tr.doc.resolve(first);\n if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))\n tr.setNodeMarkup(tr.mapping.map($from.before(splitDepth)), deflt);\n }\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nSplit the parent block of the selection. If the selection is a text\nselection, also delete its content.\n*/\nconst splitBlock = splitBlockAs();\n/**\nActs like [`splitBlock`](https://prosemirror.net/docs/ref/#commands.splitBlock), but without\nresetting the set of active marks at the cursor.\n*/\nconst splitBlockKeepMarks = (state, dispatch) => {\n return splitBlock(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n};\n/**\nMove the selection to the node wrapping the current selection, if\nany. (Will not select the document node.)\n*/\nconst selectParentNode = (state, dispatch) => {\n let { $from, to } = state.selection, pos;\n let same = $from.sharedDepth(to);\n if (same == 0)\n return false;\n pos = $from.before(same);\n if (dispatch)\n dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));\n return true;\n};\n/**\nSelect the whole document.\n*/\nconst selectAll = (state, dispatch) => {\n if (dispatch)\n dispatch(state.tr.setSelection(new AllSelection(state.doc)));\n return true;\n};\nfunction joinMaybeClear(state, $pos, dispatch) {\n let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();\n if (!before || !after || !before.type.compatibleContent(after.type))\n return false;\n if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {\n if (dispatch)\n dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());\n return true;\n }\n if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))\n return false;\n if (dispatch)\n dispatch(state.tr.join($pos.pos).scrollIntoView());\n return true;\n}\nfunction deleteBarrier(state, $cut, dispatch, dir) {\n let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;\n let isolated = before.type.spec.isolating || after.type.spec.isolating;\n if (!isolated && joinMaybeClear(state, $cut, dispatch))\n return true;\n let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);\n if (canDelAfter &&\n (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) &&\n match.matchType(conn[0] || after.type).validEnd) {\n if (dispatch) {\n let end = $cut.pos + after.nodeSize, wrap = Fragment.empty;\n for (let i = conn.length - 1; i >= 0; i--)\n wrap = Fragment.from(conn[i].create(null, wrap));\n wrap = Fragment.from(before.copy(wrap));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap, 1, 0), conn.length, true));\n let $joinAt = tr.doc.resolve(end + 2 * conn.length);\n if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type &&\n canJoin(tr.doc, $joinAt.pos))\n tr.join($joinAt.pos);\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let selAfter = after.type.spec.isolating || (dir > 0 && isolated) ? null : Selection.findFrom($cut, 1);\n let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);\n if (target != null && target >= $cut.depth) {\n if (dispatch)\n dispatch(state.tr.lift(range, target).scrollIntoView());\n return true;\n }\n if (canDelAfter && textblockAt(after, \"start\", true) && textblockAt(before, \"end\")) {\n let at = before, wrap = [];\n for (;;) {\n wrap.push(at);\n if (at.isTextblock)\n break;\n at = at.lastChild;\n }\n let afterText = after, afterDepth = 1;\n for (; !afterText.isTextblock; afterText = afterText.firstChild)\n afterDepth++;\n if (at.canReplace(at.childCount, at.childCount, afterText.content)) {\n if (dispatch) {\n let end = Fragment.empty;\n for (let i = wrap.length - 1; i >= 0; i--)\n end = Fragment.from(wrap[i].copy(end));\n let tr = state.tr.step(new ReplaceAroundStep($cut.pos - wrap.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap.length, 0), 0, true));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n }\n return false;\n}\nfunction selectTextblockSide(side) {\n return function (state, dispatch) {\n let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;\n let depth = $pos.depth;\n while ($pos.node(depth).isInline) {\n if (!depth)\n return false;\n depth--;\n }\n if (!$pos.node(depth).isTextblock)\n return false;\n if (dispatch)\n dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));\n return true;\n };\n}\n/**\nMoves the cursor to the start of current text block.\n*/\nconst selectTextblockStart = selectTextblockSide(-1);\n/**\nMoves the cursor to the end of current text block.\n*/\nconst selectTextblockEnd = selectTextblockSide(1);\n// Parameterized commands\n/**\nWrap the selection in a node of the given type with the given\nattributes.\n*/\nfunction wrapIn(nodeType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);\n if (!wrapping)\n return false;\n if (dispatch)\n dispatch(state.tr.wrap(range, wrapping).scrollIntoView());\n return true;\n };\n}\n/**\nReturns a command that tries to set the selected textblocks to the\ngiven node type with the given attributes.\n*/\nfunction setBlockType(nodeType, attrs = null) {\n return function (state, dispatch) {\n let applicable = false;\n for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (applicable)\n return false;\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs))\n return;\n if (node.type == nodeType) {\n applicable = true;\n }\n else {\n let $pos = state.doc.resolve(pos), index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n }\n if (!applicable)\n return false;\n if (dispatch) {\n let tr = state.tr;\n for (let i = 0; i < state.selection.ranges.length; i++) {\n let { $from: { pos: from }, $to: { pos: to } } = state.selection.ranges[i];\n tr.setBlockType(from, to, nodeType, attrs);\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\nfunction markApplies(doc, ranges, type, enterAtoms) {\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n let can = $from.depth == 0 ? doc.inlineContent && doc.type.allowsMarkType(type) : false;\n doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (can || !enterAtoms && node.isAtom && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos)\n return false;\n can = node.inlineContent && node.type.allowsMarkType(type);\n });\n if (can)\n return true;\n }\n return false;\n}\nfunction removeInlineAtoms(ranges) {\n let result = [];\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.isAtom && node.content.size && node.isInline && pos >= $from.pos && pos + node.nodeSize <= $to.pos) {\n if (pos + 1 > $from.pos)\n result.push(new SelectionRange($from, $from.doc.resolve(pos + 1)));\n $from = $from.doc.resolve(pos + 1 + node.content.size);\n return false;\n }\n });\n if ($from.pos < $to.pos)\n result.push(new SelectionRange($from, $to));\n }\n return result;\n}\n/**\nCreate a command function that toggles the given mark with the\ngiven attributes. Will return `false` when the current selection\ndoesn't support that mark. This will remove the mark if any marks\nof that type exist in the selection, or add it otherwise. If the\nselection is empty, this applies to the [stored\nmarks](https://prosemirror.net/docs/ref/#state.EditorState.storedMarks) instead of a range of the\ndocument.\n*/\nfunction toggleMark(markType, attrs = null, options) {\n let removeWhenPresent = (options && options.removeWhenPresent) !== false;\n let enterAtoms = (options && options.enterInlineAtoms) !== false;\n let dropSpace = !(options && options.includeWhitespace);\n return function (state, dispatch) {\n let { empty, $cursor, ranges } = state.selection;\n if ((empty && !$cursor) || !markApplies(state.doc, ranges, markType, enterAtoms))\n return false;\n if (dispatch) {\n if ($cursor) {\n if (markType.isInSet(state.storedMarks || $cursor.marks()))\n dispatch(state.tr.removeStoredMark(markType));\n else\n dispatch(state.tr.addStoredMark(markType.create(attrs)));\n }\n else {\n let add, tr = state.tr;\n if (!enterAtoms)\n ranges = removeInlineAtoms(ranges);\n if (removeWhenPresent) {\n add = !ranges.some(r => state.doc.rangeHasMark(r.$from.pos, r.$to.pos, markType));\n }\n else {\n add = !ranges.every(r => {\n let missing = false;\n tr.doc.nodesBetween(r.$from.pos, r.$to.pos, (node, pos, parent) => {\n if (missing)\n return false;\n missing = !markType.isInSet(node.marks) && !!parent && parent.type.allowsMarkType(markType) &&\n !(node.isText && /^\\s*$/.test(node.textBetween(Math.max(0, r.$from.pos - pos), Math.min(node.nodeSize, r.$to.pos - pos))));\n });\n return !missing;\n });\n }\n for (let i = 0; i < ranges.length; i++) {\n let { $from, $to } = ranges[i];\n if (!add) {\n tr.removeMark($from.pos, $to.pos, markType);\n }\n else {\n let from = $from.pos, to = $to.pos, start = $from.nodeAfter, end = $to.nodeBefore;\n let spaceStart = dropSpace && start && start.isText ? /^\\s*/.exec(start.text)[0].length : 0;\n let spaceEnd = dropSpace && end && end.isText ? /\\s*$/.exec(end.text)[0].length : 0;\n if (from + spaceStart < to) {\n from += spaceStart;\n to -= spaceEnd;\n }\n tr.addMark(from, to, markType.create(attrs));\n }\n }\n dispatch(tr.scrollIntoView());\n }\n }\n return true;\n };\n}\nfunction wrapDispatchForJoin(dispatch, isJoinable) {\n return (tr) => {\n if (!tr.isGeneric)\n return dispatch(tr);\n let ranges = [];\n for (let i = 0; i < tr.mapping.maps.length; i++) {\n let map = tr.mapping.maps[i];\n for (let j = 0; j < ranges.length; j++)\n ranges[j] = map.map(ranges[j]);\n map.forEach((_s, _e, from, to) => ranges.push(from, to));\n }\n // Figure out which joinable points exist inside those ranges,\n // by checking all node boundaries in their parent nodes.\n let joinable = [];\n for (let i = 0; i < ranges.length; i += 2) {\n let from = ranges[i], to = ranges[i + 1];\n let $from = tr.doc.resolve(from), depth = $from.sharedDepth(to), parent = $from.node(depth);\n for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {\n let after = parent.maybeChild(index);\n if (!after)\n break;\n if (index && joinable.indexOf(pos) == -1) {\n let before = parent.child(index - 1);\n if (before.type == after.type && isJoinable(before, after))\n joinable.push(pos);\n }\n pos += after.nodeSize;\n }\n }\n // Join the joinable points\n joinable.sort((a, b) => a - b);\n for (let i = joinable.length - 1; i >= 0; i--) {\n if (canJoin(tr.doc, joinable[i]))\n tr.join(joinable[i]);\n }\n dispatch(tr);\n };\n}\n/**\nWrap a command so that, when it produces a transform that causes\ntwo joinable nodes to end up next to each other, those are joined.\nNodes are considered joinable when they are of the same type and\nwhen the `isJoinable` predicate returns true for them or, if an\narray of strings was passed, if their node type name is in that\narray.\n*/\nfunction autoJoin(command, isJoinable) {\n let canJoin = Array.isArray(isJoinable) ? (node) => isJoinable.indexOf(node.type.name) > -1\n : isJoinable;\n return (state, dispatch, view) => command(state, dispatch && wrapDispatchForJoin(dispatch, canJoin), view);\n}\n/**\nCombine a number of command functions into a single function (which\ncalls them one by one until one returns true).\n*/\nfunction chainCommands(...commands) {\n return function (state, dispatch, view) {\n for (let i = 0; i < commands.length; i++)\n if (commands[i](state, dispatch, view))\n return true;\n return false;\n };\n}\nlet backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);\nlet del = chainCommands(deleteSelection, joinForward, selectNodeForward);\n/**\nA basic keymap containing bindings not specific to any schema.\nBinds the following keys (when multiple commands are listed, they\nare chained with [`chainCommands`](https://prosemirror.net/docs/ref/#commands.chainCommands)):\n\n* **Enter** to `newlineInCode`, `createParagraphNear`, `liftEmptyBlock`, `splitBlock`\n* **Mod-Enter** to `exitCode`\n* **Backspace** and **Mod-Backspace** to `deleteSelection`, `joinBackward`, `selectNodeBackward`\n* **Delete** and **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-Delete** to `deleteSelection`, `joinForward`, `selectNodeForward`\n* **Mod-a** to `selectAll`\n*/\nconst pcBaseKeymap = {\n \"Enter\": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),\n \"Mod-Enter\": exitCode,\n \"Backspace\": backspace,\n \"Mod-Backspace\": backspace,\n \"Shift-Backspace\": backspace,\n \"Delete\": del,\n \"Mod-Delete\": del,\n \"Mod-a\": selectAll\n};\n/**\nA copy of `pcBaseKeymap` that also binds **Ctrl-h** like Backspace,\n**Ctrl-d** like Delete, **Alt-Backspace** like Ctrl-Backspace, and\n**Ctrl-Alt-Backspace**, **Alt-Delete**, and **Alt-d** like\nCtrl-Delete.\n*/\nconst macBaseKeymap = {\n \"Ctrl-h\": pcBaseKeymap[\"Backspace\"],\n \"Alt-Backspace\": pcBaseKeymap[\"Mod-Backspace\"],\n \"Ctrl-d\": pcBaseKeymap[\"Delete\"],\n \"Ctrl-Alt-Backspace\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-Delete\": pcBaseKeymap[\"Mod-Delete\"],\n \"Alt-d\": pcBaseKeymap[\"Mod-Delete\"],\n \"Ctrl-a\": selectTextblockStart,\n \"Ctrl-e\": selectTextblockEnd\n};\nfor (let key in pcBaseKeymap)\n macBaseKeymap[key] = pcBaseKeymap[key];\nconst mac = typeof navigator != \"undefined\" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform)\n // @ts-ignore\n : typeof os != \"undefined\" && os.platform ? os.platform() == \"darwin\" : false;\n/**\nDepending on the detected platform, this will hold\n[`pcBasekeymap`](https://prosemirror.net/docs/ref/#commands.pcBaseKeymap) or\n[`macBaseKeymap`](https://prosemirror.net/docs/ref/#commands.macBaseKeymap).\n*/\nconst baseKeymap = mac ? macBaseKeymap : pcBaseKeymap;\n\nexport { autoJoin, baseKeymap, chainCommands, createParagraphNear, deleteSelection, exitCode, joinBackward, joinDown, joinForward, joinTextblockBackward, joinTextblockForward, joinUp, lift, liftEmptyBlock, macBaseKeymap, newlineInCode, pcBaseKeymap, selectAll, selectNodeBackward, selectNodeForward, selectParentNode, selectTextblockEnd, selectTextblockStart, setBlockType, splitBlock, splitBlockAs, splitBlockKeepMarks, toggleMark, wrapIn };\n", "import { findWrapping, ReplaceAroundStep, canSplit, liftTarget, canJoin } from 'prosemirror-transform';\nimport { NodeRange, Fragment, Slice } from 'prosemirror-model';\nimport { Selection } from 'prosemirror-state';\n\nconst olDOM = [\"ol\", 0], ulDOM = [\"ul\", 0], liDOM = [\"li\", 0];\n/**\nAn ordered list [node spec](https://prosemirror.net/docs/ref/#model.NodeSpec). Has a single\nattribute, `order`, which determines the number at which the list\nstarts counting, and defaults to 1. Represented as an `
    `\nelement.\n*/\nconst orderedList = {\n attrs: { order: { default: 1, validate: \"number\" } },\n parseDOM: [{ tag: \"ol\", getAttrs(dom) {\n return { order: dom.hasAttribute(\"start\") ? +dom.getAttribute(\"start\") : 1 };\n } }],\n toDOM(node) {\n return node.attrs.order == 1 ? olDOM : [\"ol\", { start: node.attrs.order }, 0];\n }\n};\n/**\nA bullet list node spec, represented in the DOM as `
      `.\n*/\nconst bulletList = {\n parseDOM: [{ tag: \"ul\" }],\n toDOM() { return ulDOM; }\n};\n/**\nA list item (`
    • `) spec.\n*/\nconst listItem = {\n parseDOM: [{ tag: \"li\" }],\n toDOM() { return liDOM; },\n defining: true\n};\nfunction add(obj, props) {\n let copy = {};\n for (let prop in obj)\n copy[prop] = obj[prop];\n for (let prop in props)\n copy[prop] = props[prop];\n return copy;\n}\n/**\nConvenience function for adding list-related node types to a map\nspecifying the nodes for a schema. Adds\n[`orderedList`](https://prosemirror.net/docs/ref/#schema-list.orderedList) as `\"ordered_list\"`,\n[`bulletList`](https://prosemirror.net/docs/ref/#schema-list.bulletList) as `\"bullet_list\"`, and\n[`listItem`](https://prosemirror.net/docs/ref/#schema-list.listItem) as `\"list_item\"`.\n\n`itemContent` determines the content expression for the list items.\nIf you want the commands defined in this module to apply to your\nlist structure, it should have a shape like `\"paragraph block*\"` or\n`\"paragraph (ordered_list | bullet_list)*\"`. `listGroup` can be\ngiven to assign a group name to the list node types, for example\n`\"block\"`.\n*/\nfunction addListNodes(nodes, itemContent, listGroup) {\n return nodes.append({\n ordered_list: add(orderedList, { content: \"list_item+\", group: listGroup }),\n bullet_list: add(bulletList, { content: \"list_item+\", group: listGroup }),\n list_item: add(listItem, { content: itemContent })\n });\n}\n/**\nReturns a command function that wraps the selection in a list with\nthe given type an attributes. If `dispatch` is null, only return a\nvalue to indicate whether this is possible, but don't actually\nperform the change.\n*/\nfunction wrapInList(listType, attrs = null) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to);\n if (!range)\n return false;\n let tr = dispatch ? state.tr : null;\n if (!wrapRangeInList(tr, range, listType, attrs))\n return false;\n if (dispatch)\n dispatch(tr.scrollIntoView());\n return true;\n };\n}\n/**\nTry to wrap the given node range in a list of the given type.\nReturn `true` when this is possible, `false` otherwise. When `tr`\nis non-null, the wrapping is added to that transaction. When it is\n`null`, the function only queries whether the wrapping is\npossible.\n*/\nfunction wrapRangeInList(tr, range, listType, attrs = null) {\n let doJoin = false, outerRange = range, doc = range.$from.doc;\n // This is at the top of an existing list item\n if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {\n // Don't do anything if this is the top of the list\n if (range.$from.index(range.depth - 1) == 0)\n return false;\n let $insert = doc.resolve(range.start - 2);\n outerRange = new NodeRange($insert, $insert, range.depth);\n if (range.endIndex < range.parent.childCount)\n range = new NodeRange(range.$from, doc.resolve(range.$to.end(range.depth)), range.depth);\n doJoin = true;\n }\n let wrap = findWrapping(outerRange, listType, attrs, range);\n if (!wrap)\n return false;\n if (tr)\n doWrapInList(tr, range, wrap, doJoin, listType);\n return true;\n}\nfunction doWrapInList(tr, range, wrappers, joinBefore, listType) {\n let content = Fragment.empty;\n for (let i = wrappers.length - 1; i >= 0; i--)\n content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));\n tr.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));\n let found = 0;\n for (let i = 0; i < wrappers.length; i++)\n if (wrappers[i].type == listType)\n found = i + 1;\n let splitDepth = wrappers.length - found;\n let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;\n for (let i = range.startIndex, e = range.endIndex, first = true; i < e; i++, first = false) {\n if (!first && canSplit(tr.doc, splitPos, splitDepth)) {\n tr.split(splitPos, splitDepth);\n splitPos += 2 * splitDepth;\n }\n splitPos += parent.child(i).nodeSize;\n }\n return tr;\n}\n/**\nBuild a command that splits a non-empty textblock at the top level\nof a list item by also splitting that list item.\n*/\nfunction splitListItem(itemType, itemAttrs) {\n return function (state, dispatch) {\n let { $from, $to, node } = state.selection;\n if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to))\n return false;\n let grandParent = $from.node(-1);\n if (grandParent.type != itemType)\n return false;\n if ($from.parent.content.size == 0 && $from.node(-1).childCount == $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth == 3 || $from.node(-3).type != itemType ||\n $from.index(-2) != $from.node(-2).childCount - 1)\n return false;\n if (dispatch) {\n let wrap = Fragment.empty;\n let depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d--)\n wrap = Fragment.from($from.node(d).copy(wrap));\n let depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1\n : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;\n // Add a second list item with an empty default start node\n wrap = wrap.append(Fragment.from(itemType.createAndFill()));\n let start = $from.before($from.depth - (depthBefore - 1));\n let tr = state.tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));\n let sel = -1;\n tr.doc.nodesBetween(start, tr.doc.content.size, (node, pos) => {\n if (sel > -1)\n return false;\n if (node.isTextblock && node.content.size == 0)\n sel = pos + 1;\n });\n if (sel > -1)\n tr.setSelection(Selection.near(tr.doc.resolve(sel)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n }\n let nextType = $to.pos == $from.end() ? grandParent.contentMatchAt(0).defaultType : null;\n let tr = state.tr.delete($from.pos, $to.pos);\n let types = nextType ? [itemAttrs ? { type: itemType, attrs: itemAttrs } : null, { type: nextType }] : undefined;\n if (!canSplit(tr.doc, $from.pos, 2, types))\n return false;\n if (dispatch)\n dispatch(tr.split($from.pos, 2, types).scrollIntoView());\n return true;\n };\n}\n/**\nActs like [`splitListItem`](https://prosemirror.net/docs/ref/#schema-list.splitListItem), but\nwithout resetting the set of active marks at the cursor.\n*/\nfunction splitListItemKeepMarks(itemType, itemAttrs) {\n let split = splitListItem(itemType, itemAttrs);\n return (state, dispatch) => {\n return split(state, dispatch && (tr => {\n let marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());\n if (marks)\n tr.ensureMarks(marks);\n dispatch(tr);\n }));\n };\n}\n/**\nCreate a command to lift the list item around the selection up into\na wrapping list.\n*/\nfunction liftListItem(itemType) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range)\n return false;\n if (!dispatch)\n return true;\n if ($from.node(range.depth - 1).type == itemType) // Inside a parent list\n return liftToOuterList(state, dispatch, itemType, range);\n else // Outer list node\n return liftOutOfList(state, dispatch, range);\n };\n}\nfunction liftToOuterList(state, dispatch, itemType, range) {\n let tr = state.tr, end = range.end, endOfList = range.$to.end(range.depth);\n if (end < endOfList) {\n // There are siblings after the lifted items, which must become\n // children of the last item\n tr.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));\n range = new NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);\n }\n const target = liftTarget(range);\n if (target == null)\n return false;\n tr.lift(range, target);\n let $after = tr.doc.resolve(tr.mapping.map(end, -1) - 1);\n if (canJoin(tr.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type)\n tr.join($after.pos);\n dispatch(tr.scrollIntoView());\n return true;\n}\nfunction liftOutOfList(state, dispatch, range) {\n let tr = state.tr, list = range.parent;\n // Merge the list items into a single big item\n for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {\n pos -= list.child(i).nodeSize;\n tr.delete(pos - 1, pos + 1);\n }\n let $start = tr.doc.resolve(range.start), item = $start.nodeAfter;\n if (tr.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)\n return false;\n let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount;\n let parent = $start.node(-1), indexBefore = $start.index(-1);\n if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))\n return false;\n let start = $start.pos, end = start + item.nodeSize;\n // Strip off the surrounding list. At the sides where we're not at\n // the end of the list, the existing list is closed. At sides where\n // this is the end, it is overwritten to its end.\n tr.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty)))\n .append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));\n dispatch(tr.scrollIntoView());\n return true;\n}\n/**\nCreate a command to sink the list item around the selection down\ninto an inner list.\n*/\nfunction sinkListItem(itemType) {\n return function (state, dispatch) {\n let { $from, $to } = state.selection;\n let range = $from.blockRange($to, node => node.childCount > 0 && node.firstChild.type == itemType);\n if (!range)\n return false;\n let startIndex = range.startIndex;\n if (startIndex == 0)\n return false;\n let parent = range.parent, nodeBefore = parent.child(startIndex - 1);\n if (nodeBefore.type != itemType)\n return false;\n if (dispatch) {\n let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;\n let inner = Fragment.from(nestedBefore ? itemType.create() : null);\n let slice = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);\n let before = range.start, after = range.end;\n dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice, 1, true))\n .scrollIntoView());\n }\n return true;\n };\n}\n\nexport { addListNodes, bulletList, liftListItem, listItem, orderedList, sinkListItem, splitListItem, splitListItemKeepMarks, wrapInList, wrapRangeInList };\n", "import { TextSelection, NodeSelection, AllSelection, Selection } from 'prosemirror-state';\nimport { DOMSerializer, Fragment, Mark, Slice, DOMParser } from 'prosemirror-model';\nimport { dropPoint } from 'prosemirror-transform';\n\nconst domIndex = function (node) {\n for (var index = 0;; index++) {\n node = node.previousSibling;\n if (!node)\n return index;\n }\n};\nconst parentNode = function (node) {\n let parent = node.assignedSlot || node.parentNode;\n return parent && parent.nodeType == 11 ? parent.host : parent;\n};\nlet reusedRange = null;\n// Note that this will always return the same range, because DOM range\n// objects are every expensive, and keep slowing down subsequent DOM\n// updates, for some reason.\nconst textRange = function (node, from, to) {\n let range = reusedRange || (reusedRange = document.createRange());\n range.setEnd(node, to == null ? node.nodeValue.length : to);\n range.setStart(node, from || 0);\n return range;\n};\nconst clearReusedRange = function () {\n reusedRange = null;\n};\n// Scans forward and backward through DOM positions equivalent to the\n// given one to see if the two are in the same place (i.e. after a\n// text node vs at the end of that text node)\nconst isEquivalentPosition = function (node, off, targetNode, targetOff) {\n return targetNode && (scanFor(node, off, targetNode, targetOff, -1) ||\n scanFor(node, off, targetNode, targetOff, 1));\n};\nconst atomElements = /^(img|br|input|textarea|hr)$/i;\nfunction scanFor(node, off, targetNode, targetOff, dir) {\n var _a;\n for (;;) {\n if (node == targetNode && off == targetOff)\n return true;\n if (off == (dir < 0 ? 0 : nodeSize(node))) {\n let parent = node.parentNode;\n if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) ||\n node.contentEditable == \"false\")\n return false;\n off = domIndex(node) + (dir < 0 ? 0 : 1);\n node = parent;\n }\n else if (node.nodeType == 1) {\n let child = node.childNodes[off + (dir < 0 ? -1 : 0)];\n if (child.nodeType == 1 && child.contentEditable == \"false\") {\n if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection)\n off += dir;\n else\n return false;\n }\n else {\n node = child;\n off = dir < 0 ? nodeSize(node) : 0;\n }\n }\n else {\n return false;\n }\n }\n}\nfunction nodeSize(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction textNodeBefore$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset)\n return node;\n if (node.nodeType == 1 && offset > 0) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset - 1];\n offset = nodeSize(node);\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction textNodeAfter$1(node, offset) {\n for (;;) {\n if (node.nodeType == 3 && offset < node.nodeValue.length)\n return node;\n if (node.nodeType == 1 && offset < node.childNodes.length) {\n if (node.contentEditable == \"false\")\n return null;\n node = node.childNodes[offset];\n offset = 0;\n }\n else if (node.parentNode && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n else {\n return null;\n }\n }\n}\nfunction isOnEdge(node, offset, parent) {\n for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd;) {\n if (node == parent)\n return true;\n let index = domIndex(node);\n node = node.parentNode;\n if (!node)\n return false;\n atStart = atStart && index == 0;\n atEnd = atEnd && index == nodeSize(node);\n }\n}\nfunction hasBlockDesc(dom) {\n let desc;\n for (let cur = dom; cur; cur = cur.parentNode)\n if (desc = cur.pmViewDesc)\n break;\n return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);\n}\n// Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523\n// (isCollapsed inappropriately returns true in shadow dom)\nconst selectionCollapsed = function (domSel) {\n return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);\n};\nfunction keyEvent(keyCode, key) {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"keydown\", true, true);\n event.keyCode = keyCode;\n event.key = event.code = key;\n return event;\n}\nfunction deepActiveElement(doc) {\n let elt = doc.activeElement;\n while (elt && elt.shadowRoot)\n elt = elt.shadowRoot.activeElement;\n return elt;\n}\nfunction caretFromPoint(doc, x, y) {\n if (doc.caretPositionFromPoint) {\n try { // Firefox throws for this call in hard-to-predict circumstances (#994)\n let pos = doc.caretPositionFromPoint(x, y);\n // Clip the offset, because Chrome will return a text offset\n // into nodes, which can't be treated as a regular DOM\n // offset\n if (pos)\n return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };\n }\n catch (_) { }\n }\n if (doc.caretRangeFromPoint) {\n let range = doc.caretRangeFromPoint(x, y);\n if (range)\n return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };\n }\n}\n\nconst nav = typeof navigator != \"undefined\" ? navigator : null;\nconst doc = typeof document != \"undefined\" ? document : null;\nconst agent = (nav && nav.userAgent) || \"\";\nconst ie_edge = /Edge\\/(\\d+)/.exec(agent);\nconst ie_upto10 = /MSIE \\d/.exec(agent);\nconst ie_11up = /Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(agent);\nconst ie = !!(ie_upto10 || ie_11up || ie_edge);\nconst ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;\nconst gecko = !ie && /gecko\\/(\\d+)/i.test(agent);\ngecko && +(/Firefox\\/(\\d+)/.exec(agent) || [0, 0])[1];\nconst _chrome = !ie && /Chrome\\/(\\d+)/.exec(agent);\nconst chrome = !!_chrome;\nconst chrome_version = _chrome ? +_chrome[1] : 0;\nconst safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);\n// Is true for both iOS and iPadOS for convenience\nconst ios = safari && (/Mobile\\/\\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);\nconst mac = ios || (nav ? /Mac/.test(nav.platform) : false);\nconst windows = nav ? /Win/.test(nav.platform) : false;\nconst android = /Android \\d/.test(agent);\nconst webkit = !!doc && \"webkitFontSmoothing\" in doc.documentElement.style;\nconst webkit_version = webkit ? +(/\\bAppleWebKit\\/(\\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;\n\nfunction windowRect(doc) {\n let vp = doc.defaultView && doc.defaultView.visualViewport;\n if (vp)\n return {\n left: 0, right: vp.width,\n top: 0, bottom: vp.height\n };\n return { left: 0, right: doc.documentElement.clientWidth,\n top: 0, bottom: doc.documentElement.clientHeight };\n}\nfunction getSide(value, side) {\n return typeof value == \"number\" ? value : value[side];\n}\nfunction clientRect(node) {\n let rect = node.getBoundingClientRect();\n // Adjust for elements with style \"transform: scale()\"\n let scaleX = (rect.width / node.offsetWidth) || 1;\n let scaleY = (rect.height / node.offsetHeight) || 1;\n // Make sure scrollbar width isn't included in the rectangle\n return { left: rect.left, right: rect.left + node.clientWidth * scaleX,\n top: rect.top, bottom: rect.top + node.clientHeight * scaleY };\n}\nfunction scrollRectIntoView(view, rect, startDOM) {\n let scrollThreshold = view.someProp(\"scrollThreshold\") || 0, scrollMargin = view.someProp(\"scrollMargin\") || 5;\n let doc = view.dom.ownerDocument;\n for (let parent = startDOM || view.dom;;) {\n if (!parent)\n break;\n if (parent.nodeType != 1) {\n parent = parentNode(parent);\n continue;\n }\n let elt = parent;\n let atTop = elt == doc.body;\n let bounding = atTop ? windowRect(doc) : clientRect(elt);\n let moveX = 0, moveY = 0;\n if (rect.top < bounding.top + getSide(scrollThreshold, \"top\"))\n moveY = -(bounding.top - rect.top + getSide(scrollMargin, \"top\"));\n else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, \"bottom\"))\n moveY = rect.bottom - rect.top > bounding.bottom - bounding.top\n ? rect.top + getSide(scrollMargin, \"top\") - bounding.top\n : rect.bottom - bounding.bottom + getSide(scrollMargin, \"bottom\");\n if (rect.left < bounding.left + getSide(scrollThreshold, \"left\"))\n moveX = -(bounding.left - rect.left + getSide(scrollMargin, \"left\"));\n else if (rect.right > bounding.right - getSide(scrollThreshold, \"right\"))\n moveX = rect.right - bounding.right + getSide(scrollMargin, \"right\");\n if (moveX || moveY) {\n if (atTop) {\n doc.defaultView.scrollBy(moveX, moveY);\n }\n else {\n let startX = elt.scrollLeft, startY = elt.scrollTop;\n if (moveY)\n elt.scrollTop += moveY;\n if (moveX)\n elt.scrollLeft += moveX;\n let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;\n rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };\n }\n }\n let pos = atTop ? \"fixed\" : getComputedStyle(parent).position;\n if (/^(fixed|sticky)$/.test(pos))\n break;\n parent = pos == \"absolute\" ? parent.offsetParent : parentNode(parent);\n }\n}\n// Store the scroll position of the editor's parent nodes, along with\n// the top position of an element near the top of the editor, which\n// will be used to make sure the visible viewport remains stable even\n// when the size of the content above changes.\nfunction storeScrollPos(view) {\n let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);\n let refDOM, refTop;\n for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {\n let dom = view.root.elementFromPoint(x, y);\n if (!dom || dom == view.dom || !view.dom.contains(dom))\n continue;\n let localRect = dom.getBoundingClientRect();\n if (localRect.top >= startY - 20) {\n refDOM = dom;\n refTop = localRect.top;\n break;\n }\n }\n return { refDOM: refDOM, refTop: refTop, stack: scrollStack(view.dom) };\n}\nfunction scrollStack(dom) {\n let stack = [], doc = dom.ownerDocument;\n for (let cur = dom; cur; cur = parentNode(cur)) {\n stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });\n if (dom == doc)\n break;\n }\n return stack;\n}\n// Reset the scroll position of the editor's parent nodes to that what\n// it was before, when storeScrollPos was called.\nfunction resetScrollPos({ refDOM, refTop, stack }) {\n let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;\n restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);\n}\nfunction restoreScrollStack(stack, dTop) {\n for (let i = 0; i < stack.length; i++) {\n let { dom, top, left } = stack[i];\n if (dom.scrollTop != top + dTop)\n dom.scrollTop = top + dTop;\n if (dom.scrollLeft != left)\n dom.scrollLeft = left;\n }\n}\nlet preventScrollSupported = null;\n// Feature-detects support for .focus({preventScroll: true}), and uses\n// a fallback kludge when not supported.\nfunction focusPreventScroll(dom) {\n if (dom.setActive)\n return dom.setActive(); // in IE\n if (preventScrollSupported)\n return dom.focus(preventScrollSupported);\n let stored = scrollStack(dom);\n dom.focus(preventScrollSupported == null ? {\n get preventScroll() {\n preventScrollSupported = { preventScroll: true };\n return true;\n }\n } : undefined);\n if (!preventScrollSupported) {\n preventScrollSupported = false;\n restoreScrollStack(stored, 0);\n }\n}\nfunction findOffsetInNode(node, coords) {\n let closest, dxClosest = 2e8, coordsClosest, offset = 0;\n let rowBot = coords.top, rowTop = coords.top;\n let firstBelow, coordsBelow;\n for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {\n let rects;\n if (child.nodeType == 1)\n rects = child.getClientRects();\n else if (child.nodeType == 3)\n rects = textRange(child).getClientRects();\n else\n continue;\n for (let i = 0; i < rects.length; i++) {\n let rect = rects[i];\n if (rect.top <= rowBot && rect.bottom >= rowTop) {\n rowBot = Math.max(rect.bottom, rowBot);\n rowTop = Math.min(rect.top, rowTop);\n let dx = rect.left > coords.left ? rect.left - coords.left\n : rect.right < coords.left ? coords.left - rect.right : 0;\n if (dx < dxClosest) {\n closest = child;\n dxClosest = dx;\n coordsClosest = dx && closest.nodeType == 3 ? {\n left: rect.right < coords.left ? rect.right : rect.left,\n top: coords.top\n } : coords;\n if (child.nodeType == 1 && dx)\n offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);\n continue;\n }\n }\n else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {\n firstBelow = child;\n coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };\n }\n if (!closest && (coords.left >= rect.right && coords.top >= rect.top ||\n coords.left >= rect.left && coords.top >= rect.bottom))\n offset = childIndex + 1;\n }\n }\n if (!closest && firstBelow) {\n closest = firstBelow;\n coordsClosest = coordsBelow;\n dxClosest = 0;\n }\n if (closest && closest.nodeType == 3)\n return findOffsetInText(closest, coordsClosest);\n if (!closest || (dxClosest && closest.nodeType == 1))\n return { node, offset };\n return findOffsetInNode(closest, coordsClosest);\n}\nfunction findOffsetInText(node, coords) {\n let len = node.nodeValue.length;\n let range = document.createRange(), result;\n for (let i = 0; i < len; i++) {\n range.setEnd(node, i + 1);\n range.setStart(node, i);\n let rect = singleRect(range, 1);\n if (rect.top == rect.bottom)\n continue;\n if (inRect(coords, rect)) {\n result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };\n break;\n }\n }\n range.detach();\n return result || { node, offset: 0 };\n}\nfunction inRect(coords, rect) {\n return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 &&\n coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;\n}\nfunction targetKludge(dom, coords) {\n let parent = dom.parentNode;\n if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)\n return parent;\n return dom;\n}\nfunction posFromElement(view, elt, coords) {\n let { node, offset } = findOffsetInNode(elt, coords), bias = -1;\n if (node.nodeType == 1 && !node.firstChild) {\n let rect = node.getBoundingClientRect();\n bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;\n }\n return view.docView.posFromDOM(node, offset, bias);\n}\nfunction posFromCaret(view, node, offset, coords) {\n // Browser (in caretPosition/RangeFromPoint) will agressively\n // normalize towards nearby inline nodes. Since we are interested in\n // positions between block nodes too, we first walk up the hierarchy\n // of nodes to see if there are block nodes that the coordinates\n // fall outside of. If so, we take the position before/after that\n // block. If not, we call `posFromDOM` on the raw node/offset.\n let outsideBlock = -1;\n for (let cur = node, sawBlock = false;;) {\n if (cur == view.dom)\n break;\n let desc = view.docView.nearestDesc(cur, true), rect;\n if (!desc)\n return null;\n if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) &&\n // Ignore elements with zero-size bounding rectangles\n ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {\n if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {\n // Only apply the horizontal test to the innermost block. Vertical for any parent.\n if (!sawBlock && rect.left > coords.left || rect.top > coords.top)\n outsideBlock = desc.posBefore;\n else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)\n outsideBlock = desc.posAfter;\n sawBlock = true;\n }\n if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {\n // If we are inside a leaf, return the side of the leaf closer to the coords\n let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2\n : coords.left < (rect.left + rect.right) / 2;\n return before ? desc.posBefore : desc.posAfter;\n }\n }\n cur = desc.dom.parentNode;\n }\n return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);\n}\nfunction elementFromPoint(element, coords, box) {\n let len = element.childNodes.length;\n if (len && box.top < box.bottom) {\n for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI;;) {\n let child = element.childNodes[i];\n if (child.nodeType == 1) {\n let rects = child.getClientRects();\n for (let j = 0; j < rects.length; j++) {\n let rect = rects[j];\n if (inRect(coords, rect))\n return elementFromPoint(child, coords, rect);\n }\n }\n if ((i = (i + 1) % len) == startI)\n break;\n }\n }\n return element;\n}\n// Given an x,y position on the editor, get the position in the document.\nfunction posAtCoords(view, coords) {\n let doc = view.dom.ownerDocument, node, offset = 0;\n let caret = caretFromPoint(doc, coords.left, coords.top);\n if (caret)\n ({ node, offset } = caret);\n let elt = (view.root.elementFromPoint ? view.root : doc)\n .elementFromPoint(coords.left, coords.top);\n let pos;\n if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {\n let box = view.dom.getBoundingClientRect();\n if (!inRect(coords, box))\n return null;\n elt = elementFromPoint(view.dom, coords, box);\n if (!elt)\n return null;\n }\n // Safari's caretRangeFromPoint returns nonsense when on a draggable element\n if (safari) {\n for (let p = elt; node && p; p = parentNode(p))\n if (p.draggable)\n node = undefined;\n }\n elt = targetKludge(elt, coords);\n if (node) {\n if (gecko && node.nodeType == 1) {\n // Firefox will sometimes return offsets into nodes, which\n // have no actual children, from caretPositionFromPoint (#953)\n offset = Math.min(offset, node.childNodes.length);\n // It'll also move the returned position before image nodes,\n // even if those are behind it.\n if (offset < node.childNodes.length) {\n let next = node.childNodes[offset], box;\n if (next.nodeName == \"IMG\" && (box = next.getBoundingClientRect()).right <= coords.left &&\n box.bottom > coords.top)\n offset++;\n }\n }\n let prev;\n // When clicking above the right side of an uneditable node, Chrome will report a cursor position after that node.\n if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 &&\n prev.contentEditable == \"false\" && prev.getBoundingClientRect().top >= coords.top)\n offset--;\n // Suspiciously specific kludge to work around caret*FromPoint\n // never returning a position at the end of the document\n if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 &&\n coords.top > node.lastChild.getBoundingClientRect().bottom)\n pos = view.state.doc.content.size;\n // Ignore positions directly after a BR, since caret*FromPoint\n // 'round up' positions that would be more accurately placed\n // before the BR node.\n else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != \"BR\")\n pos = posFromCaret(view, node, offset, coords);\n }\n if (pos == null)\n pos = posFromElement(view, elt, coords);\n let desc = view.docView.nearestDesc(elt, true);\n return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };\n}\nfunction nonZero(rect) {\n return rect.top < rect.bottom || rect.left < rect.right;\n}\nfunction singleRect(target, bias) {\n let rects = target.getClientRects();\n if (rects.length) {\n let first = rects[bias < 0 ? 0 : rects.length - 1];\n if (nonZero(first))\n return first;\n }\n return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();\n}\nconst BIDI = /[\\u0590-\\u05f4\\u0600-\\u06ff\\u0700-\\u08ac]/;\n// Given a position in the document model, get a bounding box of the\n// character at that position, relative to the window.\nfunction coordsAtPos(view, pos, side) {\n let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);\n let supportEmptyRange = webkit || gecko;\n if (node.nodeType == 3) {\n // These browsers support querying empty text ranges. Prefer that in\n // bidi context or when at the end of a node.\n if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {\n let rect = singleRect(textRange(node, offset, offset), side);\n // Firefox returns bad results (the position before the space)\n // when querying a position directly after line-broken\n // whitespace. Detect this situation and and kludge around it\n if (gecko && offset && /\\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {\n let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);\n if (rectBefore.top == rect.top) {\n let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);\n if (rectAfter.top != rect.top)\n return flattenV(rectAfter, rectAfter.left < rectBefore.left);\n }\n }\n return rect;\n }\n else {\n let from = offset, to = offset, takeSide = side < 0 ? 1 : -1;\n if (side < 0 && !offset) {\n to++;\n takeSide = -1;\n }\n else if (side >= 0 && offset == node.nodeValue.length) {\n from--;\n takeSide = 1;\n }\n else if (side < 0) {\n from--;\n }\n else {\n to++;\n }\n return flattenV(singleRect(textRange(node, from, to), takeSide), takeSide < 0);\n }\n }\n let $dom = view.state.doc.resolve(pos - (atom || 0));\n // Return a horizontal line in block context\n if (!$dom.parent.inlineContent) {\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n if (before.nodeType == 1)\n return flattenH(before.getBoundingClientRect(), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n if (after.nodeType == 1)\n return flattenH(after.getBoundingClientRect(), true);\n }\n return flattenH(node.getBoundingClientRect(), side >= 0);\n }\n // Inline, not in text node (this is not Bidi-safe)\n if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {\n let before = node.childNodes[offset - 1];\n let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1))\n // BR nodes tend to only return the rectangle before them.\n // Only use them if they are the last element in their parent\n : before.nodeType == 1 && (before.nodeName != \"BR\" || !before.nextSibling) ? before : null;\n if (target)\n return flattenV(singleRect(target, 1), false);\n }\n if (atom == null && offset < nodeSize(node)) {\n let after = node.childNodes[offset];\n while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)\n after = after.nextSibling;\n let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, (supportEmptyRange ? 0 : 1))\n : after.nodeType == 1 ? after : null;\n if (target)\n return flattenV(singleRect(target, -1), true);\n }\n // All else failed, just try to get a rectangle for the target node\n return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0);\n}\nfunction flattenV(rect, left) {\n if (rect.width == 0)\n return rect;\n let x = left ? rect.left : rect.right;\n return { top: rect.top, bottom: rect.bottom, left: x, right: x };\n}\nfunction flattenH(rect, top) {\n if (rect.height == 0)\n return rect;\n let y = top ? rect.top : rect.bottom;\n return { top: y, bottom: y, left: rect.left, right: rect.right };\n}\nfunction withFlushedState(view, state, f) {\n let viewState = view.state, active = view.root.activeElement;\n if (viewState != state)\n view.updateState(state);\n if (active != view.dom)\n view.focus();\n try {\n return f();\n }\n finally {\n if (viewState != state)\n view.updateState(viewState);\n if (active != view.dom && active)\n active.focus();\n }\n}\n// Whether vertical position motion in a given direction\n// from a position would leave a text block.\nfunction endOfTextblockVertical(view, state, dir) {\n let sel = state.selection;\n let $pos = dir == \"up\" ? sel.$from : sel.$to;\n return withFlushedState(view, state, () => {\n let { node: dom } = view.docView.domFromPos($pos.pos, dir == \"up\" ? -1 : 1);\n for (;;) {\n let nearest = view.docView.nearestDesc(dom, true);\n if (!nearest)\n break;\n if (nearest.node.isBlock) {\n dom = nearest.contentDOM || nearest.dom;\n break;\n }\n dom = nearest.dom.parentNode;\n }\n let coords = coordsAtPos(view, $pos.pos, 1);\n for (let child = dom.firstChild; child; child = child.nextSibling) {\n let boxes;\n if (child.nodeType == 1)\n boxes = child.getClientRects();\n else if (child.nodeType == 3)\n boxes = textRange(child, 0, child.nodeValue.length).getClientRects();\n else\n continue;\n for (let i = 0; i < boxes.length; i++) {\n let box = boxes[i];\n if (box.bottom > box.top + 1 &&\n (dir == \"up\" ? coords.top - box.top > (box.bottom - coords.top) * 2\n : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))\n return false;\n }\n }\n return true;\n });\n}\nconst maybeRTL = /[\\u0590-\\u08ac]/;\nfunction endOfTextblockHorizontal(view, state, dir) {\n let { $head } = state.selection;\n if (!$head.parent.isTextblock)\n return false;\n let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;\n let sel = view.domSelection();\n if (!sel)\n return $head.pos == $head.start() || $head.pos == $head.end();\n // If the textblock is all LTR, or the browser doesn't support\n // Selection.modify (Edge), fall back to a primitive approach\n if (!maybeRTL.test($head.parent.textContent) || !sel.modify)\n return dir == \"left\" || dir == \"backward\" ? atStart : atEnd;\n return withFlushedState(view, state, () => {\n // This is a huge hack, but appears to be the best we can\n // currently do: use `Selection.modify` to move the selection by\n // one character, and see if that moves the cursor out of the\n // textblock (or doesn't move it at all, when at the start/end of\n // the document).\n let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();\n let oldBidiLevel = sel.caretBidiLevel // Only for Firefox\n ;\n sel.modify(\"move\", dir, \"character\");\n let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;\n let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();\n let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) ||\n (oldNode == newNode && oldOff == newOff);\n // Restore the previous selection\n try {\n sel.collapse(anchorNode, anchorOffset);\n if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)\n sel.extend(oldNode, oldOff);\n }\n catch (_) { }\n if (oldBidiLevel != null)\n sel.caretBidiLevel = oldBidiLevel;\n return result;\n });\n}\nlet cachedState = null;\nlet cachedDir = null;\nlet cachedResult = false;\nfunction endOfTextblock(view, state, dir) {\n if (cachedState == state && cachedDir == dir)\n return cachedResult;\n cachedState = state;\n cachedDir = dir;\n return cachedResult = dir == \"up\" || dir == \"down\"\n ? endOfTextblockVertical(view, state, dir)\n : endOfTextblockHorizontal(view, state, dir);\n}\n\n// View descriptions are data structures that describe the DOM that is\n// used to represent the editor's content. They are used for:\n//\n// - Incremental redrawing when the document changes\n//\n// - Figuring out what part of the document a given DOM position\n// corresponds to\n//\n// - Wiring in custom implementations of the editing interface for a\n// given node\n//\n// They form a doubly-linked mutable tree, starting at `view.docView`.\nconst NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3;\n// Superclass for the various kinds of descriptions. Defines their\n// basic structure and shared methods.\nclass ViewDesc {\n constructor(parent, children, dom, \n // This is the node that holds the child views. It may be null for\n // descs that don't have children.\n contentDOM) {\n this.parent = parent;\n this.children = children;\n this.dom = dom;\n this.contentDOM = contentDOM;\n this.dirty = NOT_DIRTY;\n // An expando property on the DOM node provides a link back to its\n // description.\n dom.pmViewDesc = this;\n }\n // Used to check whether a given description corresponds to a\n // widget/mark/node.\n matchesWidget(widget) { return false; }\n matchesMark(mark) { return false; }\n matchesNode(node, outerDeco, innerDeco) { return false; }\n matchesHack(nodeName) { return false; }\n // When parsing in-editor content (in domchange.js), we allow\n // descriptions to determine the parse rules that should be used to\n // parse them.\n parseRule() { return null; }\n // Used by the editor's event handler to ignore events that come\n // from certain descs.\n stopEvent(event) { return false; }\n // The size of the content represented by this desc.\n get size() {\n let size = 0;\n for (let i = 0; i < this.children.length; i++)\n size += this.children[i].size;\n return size;\n }\n // For block nodes, this represents the space taken up by their\n // start/end tokens.\n get border() { return 0; }\n destroy() {\n this.parent = undefined;\n if (this.dom.pmViewDesc == this)\n this.dom.pmViewDesc = undefined;\n for (let i = 0; i < this.children.length; i++)\n this.children[i].destroy();\n }\n posBeforeChild(child) {\n for (let i = 0, pos = this.posAtStart;; i++) {\n let cur = this.children[i];\n if (cur == child)\n return pos;\n pos += cur.size;\n }\n }\n get posBefore() {\n return this.parent.posBeforeChild(this);\n }\n get posAtStart() {\n return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;\n }\n get posAfter() {\n return this.posBefore + this.size;\n }\n get posAtEnd() {\n return this.posAtStart + this.size - 2 * this.border;\n }\n localPosFromDOM(dom, offset, bias) {\n // If the DOM position is in the content, use the child desc after\n // it to figure out a position.\n if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {\n if (bias < 0) {\n let domBefore, desc;\n if (dom == this.contentDOM) {\n domBefore = dom.childNodes[offset - 1];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domBefore = dom.previousSibling;\n }\n while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))\n domBefore = domBefore.previousSibling;\n return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;\n }\n else {\n let domAfter, desc;\n if (dom == this.contentDOM) {\n domAfter = dom.childNodes[offset];\n }\n else {\n while (dom.parentNode != this.contentDOM)\n dom = dom.parentNode;\n domAfter = dom.nextSibling;\n }\n while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))\n domAfter = domAfter.nextSibling;\n return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;\n }\n }\n // Otherwise, use various heuristics, falling back on the bias\n // parameter, to determine whether to return the position at the\n // start or at the end of this view desc.\n let atEnd;\n if (dom == this.dom && this.contentDOM) {\n atEnd = offset > domIndex(this.contentDOM);\n }\n else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {\n atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;\n }\n else if (this.dom.firstChild) {\n if (offset == 0)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = false;\n break;\n }\n if (search.previousSibling)\n break;\n }\n if (atEnd == null && offset == dom.childNodes.length)\n for (let search = dom;; search = search.parentNode) {\n if (search == this.dom) {\n atEnd = true;\n break;\n }\n if (search.nextSibling)\n break;\n }\n }\n return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;\n }\n nearestDesc(dom, onlyNodes = false) {\n for (let first = true, cur = dom; cur; cur = cur.parentNode) {\n let desc = this.getDesc(cur), nodeDOM;\n if (desc && (!onlyNodes || desc.node)) {\n // If dom is outside of this desc's nodeDOM, don't count it.\n if (first && (nodeDOM = desc.nodeDOM) &&\n !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))\n first = false;\n else\n return desc;\n }\n }\n }\n getDesc(dom) {\n let desc = dom.pmViewDesc;\n for (let cur = desc; cur; cur = cur.parent)\n if (cur == this)\n return desc;\n }\n posFromDOM(dom, offset, bias) {\n for (let scan = dom; scan; scan = scan.parentNode) {\n let desc = this.getDesc(scan);\n if (desc)\n return desc.localPosFromDOM(dom, offset, bias);\n }\n return -1;\n }\n // Find the desc for the node after the given pos, if any. (When a\n // parent node overrode rendering, there might not be one.)\n descAt(pos) {\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == pos && end != offset) {\n while (!child.border && child.children.length) {\n for (let i = 0; i < child.children.length; i++) {\n let inner = child.children[i];\n if (inner.size) {\n child = inner;\n break;\n }\n }\n }\n return child;\n }\n if (pos < end)\n return child.descAt(pos - offset - child.border);\n offset = end;\n }\n }\n domFromPos(pos, side) {\n if (!this.contentDOM)\n return { node: this.dom, offset: 0, atom: pos + 1 };\n // First find the position in the child array\n let i = 0, offset = 0;\n for (let curPos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = curPos + child.size;\n if (end > pos || child instanceof TrailingHackViewDesc) {\n offset = pos - curPos;\n break;\n }\n curPos = end;\n }\n // If this points into the middle of a child, call through\n if (offset)\n return this.children[i].domFromPos(offset - this.children[i].border, side);\n // Go back if there were any zero-length widgets with side >= 0 before this point\n for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) { }\n // Scan towards the first useable node\n if (side <= 0) {\n let prev, enter = true;\n for (;; i--, enter = false) {\n prev = i ? this.children[i - 1] : null;\n if (!prev || prev.dom.parentNode == this.contentDOM)\n break;\n }\n if (prev && side && enter && !prev.border && !prev.domAtom)\n return prev.domFromPos(prev.size, side);\n return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };\n }\n else {\n let next, enter = true;\n for (;; i++, enter = false) {\n next = i < this.children.length ? this.children[i] : null;\n if (!next || next.dom.parentNode == this.contentDOM)\n break;\n }\n if (next && enter && !next.border && !next.domAtom)\n return next.domFromPos(0, side);\n return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };\n }\n }\n // Used to find a DOM range in a single parent for a given changed\n // range.\n parseRange(from, to, base = 0) {\n if (this.children.length == 0)\n return { node: this.contentDOM, from, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };\n let fromOffset = -1, toOffset = -1;\n for (let offset = base, i = 0;; i++) {\n let child = this.children[i], end = offset + child.size;\n if (fromOffset == -1 && from <= end) {\n let childBase = offset + child.border;\n // FIXME maybe descend mark views to parse a narrower range?\n if (from >= childBase && to <= end - child.border && child.node &&\n child.contentDOM && this.contentDOM.contains(child.contentDOM))\n return child.parseRange(from, to, childBase);\n from = offset;\n for (let j = i; j > 0; j--) {\n let prev = this.children[j - 1];\n if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {\n fromOffset = domIndex(prev.dom) + 1;\n break;\n }\n from -= prev.size;\n }\n if (fromOffset == -1)\n fromOffset = 0;\n }\n if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {\n to = end;\n for (let j = i + 1; j < this.children.length; j++) {\n let next = this.children[j];\n if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {\n toOffset = domIndex(next.dom);\n break;\n }\n to += next.size;\n }\n if (toOffset == -1)\n toOffset = this.contentDOM.childNodes.length;\n break;\n }\n offset = end;\n }\n return { node: this.contentDOM, from, to, fromOffset, toOffset };\n }\n emptyChildAt(side) {\n if (this.border || !this.contentDOM || !this.children.length)\n return false;\n let child = this.children[side < 0 ? 0 : this.children.length - 1];\n return child.size == 0 || child.emptyChildAt(side);\n }\n domAfterPos(pos) {\n let { node, offset } = this.domFromPos(pos, 0);\n if (node.nodeType != 1 || offset == node.childNodes.length)\n throw new RangeError(\"No node after pos \" + pos);\n return node.childNodes[offset];\n }\n // View descs are responsible for setting any selection that falls\n // entirely inside of them, so that custom implementations can do\n // custom things with the selection. Note that this falls apart when\n // a selection starts in such a node and ends in another, in which\n // case we just use whatever domFromPos produces as a best effort.\n setSelection(anchor, head, view, force = false) {\n // If the selection falls entirely in a child, give it to that child\n let from = Math.min(anchor, head), to = Math.max(anchor, head);\n for (let i = 0, offset = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (from > offset && to < end)\n return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);\n offset = end;\n }\n let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);\n let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);\n let domSel = view.root.getSelection();\n let selRange = view.domSelectionRange();\n let brKludge = false;\n // On Firefox, using Selection.collapse to put the cursor after a\n // BR node for some reason doesn't always work (#1073). On Safari,\n // the cursor sometimes inexplicable visually lags behind its\n // reported position in such situations (#1092).\n if ((gecko || safari) && anchor == head) {\n let { node, offset } = anchorDOM;\n if (node.nodeType == 3) {\n brKludge = !!(offset && node.nodeValue[offset - 1] == \"\\n\");\n // Issue #1128\n if (brKludge && offset == node.nodeValue.length) {\n for (let scan = node, after; scan; scan = scan.parentNode) {\n if (after = scan.nextSibling) {\n if (after.nodeName == \"BR\")\n anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };\n break;\n }\n let desc = scan.pmViewDesc;\n if (desc && desc.node && desc.node.isBlock)\n break;\n }\n }\n }\n else {\n let prev = node.childNodes[offset - 1];\n brKludge = prev && (prev.nodeName == \"BR\" || prev.contentEditable == \"false\");\n }\n }\n // Firefox can act strangely when the selection is in front of an\n // uneditable node. See #1163 and https://bugzilla.mozilla.org/show_bug.cgi?id=1709536\n if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {\n let after = selRange.focusNode.childNodes[selRange.focusOffset];\n if (after && after.contentEditable == \"false\")\n force = true;\n }\n if (!(force || brKludge && safari) &&\n isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) &&\n isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))\n return;\n // Selection.extend can be used to create an 'inverted' selection\n // (one where the focus is before the anchor), but not all\n // browsers support it yet.\n let domSelExtended = false;\n if ((domSel.extend || anchor == head) && !(brKludge && gecko)) {\n domSel.collapse(anchorDOM.node, anchorDOM.offset);\n try {\n if (anchor != head)\n domSel.extend(headDOM.node, headDOM.offset);\n domSelExtended = true;\n }\n catch (_) {\n // In some cases with Chrome the selection is empty after calling\n // collapse, even when it should be valid. This appears to be a bug, but\n // it is difficult to isolate. If this happens fallback to the old path\n // without using extend.\n // Similarly, this could crash on Safari if the editor is hidden, and\n // there was no selection.\n }\n }\n if (!domSelExtended) {\n if (anchor > head) {\n let tmp = anchorDOM;\n anchorDOM = headDOM;\n headDOM = tmp;\n }\n let range = document.createRange();\n range.setEnd(headDOM.node, headDOM.offset);\n range.setStart(anchorDOM.node, anchorDOM.offset);\n domSel.removeAllRanges();\n domSel.addRange(range);\n }\n }\n ignoreMutation(mutation) {\n return !this.contentDOM && mutation.type != \"selection\";\n }\n get contentLost() {\n return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);\n }\n // Remove a subtree of the element tree that has been touched\n // by a DOM change, so that the next update will redraw it.\n markDirty(from, to) {\n for (let offset = 0, i = 0; i < this.children.length; i++) {\n let child = this.children[i], end = offset + child.size;\n if (offset == end ? from <= end && to >= offset : from < end && to > offset) {\n let startInside = offset + child.border, endInside = end - child.border;\n if (from >= startInside && to <= endInside) {\n this.dirty = from == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;\n if (from == startInside && to == endInside &&\n (child.contentLost || child.dom.parentNode != this.contentDOM))\n child.dirty = NODE_DIRTY;\n else\n child.markDirty(from - startInside, to - startInside);\n return;\n }\n else {\n child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length\n ? CONTENT_DIRTY : NODE_DIRTY;\n }\n }\n offset = end;\n }\n this.dirty = CONTENT_DIRTY;\n }\n markParentsDirty() {\n let level = 1;\n for (let node = this.parent; node; node = node.parent, level++) {\n let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;\n if (node.dirty < dirty)\n node.dirty = dirty;\n }\n }\n get domAtom() { return false; }\n get ignoreForCoords() { return false; }\n get ignoreForSelection() { return false; }\n isText(text) { return false; }\n}\n// A widget desc represents a widget decoration, which is a DOM node\n// drawn between the document nodes.\nclass WidgetViewDesc extends ViewDesc {\n constructor(parent, widget, view, pos) {\n let self, dom = widget.type.toDOM;\n if (typeof dom == \"function\")\n dom = dom(view, () => {\n if (!self)\n return pos;\n if (self.parent)\n return self.parent.posBeforeChild(self);\n });\n if (!widget.type.spec.raw) {\n if (dom.nodeType != 1) {\n let wrap = document.createElement(\"span\");\n wrap.appendChild(dom);\n dom = wrap;\n }\n dom.contentEditable = \"false\";\n dom.classList.add(\"ProseMirror-widget\");\n }\n super(parent, [], dom, null);\n this.widget = widget;\n this.widget = widget;\n self = this;\n }\n matchesWidget(widget) {\n return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);\n }\n parseRule() { return { ignore: true }; }\n stopEvent(event) {\n let stop = this.widget.spec.stopEvent;\n return stop ? stop(event) : false;\n }\n ignoreMutation(mutation) {\n return mutation.type != \"selection\" || this.widget.spec.ignoreSelection;\n }\n destroy() {\n this.widget.type.destroy(this.dom);\n super.destroy();\n }\n get domAtom() { return true; }\n get ignoreForSelection() { return !!this.widget.type.spec.relaxedSide; }\n get side() { return this.widget.type.side; }\n}\nclass CompositionViewDesc extends ViewDesc {\n constructor(parent, dom, textDOM, text) {\n super(parent, [], dom, null);\n this.textDOM = textDOM;\n this.text = text;\n }\n get size() { return this.text.length; }\n localPosFromDOM(dom, offset) {\n if (dom != this.textDOM)\n return this.posAtStart + (offset ? this.size : 0);\n return this.posAtStart + offset;\n }\n domFromPos(pos) {\n return { node: this.textDOM, offset: pos };\n }\n ignoreMutation(mut) {\n return mut.type === 'characterData' && mut.target.nodeValue == mut.oldValue;\n }\n}\n// A mark desc represents a mark. May have multiple children,\n// depending on how the mark is split. Note that marks are drawn using\n// a fixed nesting order, for simplicity and predictability, so in\n// some cases they will be split more often than would appear\n// necessary.\nclass MarkViewDesc extends ViewDesc {\n constructor(parent, mark, dom, contentDOM, spec) {\n super(parent, [], dom, contentDOM);\n this.mark = mark;\n this.spec = spec;\n }\n static create(parent, mark, inline, view) {\n let custom = view.nodeViews[mark.type.name];\n let spec = custom && custom(mark, view, inline);\n if (!spec || !spec.dom)\n spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);\n return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);\n }\n parseRule() {\n if ((this.dirty & NODE_DIRTY) || this.mark.type.spec.reparseInView)\n return null;\n return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };\n }\n matchesMark(mark) { return this.dirty != NODE_DIRTY && this.mark.eq(mark); }\n markDirty(from, to) {\n super.markDirty(from, to);\n // Move dirty info to nearest node view\n if (this.dirty != NOT_DIRTY) {\n let parent = this.parent;\n while (!parent.node)\n parent = parent.parent;\n if (parent.dirty < this.dirty)\n parent.dirty = this.dirty;\n this.dirty = NOT_DIRTY;\n }\n }\n slice(from, to, view) {\n let copy = MarkViewDesc.create(this.parent, this.mark, true, view);\n let nodes = this.children, size = this.size;\n if (to < size)\n nodes = replaceNodes(nodes, to, size, view);\n if (from > 0)\n nodes = replaceNodes(nodes, 0, from, view);\n for (let i = 0; i < nodes.length; i++)\n nodes[i].parent = copy;\n copy.children = nodes;\n return copy;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n}\n// Node view descs are the main, most common type of view desc, and\n// correspond to an actual node in the document. Unlike mark descs,\n// they populate their child array themselves.\nclass NodeViewDesc extends ViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {\n super(parent, [], dom, contentDOM);\n this.node = node;\n this.outerDeco = outerDeco;\n this.innerDeco = innerDeco;\n this.nodeDOM = nodeDOM;\n }\n // By default, a node is rendered using the `toDOM` method from the\n // node type spec. But client code can use the `nodeViews` spec to\n // supply a custom node view, which can influence various aspects of\n // the way the node works.\n //\n // (Using subclassing for this was intentionally decided against,\n // since it'd require exposing a whole slew of finicky\n // implementation details to the user code that they probably will\n // never need.)\n static create(parent, node, outerDeco, innerDeco, view, pos) {\n let custom = view.nodeViews[node.type.name], descObj;\n let spec = custom && custom(node, view, () => {\n // (This is a function that allows the custom view to find its\n // own position)\n if (!descObj)\n return pos;\n if (descObj.parent)\n return descObj.parent.posBeforeChild(descObj);\n }, outerDeco, innerDeco);\n let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;\n if (node.isText) {\n if (!dom)\n dom = document.createTextNode(node.text);\n else if (dom.nodeType != 3)\n throw new RangeError(\"Text must be rendered as a DOM text node\");\n }\n else if (!dom) {\n let spec = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);\n ({ dom, contentDOM } = spec);\n }\n if (!contentDOM && !node.isText && dom.nodeName != \"BR\") { // Chrome gets confused by
      \n if (!dom.hasAttribute(\"contenteditable\"))\n dom.contentEditable = \"false\";\n if (node.type.spec.draggable)\n dom.draggable = true;\n }\n let nodeDOM = dom;\n dom = applyOuterDeco(dom, outerDeco, node);\n if (spec)\n return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);\n else if (node.isText)\n return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view);\n else\n return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);\n }\n parseRule() {\n // Experimental kludge to allow opt-in re-parsing of nodes\n if (this.node.type.spec.reparseInView)\n return null;\n // FIXME the assumption that this can always return the current\n // attrs means that if the user somehow manages to change the\n // attrs in the dom, that won't be picked up. Not entirely sure\n // whether this is a problem\n let rule = { node: this.node.type.name, attrs: this.node.attrs };\n if (this.node.type.whitespace == \"pre\")\n rule.preserveWhitespace = \"full\";\n if (!this.contentDOM) {\n rule.getContent = () => this.node.content;\n }\n else if (!this.contentLost) {\n rule.contentElement = this.contentDOM;\n }\n else {\n // Chrome likes to randomly recreate parent nodes when\n // backspacing things. When that happens, this tries to find the\n // new parent.\n for (let i = this.children.length - 1; i >= 0; i--) {\n let child = this.children[i];\n if (this.dom.contains(child.dom.parentNode)) {\n rule.contentElement = child.dom.parentNode;\n break;\n }\n }\n if (!rule.contentElement)\n rule.getContent = () => Fragment.empty;\n }\n return rule;\n }\n matchesNode(node, outerDeco, innerDeco) {\n return this.dirty == NOT_DIRTY && node.eq(this.node) &&\n sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);\n }\n get size() { return this.node.nodeSize; }\n get border() { return this.node.isLeaf ? 0 : 1; }\n // Syncs `this.children` to match `this.node.content` and the local\n // decorations, possibly introducing nesting for marks. Then, in a\n // separate step, syncs the DOM inside `this.contentDOM` to\n // `this.children`.\n updateChildren(view, pos) {\n let inline = this.node.inlineContent, off = pos;\n let composition = view.composing ? this.localCompositionInfo(view, pos) : null;\n let localComposition = composition && composition.pos > -1 ? composition : null;\n let compositionInChild = composition && composition.pos < 0;\n let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);\n iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {\n if (widget.spec.marks)\n updater.syncToMarks(widget.spec.marks, inline, view, i);\n else if (widget.type.side >= 0 && !insideNode)\n updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i);\n // If the next node is a desc matching this widget, reuse it,\n // otherwise insert the widget as a new view desc.\n updater.placeWidget(widget, view, off);\n }, (child, outerDeco, innerDeco, i) => {\n // Make sure the wrapping mark descs match the node's marks.\n updater.syncToMarks(child.marks, inline, view, i);\n // Try several strategies for drawing this node\n let compIndex;\n if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;\n else if (compositionInChild && view.state.selection.from > off &&\n view.state.selection.to < off + child.nodeSize &&\n (compIndex = updater.findIndexWithChild(composition.node)) > -1 &&\n updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;\n else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;\n else {\n // Add it as a new view\n updater.addNode(child, outerDeco, innerDeco, view, off);\n }\n off += child.nodeSize;\n });\n // Drop all remaining descs after the current position.\n updater.syncToMarks([], inline, view, 0);\n if (this.node.isTextblock)\n updater.addTextblockHacks();\n updater.destroyRest();\n // Sync the DOM if anything changed\n if (updater.changed || this.dirty == CONTENT_DIRTY) {\n // May have to protect focused DOM from being changed if a composition is active\n if (localComposition)\n this.protectLocalComposition(view, localComposition);\n renderDescs(this.contentDOM, this.children, view);\n if (ios)\n iosHacks(this.dom);\n }\n }\n localCompositionInfo(view, pos) {\n // Only do something if both the selection and a focused text node\n // are inside of this node\n let { from, to } = view.state.selection;\n if (!(view.state.selection instanceof TextSelection) || from < pos || to > pos + this.node.content.size)\n return null;\n let textNode = view.input.compositionNode;\n if (!textNode || !this.dom.contains(textNode.parentNode))\n return null;\n if (this.node.inlineContent) {\n // Find the text in the focused node in the node, stop if it's not\n // there (may have been modified through other means, in which\n // case it should overwritten)\n let text = textNode.nodeValue;\n let textPos = findTextInFragment(this.node.content, text, from - pos, to - pos);\n return textPos < 0 ? null : { node: textNode, pos: textPos, text };\n }\n else {\n return { node: textNode, pos: -1, text: \"\" };\n }\n }\n protectLocalComposition(view, { node, pos, text }) {\n // The node is already part of a local view desc, leave it there\n if (this.getDesc(node))\n return;\n // Create a composition view for the orphaned nodes\n let topNode = node;\n for (;; topNode = topNode.parentNode) {\n if (topNode.parentNode == this.contentDOM)\n break;\n while (topNode.previousSibling)\n topNode.parentNode.removeChild(topNode.previousSibling);\n while (topNode.nextSibling)\n topNode.parentNode.removeChild(topNode.nextSibling);\n if (topNode.pmViewDesc)\n topNode.pmViewDesc = undefined;\n }\n let desc = new CompositionViewDesc(this, topNode, node, text);\n view.input.compositionNodes.push(desc);\n // Patch up this.children to contain the composition view\n this.children = replaceNodes(this.children, pos, pos + text.length, view, desc);\n }\n // If this desc must be updated to match the given node decoration,\n // do so and return true.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY ||\n !node.sameMarkup(this.node))\n return false;\n this.updateInner(node, outerDeco, innerDeco, view);\n return true;\n }\n updateInner(node, outerDeco, innerDeco, view) {\n this.updateOuterDeco(outerDeco);\n this.node = node;\n this.innerDeco = innerDeco;\n if (this.contentDOM)\n this.updateChildren(view, this.posAtStart);\n this.dirty = NOT_DIRTY;\n }\n updateOuterDeco(outerDeco) {\n if (sameOuterDeco(outerDeco, this.outerDeco))\n return;\n let needsWrap = this.nodeDOM.nodeType != 1;\n let oldDOM = this.dom;\n this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));\n if (this.dom != oldDOM) {\n oldDOM.pmViewDesc = undefined;\n this.dom.pmViewDesc = this;\n }\n this.outerDeco = outerDeco;\n }\n // Mark this node as being the selected node.\n selectNode() {\n if (this.nodeDOM.nodeType == 1) {\n this.nodeDOM.classList.add(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.nodeDOM.draggable = true;\n }\n }\n // Remove selected node marking from this node.\n deselectNode() {\n if (this.nodeDOM.nodeType == 1) {\n this.nodeDOM.classList.remove(\"ProseMirror-selectednode\");\n if (this.contentDOM || !this.node.type.spec.draggable)\n this.nodeDOM.removeAttribute(\"draggable\");\n }\n }\n get domAtom() { return this.node.isAtom; }\n}\n// Create a view desc for the top-level document node, to be exported\n// and used by the view class.\nfunction docViewDesc(doc, outerDeco, innerDeco, dom, view) {\n applyOuterDeco(dom, outerDeco, doc);\n let docView = new NodeViewDesc(undefined, doc, outerDeco, innerDeco, dom, dom, dom, view, 0);\n if (docView.contentDOM)\n docView.updateChildren(view, 0);\n return docView;\n}\nclass TextViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {\n super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);\n }\n parseRule() {\n let skip = this.nodeDOM.parentNode;\n while (skip && skip != this.dom && !skip.pmIsDeco)\n skip = skip.parentNode;\n return { skip: (skip || true) };\n }\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY || (this.dirty != NOT_DIRTY && !this.inParent()) ||\n !node.sameMarkup(this.node))\n return false;\n this.updateOuterDeco(outerDeco);\n if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {\n this.nodeDOM.nodeValue = node.text;\n if (view.trackWrites == this.nodeDOM)\n view.trackWrites = null;\n }\n this.node = node;\n this.dirty = NOT_DIRTY;\n return true;\n }\n inParent() {\n let parentDOM = this.parent.contentDOM;\n for (let n = this.nodeDOM; n; n = n.parentNode)\n if (n == parentDOM)\n return true;\n return false;\n }\n domFromPos(pos) {\n return { node: this.nodeDOM, offset: pos };\n }\n localPosFromDOM(dom, offset, bias) {\n if (dom == this.nodeDOM)\n return this.posAtStart + Math.min(offset, this.node.text.length);\n return super.localPosFromDOM(dom, offset, bias);\n }\n ignoreMutation(mutation) {\n return mutation.type != \"characterData\" && mutation.type != \"selection\";\n }\n slice(from, to, view) {\n let node = this.node.cut(from, to), dom = document.createTextNode(node.text);\n return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);\n }\n markDirty(from, to) {\n super.markDirty(from, to);\n if (this.dom != this.nodeDOM && (from == 0 || to == this.nodeDOM.nodeValue.length))\n this.dirty = NODE_DIRTY;\n }\n get domAtom() { return false; }\n isText(text) { return this.node.text == text; }\n}\n// A dummy desc used to tag trailing BR or IMG nodes created to work\n// around contentEditable terribleness.\nclass TrailingHackViewDesc extends ViewDesc {\n parseRule() { return { ignore: true }; }\n matchesHack(nodeName) { return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; }\n get domAtom() { return true; }\n get ignoreForCoords() { return this.dom.nodeName == \"IMG\"; }\n}\n// A separate subclass is used for customized node views, so that the\n// extra checks only have to be made for nodes that are actually\n// customized.\nclass CustomNodeViewDesc extends NodeViewDesc {\n constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {\n super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);\n this.spec = spec;\n }\n // A custom `update` method gets to decide whether the update goes\n // through. If it does, and there's a `contentDOM` node, our logic\n // updates the children.\n update(node, outerDeco, innerDeco, view) {\n if (this.dirty == NODE_DIRTY)\n return false;\n if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {\n let result = this.spec.update(node, outerDeco, innerDeco);\n if (result)\n this.updateInner(node, outerDeco, innerDeco, view);\n return result;\n }\n else if (!this.contentDOM && !node.isLeaf) {\n return false;\n }\n else {\n return super.update(node, outerDeco, innerDeco, view);\n }\n }\n selectNode() {\n this.spec.selectNode ? this.spec.selectNode() : super.selectNode();\n }\n deselectNode() {\n this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();\n }\n setSelection(anchor, head, view, force) {\n this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root)\n : super.setSelection(anchor, head, view, force);\n }\n destroy() {\n if (this.spec.destroy)\n this.spec.destroy();\n super.destroy();\n }\n stopEvent(event) {\n return this.spec.stopEvent ? this.spec.stopEvent(event) : false;\n }\n ignoreMutation(mutation) {\n return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);\n }\n}\n// Sync the content of the given DOM node with the nodes associated\n// with the given array of view descs, recursing into mark descs\n// because this should sync the subtree for a whole node at a time.\nfunction renderDescs(parentDOM, descs, view) {\n let dom = parentDOM.firstChild, written = false;\n for (let i = 0; i < descs.length; i++) {\n let desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) {\n dom = rm(dom);\n written = true;\n }\n dom = dom.nextSibling;\n }\n else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n let pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) {\n dom = rm(dom);\n written = true;\n }\n if (written && view.trackWrites == parentDOM)\n view.trackWrites = null;\n}\nconst OuterDecoLevel = function (nodeName) {\n if (nodeName)\n this.nodeName = nodeName;\n};\nOuterDecoLevel.prototype = Object.create(null);\nconst noDeco = [new OuterDecoLevel];\nfunction computeOuterDeco(outerDeco, node, needsWrap) {\n if (outerDeco.length == 0)\n return noDeco;\n let top = needsWrap ? noDeco[0] : new OuterDecoLevel, result = [top];\n for (let i = 0; i < outerDeco.length; i++) {\n let attrs = outerDeco[i].type.attrs;\n if (!attrs)\n continue;\n if (attrs.nodeName)\n result.push(top = new OuterDecoLevel(attrs.nodeName));\n for (let name in attrs) {\n let val = attrs[name];\n if (val == null)\n continue;\n if (needsWrap && result.length == 1)\n result.push(top = new OuterDecoLevel(node.isInline ? \"span\" : \"div\"));\n if (name == \"class\")\n top.class = (top.class ? top.class + \" \" : \"\") + val;\n else if (name == \"style\")\n top.style = (top.style ? top.style + \";\" : \"\") + val;\n else if (name != \"nodeName\")\n top[name] = val;\n }\n }\n return result;\n}\nfunction patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {\n // Shortcut for trivial case\n if (prevComputed == noDeco && curComputed == noDeco)\n return nodeDOM;\n let curDOM = nodeDOM;\n for (let i = 0; i < curComputed.length; i++) {\n let deco = curComputed[i], prev = prevComputed[i];\n if (i) {\n let parent;\n if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM &&\n (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {\n curDOM = parent;\n }\n else {\n parent = document.createElement(deco.nodeName);\n parent.pmIsDeco = true;\n parent.appendChild(curDOM);\n prev = noDeco[0];\n curDOM = parent;\n }\n }\n patchAttributes(curDOM, prev || noDeco[0], deco);\n }\n return curDOM;\n}\nfunction patchAttributes(dom, prev, cur) {\n for (let name in prev)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && !(name in cur))\n dom.removeAttribute(name);\n for (let name in cur)\n if (name != \"class\" && name != \"style\" && name != \"nodeName\" && cur[name] != prev[name])\n dom.setAttribute(name, cur[name]);\n if (prev.class != cur.class) {\n let prevList = prev.class ? prev.class.split(\" \").filter(Boolean) : [];\n let curList = cur.class ? cur.class.split(\" \").filter(Boolean) : [];\n for (let i = 0; i < prevList.length; i++)\n if (curList.indexOf(prevList[i]) == -1)\n dom.classList.remove(prevList[i]);\n for (let i = 0; i < curList.length; i++)\n if (prevList.indexOf(curList[i]) == -1)\n dom.classList.add(curList[i]);\n if (dom.classList.length == 0)\n dom.removeAttribute(\"class\");\n }\n if (prev.style != cur.style) {\n if (prev.style) {\n let prop = /\\s*([\\w\\-\\xa1-\\uffff]+)\\s*:(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|\\(.*?\\)|[^;])*/g, m;\n while (m = prop.exec(prev.style))\n dom.style.removeProperty(m[1]);\n }\n if (cur.style)\n dom.style.cssText += cur.style;\n }\n}\nfunction applyOuterDeco(dom, deco, node) {\n return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));\n}\nfunction sameOuterDeco(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!a[i].type.eq(b[i].type))\n return false;\n return true;\n}\n// Remove a DOM node and return its next sibling.\nfunction rm(dom) {\n let next = dom.nextSibling;\n dom.parentNode.removeChild(dom);\n return next;\n}\n// Helper class for incrementally updating a tree of mark descs and\n// the widget and node descs inside of them.\nclass ViewTreeUpdater {\n constructor(top, lock, view) {\n this.lock = lock;\n this.view = view;\n // Index into `this.top`'s child array, represents the current\n // update position.\n this.index = 0;\n // When entering a mark, the current top and index are pushed\n // onto this.\n this.stack = [];\n // Tracks whether anything was changed\n this.changed = false;\n this.top = top;\n this.preMatch = preMatch(top.node.content, top);\n }\n // Destroy and remove the children between the given indices in\n // `this.top`.\n destroyBetween(start, end) {\n if (start == end)\n return;\n for (let i = start; i < end; i++)\n this.top.children[i].destroy();\n this.top.children.splice(start, end - start);\n this.changed = true;\n }\n // Destroy all remaining children in `this.top`.\n destroyRest() {\n this.destroyBetween(this.index, this.top.children.length);\n }\n // Sync the current stack of mark descs with the given array of\n // marks, reusing existing mark descs when possible.\n syncToMarks(marks, inline, view, parentIndex) {\n let keep = 0, depth = this.stack.length >> 1;\n let maxKeep = Math.min(depth, marks.length);\n while (keep < maxKeep &&\n (keep == depth - 1 ? this.top : this.stack[(keep + 1) << 1])\n .matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)\n keep++;\n while (keep < depth) {\n this.destroyRest();\n this.top.dirty = NOT_DIRTY;\n this.index = this.stack.pop();\n this.top = this.stack.pop();\n depth--;\n }\n while (depth < marks.length) {\n this.stack.push(this.top, this.index + 1);\n let found = -1, scanTo = this.top.children.length;\n if (parentIndex < this.preMatch.index)\n scanTo = Math.min(this.index + 3, scanTo);\n for (let i = this.index; i < scanTo; i++) {\n let next = this.top.children[i];\n if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {\n found = i;\n break;\n }\n }\n if (found > -1) {\n if (found > this.index) {\n this.changed = true;\n this.destroyBetween(this.index, found);\n }\n this.top = this.top.children[this.index];\n }\n else {\n let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);\n this.top.children.splice(this.index, 0, markDesc);\n this.top = markDesc;\n this.changed = true;\n }\n this.index = 0;\n depth++;\n }\n }\n // Try to find a node desc matching the given data. Skip over it and\n // return true when successful.\n findNodeMatch(node, outerDeco, innerDeco, index) {\n let found = -1, targetDesc;\n if (index >= this.preMatch.index &&\n (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top &&\n targetDesc.matchesNode(node, outerDeco, innerDeco)) {\n found = this.top.children.indexOf(targetDesc, this.index);\n }\n else {\n for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {\n let child = this.top.children[i];\n if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {\n found = i;\n break;\n }\n }\n }\n if (found < 0)\n return false;\n this.destroyBetween(this.index, found);\n this.index++;\n return true;\n }\n updateNodeAt(node, outerDeco, innerDeco, index, view) {\n let child = this.top.children[index];\n if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)\n child.dirty = CONTENT_DIRTY;\n if (!child.update(node, outerDeco, innerDeco, view))\n return false;\n this.destroyBetween(this.index, index);\n this.index++;\n return true;\n }\n findIndexWithChild(domNode) {\n for (;;) {\n let parent = domNode.parentNode;\n if (!parent)\n return -1;\n if (parent == this.top.contentDOM) {\n let desc = domNode.pmViewDesc;\n if (desc)\n for (let i = this.index; i < this.top.children.length; i++) {\n if (this.top.children[i] == desc)\n return i;\n }\n return -1;\n }\n domNode = parent;\n }\n }\n // Try to update the next node, if any, to the given data. Checks\n // pre-matches to avoid overwriting nodes that could still be used.\n updateNextNode(node, outerDeco, innerDeco, view, index, pos) {\n for (let i = this.index; i < this.top.children.length; i++) {\n let next = this.top.children[i];\n if (next instanceof NodeViewDesc) {\n let preMatch = this.preMatch.matched.get(next);\n if (preMatch != null && preMatch != index)\n return false;\n let nextDOM = next.dom, updated;\n // Can't update if nextDOM is or contains this.lock, except if\n // it's a text node whose content already matches the new text\n // and whose decorations match the new ones.\n let locked = this.isLocked(nextDOM) &&\n !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text &&\n next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));\n if (!locked && next.update(node, outerDeco, innerDeco, view)) {\n this.destroyBetween(this.index, i);\n if (next.dom != nextDOM)\n this.changed = true;\n this.index++;\n return true;\n }\n else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {\n this.destroyBetween(this.index, i);\n this.top.children[this.index] = updated;\n if (updated.contentDOM) {\n updated.dirty = CONTENT_DIRTY;\n updated.updateChildren(view, pos + 1);\n updated.dirty = NOT_DIRTY;\n }\n this.changed = true;\n this.index++;\n return true;\n }\n break;\n }\n }\n return false;\n }\n // When a node with content is replaced by a different node with\n // identical content, move over its children.\n recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {\n if (next.dirty || node.isAtom || !next.children.length ||\n !next.node.content.eq(node.content) ||\n !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))\n return null;\n let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (wrapper.contentDOM) {\n wrapper.children = next.children;\n next.children = [];\n for (let ch of wrapper.children)\n ch.parent = wrapper;\n }\n next.destroy();\n return wrapper;\n }\n // Insert the node as a newly created node desc.\n addNode(node, outerDeco, innerDeco, view, pos) {\n let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);\n if (desc.contentDOM)\n desc.updateChildren(view, pos + 1);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n placeWidget(widget, view, pos) {\n let next = this.index < this.top.children.length ? this.top.children[this.index] : null;\n if (next && next.matchesWidget(widget) &&\n (widget == next.widget || !next.widget.type.toDOM.parentNode)) {\n this.index++;\n }\n else {\n let desc = new WidgetViewDesc(this.top, widget, view, pos);\n this.top.children.splice(this.index++, 0, desc);\n this.changed = true;\n }\n }\n // Make sure a textblock looks and behaves correctly in\n // contentEditable.\n addTextblockHacks() {\n let lastChild = this.top.children[this.index - 1], parent = this.top;\n while (lastChild instanceof MarkViewDesc) {\n parent = lastChild;\n lastChild = parent.children[parent.children.length - 1];\n }\n if (!lastChild || // Empty textblock\n !(lastChild instanceof TextViewDesc) ||\n /\\n$/.test(lastChild.node.text) ||\n (this.view.requiresGeckoHackNode && /\\s$/.test(lastChild.node.text))) {\n // Avoid bugs in Safari's cursor drawing (#1165) and Chrome's mouse selection (#1152)\n if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == \"false\")\n this.addHackNode(\"IMG\", parent);\n this.addHackNode(\"BR\", this.top);\n }\n }\n addHackNode(nodeName, parent) {\n if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {\n this.index++;\n }\n else {\n let dom = document.createElement(nodeName);\n if (nodeName == \"IMG\") {\n dom.className = \"ProseMirror-separator\";\n dom.alt = \"\";\n }\n if (nodeName == \"BR\")\n dom.className = \"ProseMirror-trailingBreak\";\n let hack = new TrailingHackViewDesc(this.top, [], dom, null);\n if (parent != this.top)\n parent.children.push(hack);\n else\n parent.children.splice(this.index++, 0, hack);\n this.changed = true;\n }\n }\n isLocked(node) {\n return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode));\n }\n}\n// Iterate from the end of the fragment and array of descs to find\n// directly matching ones, in order to avoid overeagerly reusing those\n// for other nodes.\nfunction preMatch(frag, parentDesc) {\n let curDesc = parentDesc, descI = curDesc.children.length;\n let fI = frag.childCount, matched = new Map, matches = [];\n outer: while (fI > 0) {\n let desc;\n for (;;) {\n if (descI) {\n let next = curDesc.children[descI - 1];\n if (next instanceof MarkViewDesc) {\n curDesc = next;\n descI = next.children.length;\n }\n else {\n desc = next;\n descI--;\n break;\n }\n }\n else if (curDesc == parentDesc) {\n break outer;\n }\n else {\n descI = curDesc.parent.children.indexOf(curDesc);\n curDesc = curDesc.parent;\n }\n }\n let node = desc.node;\n if (!node)\n continue;\n if (node != frag.child(fI - 1))\n break;\n --fI;\n matched.set(desc, fI);\n matches.push(desc);\n }\n return { index: fI, matched, matches: matches.reverse() };\n}\nfunction compareSide(a, b) {\n return a.type.side - b.type.side;\n}\n// This function abstracts iterating over the nodes and decorations in\n// a fragment. Calls `onNode` for each node, with its local and child\n// decorations. Splits text nodes when there is a decoration starting\n// or ending inside of them. Calls `onWidget` for each widget.\nfunction iterDeco(parent, deco, onWidget, onNode) {\n let locals = deco.locals(parent), offset = 0;\n // Simple, cheap variant for when there are no local decorations\n if (locals.length == 0) {\n for (let i = 0; i < parent.childCount; i++) {\n let child = parent.child(i);\n onNode(child, locals, deco.forChild(offset, child), i);\n offset += child.nodeSize;\n }\n return;\n }\n let decoIndex = 0, active = [], restNode = null;\n for (let parentIndex = 0;;) {\n let widget, widgets;\n while (decoIndex < locals.length && locals[decoIndex].to == offset) {\n let next = locals[decoIndex++];\n if (next.widget) {\n if (!widget)\n widget = next;\n else\n (widgets || (widgets = [widget])).push(next);\n }\n }\n if (widget) {\n if (widgets) {\n widgets.sort(compareSide);\n for (let i = 0; i < widgets.length; i++)\n onWidget(widgets[i], parentIndex, !!restNode);\n }\n else {\n onWidget(widget, parentIndex, !!restNode);\n }\n }\n let child, index;\n if (restNode) {\n index = -1;\n child = restNode;\n restNode = null;\n }\n else if (parentIndex < parent.childCount) {\n index = parentIndex;\n child = parent.child(parentIndex++);\n }\n else {\n break;\n }\n for (let i = 0; i < active.length; i++)\n if (active[i].to <= offset)\n active.splice(i--, 1);\n while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)\n active.push(locals[decoIndex++]);\n let end = offset + child.nodeSize;\n if (child.isText) {\n let cutAt = end;\n if (decoIndex < locals.length && locals[decoIndex].from < cutAt)\n cutAt = locals[decoIndex].from;\n for (let i = 0; i < active.length; i++)\n if (active[i].to < cutAt)\n cutAt = active[i].to;\n if (cutAt < end) {\n restNode = child.cut(cutAt - offset);\n child = child.cut(0, cutAt - offset);\n end = cutAt;\n index = -1;\n }\n }\n else {\n while (decoIndex < locals.length && locals[decoIndex].to < end)\n decoIndex++;\n }\n let outerDeco = child.isInline && !child.isLeaf ? active.filter(d => !d.inline) : active.slice();\n onNode(child, outerDeco, deco.forChild(offset, child), index);\n offset = end;\n }\n}\n// List markers in Mobile Safari will mysteriously disappear\n// sometimes. This works around that.\nfunction iosHacks(dom) {\n if (dom.nodeName == \"UL\" || dom.nodeName == \"OL\") {\n let oldCSS = dom.style.cssText;\n dom.style.cssText = oldCSS + \"; list-style: square !important\";\n window.getComputedStyle(dom).listStyle;\n dom.style.cssText = oldCSS;\n }\n}\n// Find a piece of text in an inline fragment, overlapping from-to\nfunction findTextInFragment(frag, text, from, to) {\n for (let i = 0, pos = 0; i < frag.childCount && pos <= to;) {\n let child = frag.child(i++), childStart = pos;\n pos += child.nodeSize;\n if (!child.isText)\n continue;\n let str = child.text;\n while (i < frag.childCount) {\n let next = frag.child(i++);\n pos += next.nodeSize;\n if (!next.isText)\n break;\n str += next.text;\n }\n if (pos >= from) {\n if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text)\n return to - text.length;\n let found = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1;\n if (found >= 0 && found + text.length + childStart >= from)\n return childStart + found;\n if (from == to && str.length >= (to + text.length) - childStart &&\n str.slice(to - childStart, to - childStart + text.length) == text)\n return to;\n }\n }\n return -1;\n}\n// Replace range from-to in an array of view descs with replacement\n// (may be null to just delete). This goes very much against the grain\n// of the rest of this code, which tends to create nodes with the\n// right shape in one go, rather than messing with them after\n// creation, but is necessary in the composition hack.\nfunction replaceNodes(nodes, from, to, view, replacement) {\n let result = [];\n for (let i = 0, off = 0; i < nodes.length; i++) {\n let child = nodes[i], start = off, end = off += child.size;\n if (start >= to || end <= from) {\n result.push(child);\n }\n else {\n if (start < from)\n result.push(child.slice(0, from - start, view));\n if (replacement) {\n result.push(replacement);\n replacement = undefined;\n }\n if (end > to)\n result.push(child.slice(to - start, child.size, view));\n }\n }\n return result;\n}\n\nfunction selectionFromDOM(view, origin = null) {\n let domSel = view.domSelectionRange(), doc = view.state.doc;\n if (!domSel.focusNode)\n return null;\n let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;\n let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);\n if (head < 0)\n return null;\n let $head = doc.resolve(head), anchor, selection;\n if (selectionCollapsed(domSel)) {\n anchor = head;\n while (nearestDesc && !nearestDesc.node)\n nearestDesc = nearestDesc.parent;\n let nearestDescNode = nearestDesc.node;\n if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent\n && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {\n let pos = nearestDesc.posBefore;\n selection = new NodeSelection(head == pos ? $head : doc.resolve(pos));\n }\n }\n else {\n if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {\n let min = head, max = head;\n for (let i = 0; i < domSel.rangeCount; i++) {\n let range = domSel.getRangeAt(i);\n min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));\n max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));\n }\n if (min < 0)\n return null;\n [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];\n $head = doc.resolve(head);\n }\n else {\n anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);\n }\n if (anchor < 0)\n return null;\n }\n let $anchor = doc.resolve(anchor);\n if (!selection) {\n let bias = origin == \"pointer\" || (view.state.selection.head < $head.pos && !inWidget) ? 1 : -1;\n selection = selectionBetween(view, $anchor, $head, bias);\n }\n return selection;\n}\nfunction editorOwnsSelection(view) {\n return view.editable ? view.hasFocus() :\n hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);\n}\nfunction selectionToDOM(view, force = false) {\n let sel = view.state.selection;\n syncNodeSelection(view, sel);\n if (!editorOwnsSelection(view))\n return;\n // The delayed drag selection causes issues with Cell Selections\n // in Safari. And the drag selection delay is to workarond issues\n // which only present in Chrome.\n if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) {\n let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;\n if (domSel.anchorNode && curSel.anchorNode &&\n isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {\n view.input.mouseDown.delayedSelectionSync = true;\n view.domObserver.setCurSelection();\n return;\n }\n }\n view.domObserver.disconnectSelection();\n if (view.cursorWrapper) {\n selectCursorWrapper(view);\n }\n else {\n let { anchor, head } = sel, resetEditableFrom, resetEditableTo;\n if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {\n if (!sel.$from.parent.inlineContent)\n resetEditableFrom = temporarilyEditableNear(view, sel.from);\n if (!sel.empty && !sel.$from.parent.inlineContent)\n resetEditableTo = temporarilyEditableNear(view, sel.to);\n }\n view.docView.setSelection(anchor, head, view, force);\n if (brokenSelectBetweenUneditable) {\n if (resetEditableFrom)\n resetEditable(resetEditableFrom);\n if (resetEditableTo)\n resetEditable(resetEditableTo);\n }\n if (sel.visible) {\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }\n else {\n view.dom.classList.add(\"ProseMirror-hideselection\");\n if (\"onselectionchange\" in document)\n removeClassOnSelectionChange(view);\n }\n }\n view.domObserver.setCurSelection();\n view.domObserver.connectSelection();\n}\n// Kludge to work around Webkit not allowing a selection to start/end\n// between non-editable block nodes. We briefly make something\n// editable, set the selection, then set it uneditable again.\nconst brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;\nfunction temporarilyEditableNear(view, pos) {\n let { node, offset } = view.docView.domFromPos(pos, 0);\n let after = offset < node.childNodes.length ? node.childNodes[offset] : null;\n let before = offset ? node.childNodes[offset - 1] : null;\n if (safari && after && after.contentEditable == \"false\")\n return setEditable(after);\n if ((!after || after.contentEditable == \"false\") &&\n (!before || before.contentEditable == \"false\")) {\n if (after)\n return setEditable(after);\n else if (before)\n return setEditable(before);\n }\n}\nfunction setEditable(element) {\n element.contentEditable = \"true\";\n if (safari && element.draggable) {\n element.draggable = false;\n element.wasDraggable = true;\n }\n return element;\n}\nfunction resetEditable(element) {\n element.contentEditable = \"false\";\n if (element.wasDraggable) {\n element.draggable = true;\n element.wasDraggable = null;\n }\n}\nfunction removeClassOnSelectionChange(view) {\n let doc = view.dom.ownerDocument;\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n let domSel = view.domSelectionRange();\n let node = domSel.anchorNode, offset = domSel.anchorOffset;\n doc.addEventListener(\"selectionchange\", view.input.hideSelectionGuard = () => {\n if (domSel.anchorNode != node || domSel.anchorOffset != offset) {\n doc.removeEventListener(\"selectionchange\", view.input.hideSelectionGuard);\n setTimeout(() => {\n if (!editorOwnsSelection(view) || view.state.selection.visible)\n view.dom.classList.remove(\"ProseMirror-hideselection\");\n }, 20);\n }\n });\n}\nfunction selectCursorWrapper(view) {\n let domSel = view.domSelection();\n if (!domSel)\n return;\n let node = view.cursorWrapper.dom, img = node.nodeName == \"IMG\";\n if (img)\n domSel.collapse(node.parentNode, domIndex(node) + 1);\n else\n domSel.collapse(node, 0);\n // Kludge to kill 'control selection' in IE11 when selecting an\n // invisible cursor wrapper, since that would result in those weird\n // resize handles and a selection that considers the absolutely\n // positioned wrapper, rather than the root editable node, the\n // focused element.\n if (!img && !view.state.selection.visible && ie && ie_version <= 11) {\n node.disabled = true;\n node.disabled = false;\n }\n}\nfunction syncNodeSelection(view, sel) {\n if (sel instanceof NodeSelection) {\n let desc = view.docView.descAt(sel.from);\n if (desc != view.lastSelectedViewDesc) {\n clearNodeSelection(view);\n if (desc)\n desc.selectNode();\n view.lastSelectedViewDesc = desc;\n }\n }\n else {\n clearNodeSelection(view);\n }\n}\n// Clear all DOM statefulness of the last node selection.\nfunction clearNodeSelection(view) {\n if (view.lastSelectedViewDesc) {\n if (view.lastSelectedViewDesc.parent)\n view.lastSelectedViewDesc.deselectNode();\n view.lastSelectedViewDesc = undefined;\n }\n}\nfunction selectionBetween(view, $anchor, $head, bias) {\n return view.someProp(\"createSelectionBetween\", f => f(view, $anchor, $head))\n || TextSelection.between($anchor, $head, bias);\n}\nfunction hasFocusAndSelection(view) {\n if (view.editable && !view.hasFocus())\n return false;\n return hasSelection(view);\n}\nfunction hasSelection(view) {\n let sel = view.domSelectionRange();\n if (!sel.anchorNode)\n return false;\n try {\n // Firefox will raise 'permission denied' errors when accessing\n // properties of `sel.anchorNode` when it's in a generated CSS\n // element.\n return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) &&\n (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));\n }\n catch (_) {\n return false;\n }\n}\nfunction anchorInRightPlace(view) {\n let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);\n let domSel = view.domSelectionRange();\n return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);\n}\n\nfunction moveSelectionBlock(state, dir) {\n let { $anchor, $head } = state.selection;\n let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);\n let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;\n return $start && Selection.findFrom($start, dir);\n}\nfunction apply(view, sel) {\n view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());\n return true;\n}\nfunction selectHorizontally(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection) {\n if (mods.indexOf(\"s\") > -1) {\n let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;\n if (!node || node.isText || !node.isLeaf)\n return false;\n let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));\n return apply(view, new TextSelection(sel.$anchor, $newHead));\n }\n else if (!sel.empty) {\n return false;\n }\n else if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n return false;\n }\n else if (!(mac && mods.indexOf(\"m\") > -1)) {\n let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;\n if (!node || node.isText)\n return false;\n let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;\n if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))\n return false;\n if (NodeSelection.isSelectable(node)) {\n return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));\n }\n else if (webkit) {\n // Chrome and Safari will introduce extra pointless cursor\n // positions around inline uneditable nodes, so we have to\n // take over and move the cursor past them (#937)\n return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));\n }\n else {\n return false;\n }\n }\n }\n else if (sel instanceof NodeSelection && sel.node.isInline) {\n return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));\n }\n else {\n let next = moveSelectionBlock(view.state, dir);\n if (next)\n return apply(view, next);\n return false;\n }\n}\nfunction nodeLen(node) {\n return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;\n}\nfunction isIgnorable(dom, dir) {\n let desc = dom.pmViewDesc;\n return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != \"BR\");\n}\nfunction skipIgnoredNodes(view, dir) {\n return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);\n}\n// Make sure the cursor isn't directly after one or more ignored\n// nodes, which will confuse the browser's cursor motion logic.\nfunction skipIgnoredNodesBefore(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let moveNode, moveOffset, force = false;\n // Gecko will do odd things when the selection is directly in front\n // of a non-editable node, so in that case, move it into the next\n // node if possible. Issue prosemirror/prosemirror#832.\n if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1))\n force = true;\n for (;;) {\n if (offset > 0) {\n if (node.nodeType != 1) {\n break;\n }\n else {\n let before = node.childNodes[offset - 1];\n if (isIgnorable(before, -1)) {\n moveNode = node;\n moveOffset = --offset;\n }\n else if (before.nodeType == 3) {\n node = before;\n offset = node.nodeValue.length;\n }\n else\n break;\n }\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let prev = node.previousSibling;\n while (prev && isIgnorable(prev, -1)) {\n moveNode = node.parentNode;\n moveOffset = domIndex(prev);\n prev = prev.previousSibling;\n }\n if (!prev) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = 0;\n }\n else {\n node = prev;\n offset = nodeLen(node);\n }\n }\n }\n if (force)\n setSelFocus(view, node, offset);\n else if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\n// Make sure the cursor isn't directly before one or more ignored\n// nodes.\nfunction skipIgnoredNodesAfter(view) {\n let sel = view.domSelectionRange();\n let node = sel.focusNode, offset = sel.focusOffset;\n if (!node)\n return;\n let len = nodeLen(node);\n let moveNode, moveOffset;\n for (;;) {\n if (offset < len) {\n if (node.nodeType != 1)\n break;\n let after = node.childNodes[offset];\n if (isIgnorable(after, 1)) {\n moveNode = node;\n moveOffset = ++offset;\n }\n else\n break;\n }\n else if (isBlockNode(node)) {\n break;\n }\n else {\n let next = node.nextSibling;\n while (next && isIgnorable(next, 1)) {\n moveNode = next.parentNode;\n moveOffset = domIndex(next) + 1;\n next = next.nextSibling;\n }\n if (!next) {\n node = node.parentNode;\n if (node == view.dom)\n break;\n offset = len = 0;\n }\n else {\n node = next;\n offset = 0;\n len = nodeLen(node);\n }\n }\n }\n if (moveNode)\n setSelFocus(view, moveNode, moveOffset);\n}\nfunction isBlockNode(dom) {\n let desc = dom.pmViewDesc;\n return desc && desc.node && desc.node.isBlock;\n}\nfunction textNodeAfter(node, offset) {\n while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {\n offset = domIndex(node) + 1;\n node = node.parentNode;\n }\n while (node && offset < node.childNodes.length) {\n let next = node.childNodes[offset];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = 0;\n }\n}\nfunction textNodeBefore(node, offset) {\n while (node && !offset && !hasBlockDesc(node)) {\n offset = domIndex(node);\n node = node.parentNode;\n }\n while (node && offset) {\n let next = node.childNodes[offset - 1];\n if (next.nodeType == 3)\n return next;\n if (next.nodeType == 1 && next.contentEditable == \"false\")\n break;\n node = next;\n offset = node.childNodes.length;\n }\n}\nfunction setSelFocus(view, node, offset) {\n if (node.nodeType != 3) {\n let before, after;\n if (after = textNodeAfter(node, offset)) {\n node = after;\n offset = 0;\n }\n else if (before = textNodeBefore(node, offset)) {\n node = before;\n offset = before.nodeValue.length;\n }\n }\n let sel = view.domSelection();\n if (!sel)\n return;\n if (selectionCollapsed(sel)) {\n let range = document.createRange();\n range.setEnd(node, offset);\n range.setStart(node, offset);\n sel.removeAllRanges();\n sel.addRange(range);\n }\n else if (sel.extend) {\n sel.extend(node, offset);\n }\n view.domObserver.setCurSelection();\n let { state } = view;\n // If no state update ends up happening, reset the selection.\n setTimeout(() => {\n if (view.state == state)\n selectionToDOM(view);\n }, 50);\n}\nfunction findDirection(view, pos) {\n let $pos = view.state.doc.resolve(pos);\n if (!(chrome || windows) && $pos.parent.inlineContent) {\n let coords = view.coordsAtPos(pos);\n if (pos > $pos.start()) {\n let before = view.coordsAtPos(pos - 1);\n let mid = (before.top + before.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)\n return before.left < coords.left ? \"ltr\" : \"rtl\";\n }\n if (pos < $pos.end()) {\n let after = view.coordsAtPos(pos + 1);\n let mid = (after.top + after.bottom) / 2;\n if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)\n return after.left > coords.left ? \"ltr\" : \"rtl\";\n }\n }\n let computed = getComputedStyle(view.dom).direction;\n return computed == \"rtl\" ? \"rtl\" : \"ltr\";\n}\n// Check whether vertical selection motion would involve node\n// selections. If so, apply it (if not, the result is left to the\n// browser)\nfunction selectVertically(view, dir, mods) {\n let sel = view.state.selection;\n if (sel instanceof TextSelection && !sel.empty || mods.indexOf(\"s\") > -1)\n return false;\n if (mac && mods.indexOf(\"m\") > -1)\n return false;\n let { $from, $to } = sel;\n if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? \"up\" : \"down\")) {\n let next = moveSelectionBlock(view.state, dir);\n if (next && (next instanceof NodeSelection))\n return apply(view, next);\n }\n if (!$from.parent.inlineContent) {\n let side = dir < 0 ? $from : $to;\n let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);\n return beyond ? apply(view, beyond) : false;\n }\n return false;\n}\nfunction stopNativeHorizontalDelete(view, dir) {\n if (!(view.state.selection instanceof TextSelection))\n return true;\n let { $head, $anchor, empty } = view.state.selection;\n if (!$head.sameParent($anchor))\n return true;\n if (!empty)\n return false;\n if (view.endOfTextblock(dir > 0 ? \"forward\" : \"backward\"))\n return true;\n let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);\n if (nextNode && !nextNode.isText) {\n let tr = view.state.tr;\n if (dir < 0)\n tr.delete($head.pos - nextNode.nodeSize, $head.pos);\n else\n tr.delete($head.pos, $head.pos + nextNode.nodeSize);\n view.dispatch(tr);\n return true;\n }\n return false;\n}\nfunction switchEditable(view, node, state) {\n view.domObserver.stop();\n node.contentEditable = state;\n view.domObserver.start();\n}\n// Issue #867 / #1090 / https://bugs.chromium.org/p/chromium/issues/detail?id=903821\n// In which Safari (and at some point in the past, Chrome) does really\n// wrong things when the down arrow is pressed when the cursor is\n// directly at the start of a textblock and has an uneditable node\n// after it\nfunction safariDownArrowBug(view) {\n if (!safari || view.state.selection.$head.parentOffset > 0)\n return false;\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 &&\n focusNode.firstChild && focusNode.firstChild.contentEditable == \"false\") {\n let child = focusNode.firstChild;\n switchEditable(view, child, \"true\");\n setTimeout(() => switchEditable(view, child, \"false\"), 20);\n }\n return false;\n}\n// A backdrop key mapping used to make sure we always suppress keys\n// that have a dangerous default effect, even if the commands they are\n// bound to return false, and to make sure that cursor-motion keys\n// find a cursor (as opposed to a node selection) when pressed. For\n// cursor-motion keys, the code in the handlers also takes care of\n// block selections.\nfunction getMods(event) {\n let result = \"\";\n if (event.ctrlKey)\n result += \"c\";\n if (event.metaKey)\n result += \"m\";\n if (event.altKey)\n result += \"a\";\n if (event.shiftKey)\n result += \"s\";\n return result;\n}\nfunction captureKeyDown(view, event) {\n let code = event.keyCode, mods = getMods(event);\n if (code == 8 || (mac && code == 72 && mods == \"c\")) { // Backspace, Ctrl-h on Mac\n return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);\n }\n else if ((code == 46 && !event.shiftKey) || (mac && code == 68 && mods == \"c\")) { // Delete, Ctrl-d on Mac\n return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);\n }\n else if (code == 13 || code == 27) { // Enter, Esc\n return true;\n }\n else if (code == 37 || (mac && code == 66 && mods == \"c\")) { // Left arrow, Ctrl-b on Mac\n let dir = code == 37 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? -1 : 1) : -1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 39 || (mac && code == 70 && mods == \"c\")) { // Right arrow, Ctrl-f on Mac\n let dir = code == 39 ? (findDirection(view, view.state.selection.from) == \"ltr\" ? 1 : -1) : 1;\n return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);\n }\n else if (code == 38 || (mac && code == 80 && mods == \"c\")) { // Up arrow, Ctrl-p on Mac\n return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);\n }\n else if (code == 40 || (mac && code == 78 && mods == \"c\")) { // Down arrow, Ctrl-n on Mac\n return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);\n }\n else if (mods == (mac ? \"m\" : \"c\") &&\n (code == 66 || code == 73 || code == 89 || code == 90)) { // Mod-[biyz]\n return true;\n }\n return false;\n}\n\nfunction serializeForClipboard(view, slice) {\n view.someProp(\"transformCopied\", f => { slice = f(slice, view); });\n let context = [], { content, openStart, openEnd } = slice;\n while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {\n openStart--;\n openEnd--;\n let node = content.firstChild;\n context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);\n content = node.content;\n }\n let serializer = view.someProp(\"clipboardSerializer\") || DOMSerializer.fromSchema(view.state.schema);\n let doc = detachedDoc(), wrap = doc.createElement(\"div\");\n wrap.appendChild(serializer.serializeFragment(content, { document: doc }));\n let firstChild = wrap.firstChild, needsWrap, wrappers = 0;\n while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {\n for (let i = needsWrap.length - 1; i >= 0; i--) {\n let wrapper = doc.createElement(needsWrap[i]);\n while (wrap.firstChild)\n wrapper.appendChild(wrap.firstChild);\n wrap.appendChild(wrapper);\n wrappers++;\n }\n firstChild = wrap.firstChild;\n }\n if (firstChild && firstChild.nodeType == 1)\n firstChild.setAttribute(\"data-pm-slice\", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : \"\"} ${JSON.stringify(context)}`);\n let text = view.someProp(\"clipboardTextSerializer\", f => f(slice, view)) ||\n slice.content.textBetween(0, slice.content.size, \"\\n\\n\");\n return { dom: wrap, text, slice };\n}\n// Read a slice of content from the clipboard (or drop data).\nfunction parseFromClipboard(view, text, html, plainText, $context) {\n let inCode = $context.parent.type.spec.code;\n let dom, slice;\n if (!html && !text)\n return null;\n let asText = !!text && (plainText || inCode || !html);\n if (asText) {\n view.someProp(\"transformPastedText\", f => { text = f(text, inCode || plainText, view); });\n if (inCode) {\n slice = new Slice(Fragment.from(view.state.schema.text(text.replace(/\\r\\n?/g, \"\\n\"))), 0, 0);\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, true); });\n return slice;\n }\n let parsed = view.someProp(\"clipboardTextParser\", f => f(text, $context, plainText, view));\n if (parsed) {\n slice = parsed;\n }\n else {\n let marks = $context.marks();\n let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);\n dom = document.createElement(\"div\");\n text.split(/(?:\\r\\n?|\\n)+/).forEach(block => {\n let p = dom.appendChild(document.createElement(\"p\"));\n if (block)\n p.appendChild(serializer.serializeNode(schema.text(block, marks)));\n });\n }\n }\n else {\n view.someProp(\"transformPastedHTML\", f => { html = f(html, view); });\n dom = readHTML(html);\n if (webkit)\n restoreReplacedSpaces(dom);\n }\n let contextNode = dom && dom.querySelector(\"[data-pm-slice]\");\n let sliceData = contextNode && /^(\\d+) (\\d+)(?: -(\\d+))? (.*)/.exec(contextNode.getAttribute(\"data-pm-slice\") || \"\");\n if (sliceData && sliceData[3])\n for (let i = +sliceData[3]; i > 0; i--) {\n let child = dom.firstChild;\n while (child && child.nodeType != 1)\n child = child.nextSibling;\n if (!child)\n break;\n dom = child;\n }\n if (!slice) {\n let parser = view.someProp(\"clipboardParser\") || view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n slice = parser.parseSlice(dom, {\n preserveWhitespace: !!(asText || sliceData),\n context: $context,\n ruleFromNode(dom) {\n if (dom.nodeName == \"BR\" && !dom.nextSibling &&\n dom.parentNode && !inlineParents.test(dom.parentNode.nodeName))\n return { ignore: true };\n return null;\n }\n });\n }\n if (sliceData) {\n slice = addContext(closeSlice(slice, +sliceData[1], +sliceData[2]), sliceData[4]);\n }\n else { // HTML wasn't created by ProseMirror. Make sure top-level siblings are coherent\n slice = Slice.maxOpen(normalizeSiblings(slice.content, $context), true);\n if (slice.openStart || slice.openEnd) {\n let openStart = 0, openEnd = 0;\n for (let node = slice.content.firstChild; openStart < slice.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { }\n for (let node = slice.content.lastChild; openEnd < slice.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { }\n slice = closeSlice(slice, openStart, openEnd);\n }\n }\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, asText); });\n return slice;\n}\nconst inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;\n// Takes a slice parsed with parseSlice, which means there hasn't been\n// any content-expression checking done on the top nodes, tries to\n// find a parent node in the current context that might fit the nodes,\n// and if successful, rebuilds the slice so that it fits into that parent.\n//\n// This addresses the problem that Transform.replace expects a\n// coherent slice, and will fail to place a set of siblings that don't\n// fit anywhere in the schema.\nfunction normalizeSiblings(fragment, $context) {\n if (fragment.childCount < 2)\n return fragment;\n for (let d = $context.depth; d >= 0; d--) {\n let parent = $context.node(d);\n let match = parent.contentMatchAt($context.index(d));\n let lastWrap, result = [];\n fragment.forEach(node => {\n if (!result)\n return;\n let wrap = match.findWrapping(node.type), inLast;\n if (!wrap)\n return result = null;\n if (inLast = result.length && lastWrap.length && addToSibling(wrap, lastWrap, node, result[result.length - 1], 0)) {\n result[result.length - 1] = inLast;\n }\n else {\n if (result.length)\n result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);\n let wrapped = withWrappers(node, wrap);\n result.push(wrapped);\n match = match.matchType(wrapped.type);\n lastWrap = wrap;\n }\n });\n if (result)\n return Fragment.from(result);\n }\n return fragment;\n}\nfunction withWrappers(node, wrap, from = 0) {\n for (let i = wrap.length - 1; i >= from; i--)\n node = wrap[i].create(null, Fragment.from(node));\n return node;\n}\n// Used to group adjacent nodes wrapped in similar parents by\n// normalizeSiblings into the same parent node\nfunction addToSibling(wrap, lastWrap, node, sibling, depth) {\n if (depth < wrap.length && depth < lastWrap.length && wrap[depth] == lastWrap[depth]) {\n let inner = addToSibling(wrap, lastWrap, node, sibling.lastChild, depth + 1);\n if (inner)\n return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));\n let match = sibling.contentMatchAt(sibling.childCount);\n if (match.matchType(depth == wrap.length - 1 ? node.type : wrap[depth + 1]))\n return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap, depth + 1))));\n }\n}\nfunction closeRight(node, depth) {\n if (depth == 0)\n return node;\n let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));\n let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);\n return node.copy(fragment.append(fill));\n}\nfunction closeRange(fragment, side, from, to, depth, openEnd) {\n let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content;\n if (fragment.childCount > 1)\n openEnd = 0;\n if (depth < to - 1)\n inner = closeRange(inner, side, from, to, depth + 1, openEnd);\n if (depth >= from)\n inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner)\n : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));\n return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner));\n}\nfunction closeSlice(slice, openStart, openEnd) {\n if (openStart < slice.openStart)\n slice = new Slice(closeRange(slice.content, -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd);\n if (openEnd < slice.openEnd)\n slice = new Slice(closeRange(slice.content, 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd);\n return slice;\n}\n// Trick from jQuery -- some elements must be wrapped in other\n// elements for innerHTML to work. I.e. if you do `div.innerHTML =\n// \"..\"` the table cells are ignored.\nconst wrapMap = {\n thead: [\"table\"],\n tbody: [\"table\"],\n tfoot: [\"table\"],\n caption: [\"table\"],\n colgroup: [\"table\"],\n col: [\"table\", \"colgroup\"],\n tr: [\"table\", \"tbody\"],\n td: [\"table\", \"tbody\", \"tr\"],\n th: [\"table\", \"tbody\", \"tr\"]\n};\nlet _detachedDoc = null;\nfunction detachedDoc() {\n return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument(\"title\"));\n}\nlet _policy = null;\nfunction maybeWrapTrusted(html) {\n let trustedTypes = window.trustedTypes;\n if (!trustedTypes)\n return html;\n // With the require-trusted-types-for CSP, Chrome will block\n // innerHTML, even on a detached document. This wraps the string in\n // a way that makes the browser allow us to use its parser again.\n if (!_policy)\n _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy(\"ProseMirrorClipboard\", { createHTML: (s) => s });\n return _policy.createHTML(html);\n}\nfunction readHTML(html) {\n let metas = /^(\\s*]*>)*/.exec(html);\n if (metas)\n html = html.slice(metas[0].length);\n let elt = detachedDoc().createElement(\"div\");\n let firstTag = /<([a-z][^>\\s]+)/i.exec(html), wrap;\n if (wrap = firstTag && wrapMap[firstTag[1].toLowerCase()])\n html = wrap.map(n => \"<\" + n + \">\").join(\"\") + html + wrap.map(n => \"\").reverse().join(\"\");\n elt.innerHTML = maybeWrapTrusted(html);\n if (wrap)\n for (let i = 0; i < wrap.length; i++)\n elt = elt.querySelector(wrap[i]) || elt;\n return elt;\n}\n// Webkit browsers do some hard-to-predict replacement of regular\n// spaces with non-breaking spaces when putting content on the\n// clipboard. This tries to convert such non-breaking spaces (which\n// will be wrapped in a plain span on Chrome, a span with class\n// Apple-converted-space on Safari) back to regular spaces.\nfunction restoreReplacedSpaces(dom) {\n let nodes = dom.querySelectorAll(chrome ? \"span:not([class]):not([style])\" : \"span.Apple-converted-space\");\n for (let i = 0; i < nodes.length; i++) {\n let node = nodes[i];\n if (node.childNodes.length == 1 && node.textContent == \"\\u00a0\" && node.parentNode)\n node.parentNode.replaceChild(dom.ownerDocument.createTextNode(\" \"), node);\n }\n}\nfunction addContext(slice, context) {\n if (!slice.size)\n return slice;\n let schema = slice.content.firstChild.type.schema, array;\n try {\n array = JSON.parse(context);\n }\n catch (e) {\n return slice;\n }\n let { content, openStart, openEnd } = slice;\n for (let i = array.length - 2; i >= 0; i -= 2) {\n let type = schema.nodes[array[i]];\n if (!type || type.hasRequiredAttrs())\n break;\n content = Fragment.from(type.create(array[i + 1], content));\n openStart++;\n openEnd++;\n }\n return new Slice(content, openStart, openEnd);\n}\n\n// A collection of DOM events that occur within the editor, and callback functions\n// to invoke when the event fires.\nconst handlers = {};\nconst editHandlers = {};\nconst passiveHandlers = { touchstart: true, touchmove: true };\nclass InputState {\n constructor() {\n this.shiftKey = false;\n this.mouseDown = null;\n this.lastKeyCode = null;\n this.lastKeyCodeTime = 0;\n this.lastClick = { time: 0, x: 0, y: 0, type: \"\", button: 0 };\n this.lastSelectionOrigin = null;\n this.lastSelectionTime = 0;\n this.lastIOSEnter = 0;\n this.lastIOSEnterFallbackTimeout = -1;\n this.lastFocus = 0;\n this.lastTouch = 0;\n this.lastChromeDelete = 0;\n this.composing = false;\n this.compositionNode = null;\n this.composingTimeout = -1;\n this.compositionNodes = [];\n this.compositionEndedAt = -2e8;\n this.compositionID = 1;\n this.badSafariComposition = false;\n // Set to a composition ID when there are pending changes at compositionend\n this.compositionPendingChanges = 0;\n this.domChangeCount = 0;\n this.eventHandlers = Object.create(null);\n this.hideSelectionGuard = null;\n }\n}\nfunction initInput(view) {\n for (let event in handlers) {\n let handler = handlers[event];\n view.dom.addEventListener(event, view.input.eventHandlers[event] = (event) => {\n if (eventBelongsToView(view, event) && !runCustomHandler(view, event) &&\n (view.editable || !(event.type in editHandlers)))\n handler(view, event);\n }, passiveHandlers[event] ? { passive: true } : undefined);\n }\n // On Safari, for reasons beyond my understanding, adding an input\n // event handler makes an issue where the composition vanishes when\n // you press enter go away.\n if (safari)\n view.dom.addEventListener(\"input\", () => null);\n ensureListeners(view);\n}\nfunction setSelectionOrigin(view, origin) {\n view.input.lastSelectionOrigin = origin;\n view.input.lastSelectionTime = Date.now();\n}\nfunction destroyInput(view) {\n view.domObserver.stop();\n for (let type in view.input.eventHandlers)\n view.dom.removeEventListener(type, view.input.eventHandlers[type]);\n clearTimeout(view.input.composingTimeout);\n clearTimeout(view.input.lastIOSEnterFallbackTimeout);\n}\nfunction ensureListeners(view) {\n view.someProp(\"handleDOMEvents\", currentHandlers => {\n for (let type in currentHandlers)\n if (!view.input.eventHandlers[type])\n view.dom.addEventListener(type, view.input.eventHandlers[type] = event => runCustomHandler(view, event));\n });\n}\nfunction runCustomHandler(view, event) {\n return view.someProp(\"handleDOMEvents\", handlers => {\n let handler = handlers[event.type];\n return handler ? handler(view, event) || event.defaultPrevented : false;\n });\n}\nfunction eventBelongsToView(view, event) {\n if (!event.bubbles)\n return true;\n if (event.defaultPrevented)\n return false;\n for (let node = event.target; node != view.dom; node = node.parentNode)\n if (!node || node.nodeType == 11 ||\n (node.pmViewDesc && node.pmViewDesc.stopEvent(event)))\n return false;\n return true;\n}\nfunction dispatchEvent(view, event) {\n if (!runCustomHandler(view, event) && handlers[event.type] &&\n (view.editable || !(event.type in editHandlers)))\n handlers[event.type](view, event);\n}\neditHandlers.keydown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.keyCode == 16 || event.shiftKey;\n if (inOrNearComposition(view, event))\n return;\n view.input.lastKeyCode = event.keyCode;\n view.input.lastKeyCodeTime = Date.now();\n // Suppress enter key events on Chrome Android, because those tend\n // to be part of a confused sequence of composition events fired,\n // and handling them eagerly tends to corrupt the input.\n if (android && chrome && event.keyCode == 13)\n return;\n if (event.keyCode != 229)\n view.domObserver.forceFlush();\n // On iOS, if we preventDefault enter key presses, the virtual\n // keyboard gets confused. So the hack here is to set a flag that\n // makes the DOM change code recognize that what just happens should\n // be replaced by whatever the Enter key handlers do.\n if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {\n let now = Date.now();\n view.input.lastIOSEnter = now;\n view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {\n if (view.input.lastIOSEnter == now) {\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")));\n view.input.lastIOSEnter = 0;\n }\n }, 200);\n }\n else if (view.someProp(\"handleKeyDown\", f => f(view, event)) || captureKeyDown(view, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"key\");\n }\n};\neditHandlers.keyup = (view, event) => {\n if (event.keyCode == 16)\n view.input.shiftKey = false;\n};\neditHandlers.keypress = (view, _event) => {\n let event = _event;\n if (inOrNearComposition(view, event) || !event.charCode ||\n event.ctrlKey && !event.altKey || mac && event.metaKey)\n return;\n if (view.someProp(\"handleKeyPress\", f => f(view, event))) {\n event.preventDefault();\n return;\n }\n let sel = view.state.selection;\n if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {\n let text = String.fromCharCode(event.charCode);\n let deflt = () => view.state.tr.insertText(text).scrollIntoView();\n if (!/[\\r\\n]/.test(text) && !view.someProp(\"handleTextInput\", f => f(view, sel.$from.pos, sel.$to.pos, text, deflt)))\n view.dispatch(deflt());\n event.preventDefault();\n }\n};\nfunction eventCoords(event) { return { left: event.clientX, top: event.clientY }; }\nfunction isNear(event, click) {\n let dx = click.x - event.clientX, dy = click.y - event.clientY;\n return dx * dx + dy * dy < 100;\n}\nfunction runHandlerOnContext(view, propName, pos, inside, event) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n if (view.someProp(propName, f => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true)\n : f(view, pos, $pos.node(i), $pos.before(i), event, false)))\n return true;\n }\n return false;\n}\nfunction updateSelection(view, selection, origin) {\n if (!view.focused)\n view.focus();\n if (view.state.selection.eq(selection))\n return;\n let tr = view.state.tr.setSelection(selection);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n view.dispatch(tr);\n}\nfunction selectClickedLeaf(view, inside) {\n if (inside == -1)\n return false;\n let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;\n if (node && node.isAtom && NodeSelection.isSelectable(node)) {\n updateSelection(view, new NodeSelection($pos), \"pointer\");\n return true;\n }\n return false;\n}\nfunction selectClickedNode(view, inside) {\n if (inside == -1)\n return false;\n let sel = view.state.selection, selectedNode, selectAt;\n if (sel instanceof NodeSelection)\n selectedNode = sel.node;\n let $pos = view.state.doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n if (NodeSelection.isSelectable(node)) {\n if (selectedNode && sel.$from.depth > 0 &&\n i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)\n selectAt = $pos.before(sel.$from.depth);\n else\n selectAt = $pos.before(i);\n break;\n }\n }\n if (selectAt != null) {\n updateSelection(view, NodeSelection.create(view.state.doc, selectAt), \"pointer\");\n return true;\n }\n else {\n return false;\n }\n}\nfunction handleSingleClick(view, pos, inside, event, selectNode) {\n return runHandlerOnContext(view, \"handleClickOn\", pos, inside, event) ||\n view.someProp(\"handleClick\", f => f(view, pos, event)) ||\n (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));\n}\nfunction handleDoubleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleDoubleClickOn\", pos, inside, event) ||\n view.someProp(\"handleDoubleClick\", f => f(view, pos, event));\n}\nfunction handleTripleClick(view, pos, inside, event) {\n return runHandlerOnContext(view, \"handleTripleClickOn\", pos, inside, event) ||\n view.someProp(\"handleTripleClick\", f => f(view, pos, event)) ||\n defaultTripleClick(view, inside, event);\n}\nfunction defaultTripleClick(view, inside, event) {\n if (event.button != 0)\n return false;\n let doc = view.state.doc;\n if (inside == -1) {\n if (doc.inlineContent) {\n updateSelection(view, TextSelection.create(doc, 0, doc.content.size), \"pointer\");\n return true;\n }\n return false;\n }\n let $pos = doc.resolve(inside);\n for (let i = $pos.depth + 1; i > 0; i--) {\n let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);\n let nodePos = $pos.before(i);\n if (node.inlineContent)\n updateSelection(view, TextSelection.create(doc, nodePos + 1, nodePos + 1 + node.content.size), \"pointer\");\n else if (NodeSelection.isSelectable(node))\n updateSelection(view, NodeSelection.create(doc, nodePos), \"pointer\");\n else\n continue;\n return true;\n }\n}\nfunction forceDOMFlush(view) {\n return endComposition(view);\n}\nconst selectNodeModifier = mac ? \"metaKey\" : \"ctrlKey\";\nhandlers.mousedown = (view, _event) => {\n let event = _event;\n view.input.shiftKey = event.shiftKey;\n let flushed = forceDOMFlush(view);\n let now = Date.now(), type = \"singleClick\";\n if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] &&\n view.input.lastClick.button == event.button) {\n if (view.input.lastClick.type == \"singleClick\")\n type = \"doubleClick\";\n else if (view.input.lastClick.type == \"doubleClick\")\n type = \"tripleClick\";\n }\n view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };\n let pos = view.posAtCoords(eventCoords(event));\n if (!pos)\n return;\n if (type == \"singleClick\") {\n if (view.input.mouseDown)\n view.input.mouseDown.done();\n view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);\n }\n else if ((type == \"doubleClick\" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {\n event.preventDefault();\n }\n else {\n setSelectionOrigin(view, \"pointer\");\n }\n};\nclass MouseDown {\n constructor(view, pos, event, flushed) {\n this.view = view;\n this.pos = pos;\n this.event = event;\n this.flushed = flushed;\n this.delayedSelectionSync = false;\n this.mightDrag = null;\n this.startDoc = view.state.doc;\n this.selectNode = !!event[selectNodeModifier];\n this.allowDefault = event.shiftKey;\n let targetNode, targetPos;\n if (pos.inside > -1) {\n targetNode = view.state.doc.nodeAt(pos.inside);\n targetPos = pos.inside;\n }\n else {\n let $pos = view.state.doc.resolve(pos.pos);\n targetNode = $pos.parent;\n targetPos = $pos.depth ? $pos.before() : 0;\n }\n const target = flushed ? null : event.target;\n const targetDesc = target ? view.docView.nearestDesc(target, true) : null;\n this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null;\n let { selection } = view.state;\n if (event.button == 0 &&\n targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false ||\n selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)\n this.mightDrag = {\n node: targetNode,\n pos: targetPos,\n addAttr: !!(this.target && !this.target.draggable),\n setUneditable: !!(this.target && gecko && !this.target.hasAttribute(\"contentEditable\"))\n };\n if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.draggable = true;\n if (this.mightDrag.setUneditable)\n setTimeout(() => {\n if (this.view.input.mouseDown == this)\n this.target.setAttribute(\"contentEditable\", \"false\");\n }, 20);\n this.view.domObserver.start();\n }\n view.root.addEventListener(\"mouseup\", this.up = this.up.bind(this));\n view.root.addEventListener(\"mousemove\", this.move = this.move.bind(this));\n setSelectionOrigin(view, \"pointer\");\n }\n done() {\n this.view.root.removeEventListener(\"mouseup\", this.up);\n this.view.root.removeEventListener(\"mousemove\", this.move);\n if (this.mightDrag && this.target) {\n this.view.domObserver.stop();\n if (this.mightDrag.addAttr)\n this.target.removeAttribute(\"draggable\");\n if (this.mightDrag.setUneditable)\n this.target.removeAttribute(\"contentEditable\");\n this.view.domObserver.start();\n }\n if (this.delayedSelectionSync)\n setTimeout(() => selectionToDOM(this.view));\n this.view.input.mouseDown = null;\n }\n up(event) {\n this.done();\n if (!this.view.dom.contains(event.target))\n return;\n let pos = this.pos;\n if (this.view.state.doc != this.startDoc)\n pos = this.view.posAtCoords(eventCoords(event));\n this.updateAllowDefault(event);\n if (this.allowDefault || !pos) {\n setSelectionOrigin(this.view, \"pointer\");\n }\n else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {\n event.preventDefault();\n }\n else if (event.button == 0 &&\n (this.flushed ||\n // Safari ignores clicks on draggable elements\n (safari && this.mightDrag && !this.mightDrag.node.isAtom) ||\n // Chrome will sometimes treat a node selection as a\n // cursor, but still report that the node is selected\n // when asked through getSelection. You'll then get a\n // situation where clicking at the point where that\n // (hidden) cursor is doesn't change the selection, and\n // thus doesn't get a reaction from ProseMirror. This\n // works around that.\n (chrome && !this.view.state.selection.visible &&\n Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2))) {\n updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), \"pointer\");\n event.preventDefault();\n }\n else {\n setSelectionOrigin(this.view, \"pointer\");\n }\n }\n move(event) {\n this.updateAllowDefault(event);\n setSelectionOrigin(this.view, \"pointer\");\n if (event.buttons == 0)\n this.done();\n }\n updateAllowDefault(event) {\n if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 ||\n Math.abs(this.event.y - event.clientY) > 4))\n this.allowDefault = true;\n }\n}\nhandlers.touchstart = view => {\n view.input.lastTouch = Date.now();\n forceDOMFlush(view);\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.touchmove = view => {\n view.input.lastTouch = Date.now();\n setSelectionOrigin(view, \"pointer\");\n};\nhandlers.contextmenu = view => forceDOMFlush(view);\nfunction inOrNearComposition(view, event) {\n if (view.composing)\n return true;\n // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.\n // On Japanese input method editors (IMEs), the Enter key is used to confirm character\n // selection. On Safari, when Enter is pressed, compositionend and keydown events are\n // emitted. The keydown event triggers newline insertion, which we don't want.\n // This method returns true if the keydown event should be ignored.\n // We only ignore it once, as pressing Enter a second time *should* insert a newline.\n // Furthermore, the keydown event timestamp must be close to the compositionEndedAt timestamp.\n // This guards against the case where compositionend is triggered without the keyboard\n // (e.g. character confirmation may be done with the mouse), and keydown is triggered\n // afterwards- we wouldn't want to ignore the keydown event in this case.\n if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {\n view.input.compositionEndedAt = -2e8;\n return true;\n }\n return false;\n}\n// Drop active composition after 5 seconds of inactivity on Android\nconst timeoutComposition = android ? 5000 : -1;\neditHandlers.compositionstart = editHandlers.compositionupdate = view => {\n if (!view.composing) {\n view.domObserver.flush();\n let { state } = view, $pos = state.selection.$to;\n if (state.selection instanceof TextSelection &&\n (state.storedMarks ||\n (!$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some(m => m.type.spec.inclusive === false)) ||\n chrome && windows && selectionBeforeUneditable(view))) { // Issue #1500\n // Need to wrap the cursor in mark nodes different from the ones in the DOM context\n view.markCursor = view.state.storedMarks || $pos.marks();\n endComposition(view, true);\n view.markCursor = null;\n }\n else {\n endComposition(view, !state.selection.empty);\n // In firefox, if the cursor is after but outside a marked node,\n // the inserted text won't inherit the marks. So this moves it\n // inside if necessary.\n if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {\n let sel = view.domSelectionRange();\n for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0;) {\n let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];\n if (!before)\n break;\n if (before.nodeType == 3) {\n let sel = view.domSelection();\n if (sel)\n sel.collapse(before, before.nodeValue.length);\n break;\n }\n else {\n node = before;\n offset = -1;\n }\n }\n }\n }\n view.input.composing = true;\n }\n scheduleComposeEnd(view, timeoutComposition);\n};\nfunction selectionBeforeUneditable(view) {\n let { focusNode, focusOffset } = view.domSelectionRange();\n if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length)\n return false;\n let next = focusNode.childNodes[focusOffset];\n return next.nodeType == 1 && next.contentEditable == \"false\";\n}\neditHandlers.compositionend = (view, event) => {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = event.timeStamp;\n view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;\n view.input.compositionNode = null;\n if (view.input.badSafariComposition)\n view.domObserver.forceFlush();\n else if (view.input.compositionPendingChanges)\n Promise.resolve().then(() => view.domObserver.flush());\n view.input.compositionID++;\n scheduleComposeEnd(view, 20);\n }\n};\nfunction scheduleComposeEnd(view, delay) {\n clearTimeout(view.input.composingTimeout);\n if (delay > -1)\n view.input.composingTimeout = setTimeout(() => endComposition(view), delay);\n}\nfunction clearComposition(view) {\n if (view.composing) {\n view.input.composing = false;\n view.input.compositionEndedAt = timestampFromCustomEvent();\n }\n while (view.input.compositionNodes.length > 0)\n view.input.compositionNodes.pop().markParentsDirty();\n}\nfunction findCompositionNode(view) {\n let sel = view.domSelectionRange();\n if (!sel.focusNode)\n return null;\n let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);\n let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);\n if (textBefore && textAfter && textBefore != textAfter) {\n let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;\n if (textBefore == lastChanged || textAfter == lastChanged)\n return lastChanged;\n if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {\n return textAfter;\n }\n else if (view.input.compositionNode == textAfter) {\n let descBefore = textBefore.pmViewDesc;\n if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))\n return textAfter;\n }\n }\n return textBefore || textAfter;\n}\nfunction timestampFromCustomEvent() {\n let event = document.createEvent(\"Event\");\n event.initEvent(\"event\", true, true);\n return event.timeStamp;\n}\n/**\n@internal\n*/\nfunction endComposition(view, restarting = false) {\n if (android && view.domObserver.flushingSoon >= 0)\n return;\n view.domObserver.forceFlush();\n clearComposition(view);\n if (restarting || view.docView && view.docView.dirty) {\n let sel = selectionFromDOM(view), cur = view.state.selection;\n if (sel && !sel.eq(cur))\n view.dispatch(view.state.tr.setSelection(sel));\n else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)\n view.dispatch(view.state.tr.deleteSelection());\n else\n view.updateState(view.state);\n return true;\n }\n return false;\n}\nfunction captureCopy(view, dom) {\n // The extra wrapper is somehow necessary on IE/Edge to prevent the\n // content from being mangled when it is put onto the clipboard\n if (!view.dom.parentNode)\n return;\n let wrap = view.dom.parentNode.appendChild(document.createElement(\"div\"));\n wrap.appendChild(dom);\n wrap.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n let sel = getSelection(), range = document.createRange();\n range.selectNodeContents(dom);\n // Done because IE will fire a selectionchange moving the selection\n // to its start when removeAllRanges is called and the editor still\n // has focus (which will mess up the editor's selection state).\n view.dom.blur();\n sel.removeAllRanges();\n sel.addRange(range);\n setTimeout(() => {\n if (wrap.parentNode)\n wrap.parentNode.removeChild(wrap);\n view.focus();\n }, 50);\n}\n// This is very crude, but unfortunately both these browsers _pretend_\n// that they have a clipboard API—all the objects and methods are\n// there, they just don't work, and they are hard to test.\nconst brokenClipboardAPI = (ie && ie_version < 15) ||\n (ios && webkit_version < 604);\nhandlers.copy = editHandlers.cut = (view, _event) => {\n let event = _event;\n let sel = view.state.selection, cut = event.type == \"cut\";\n if (sel.empty)\n return;\n // IE and Edge's clipboard interface is completely broken\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let slice = sel.content(), { dom, text } = serializeForClipboard(view, slice);\n if (data) {\n event.preventDefault();\n data.clearData();\n data.setData(\"text/html\", dom.innerHTML);\n data.setData(\"text/plain\", text);\n }\n else {\n captureCopy(view, dom);\n }\n if (cut)\n view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta(\"uiEvent\", \"cut\"));\n};\nfunction sliceSingleNode(slice) {\n return slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1 ? slice.content.firstChild : null;\n}\nfunction capturePaste(view, event) {\n if (!view.dom.parentNode)\n return;\n let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;\n let target = view.dom.parentNode.appendChild(document.createElement(plainText ? \"textarea\" : \"div\"));\n if (!plainText)\n target.contentEditable = \"true\";\n target.style.cssText = \"position: fixed; left: -10000px; top: 10px\";\n target.focus();\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n setTimeout(() => {\n view.focus();\n if (target.parentNode)\n target.parentNode.removeChild(target);\n if (plainText)\n doPaste(view, target.value, null, plain, event);\n else\n doPaste(view, target.textContent, target.innerHTML, plain, event);\n }, 50);\n}\nfunction doPaste(view, text, html, preferPlain, event) {\n let slice = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from);\n if (view.someProp(\"handlePaste\", f => f(view, event, slice || Slice.empty)))\n return true;\n if (!slice)\n return false;\n let singleNode = sliceSingleNode(slice);\n let tr = singleNode\n ? view.state.tr.replaceSelectionWith(singleNode, preferPlain)\n : view.state.tr.replaceSelection(slice);\n view.dispatch(tr.scrollIntoView().setMeta(\"paste\", true).setMeta(\"uiEvent\", \"paste\"));\n return true;\n}\nfunction getText(clipboardData) {\n let text = clipboardData.getData(\"text/plain\") || clipboardData.getData(\"Text\");\n if (text)\n return text;\n let uris = clipboardData.getData(\"text/uri-list\");\n return uris ? uris.replace(/\\r?\\n/g, \" \") : \"\";\n}\neditHandlers.paste = (view, _event) => {\n let event = _event;\n // Handling paste from JavaScript during composition is very poorly\n // handled by browsers, so as a dodgy but preferable kludge, we just\n // let the browser do its native thing there, except on Android,\n // where the editor is almost always composing.\n if (view.composing && !android)\n return;\n let data = brokenClipboardAPI ? null : event.clipboardData;\n let plain = view.input.shiftKey && view.input.lastKeyCode != 45;\n if (data && doPaste(view, getText(data), data.getData(\"text/html\"), plain, event))\n event.preventDefault();\n else\n capturePaste(view, event);\n};\nclass Dragging {\n constructor(slice, move, node) {\n this.slice = slice;\n this.move = move;\n this.node = node;\n }\n}\nconst dragCopyModifier = mac ? \"altKey\" : \"ctrlKey\";\nfunction dragMoves(view, event) {\n let moves = view.someProp(\"dragCopies\", test => !test(event));\n return moves != null ? moves : !event[dragCopyModifier];\n}\nhandlers.dragstart = (view, _event) => {\n let event = _event;\n let mouseDown = view.input.mouseDown;\n if (mouseDown)\n mouseDown.done();\n if (!event.dataTransfer)\n return;\n let sel = view.state.selection;\n let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));\n let node;\n if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;\n else if (mouseDown && mouseDown.mightDrag) {\n node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);\n }\n else if (event.target && event.target.nodeType == 1) {\n let desc = view.docView.nearestDesc(event.target, true);\n if (desc && desc.node.type.spec.draggable && desc != view.docView)\n node = NodeSelection.create(view.state.doc, desc.posBefore);\n }\n let draggedSlice = (node || view.state.selection).content();\n let { dom, text, slice } = serializeForClipboard(view, draggedSlice);\n // Pre-120 Chrome versions clear files when calling `clearData` (#1472)\n if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)\n event.dataTransfer.clearData();\n event.dataTransfer.setData(brokenClipboardAPI ? \"Text\" : \"text/html\", dom.innerHTML);\n // See https://github.com/ProseMirror/prosemirror/issues/1156\n event.dataTransfer.effectAllowed = \"copyMove\";\n if (!brokenClipboardAPI)\n event.dataTransfer.setData(\"text/plain\", text);\n view.dragging = new Dragging(slice, dragMoves(view, event), node);\n};\nhandlers.dragend = view => {\n let dragging = view.dragging;\n window.setTimeout(() => {\n if (view.dragging == dragging)\n view.dragging = null;\n }, 50);\n};\neditHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault();\neditHandlers.drop = (view, event) => {\n try {\n handleDrop(view, event, view.dragging);\n }\n finally {\n view.dragging = null;\n }\n};\nfunction handleDrop(view, event, dragging) {\n if (!event.dataTransfer)\n return;\n let eventPos = view.posAtCoords(eventCoords(event));\n if (!eventPos)\n return;\n let $mouse = view.state.doc.resolve(eventPos.pos);\n let slice = dragging && dragging.slice;\n if (slice) {\n view.someProp(\"transformPasted\", f => { slice = f(slice, view, false); });\n }\n else {\n slice = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData(\"text/html\"), false, $mouse);\n }\n let move = !!(dragging && dragMoves(view, event));\n if (view.someProp(\"handleDrop\", f => f(view, event, slice || Slice.empty, move))) {\n event.preventDefault();\n return;\n }\n if (!slice)\n return;\n event.preventDefault();\n let insertPos = slice ? dropPoint(view.state.doc, $mouse.pos, slice) : $mouse.pos;\n if (insertPos == null)\n insertPos = $mouse.pos;\n let tr = view.state.tr;\n if (move) {\n let { node } = dragging;\n if (node)\n node.replace(tr);\n else\n tr.deleteSelection();\n }\n let pos = tr.mapping.map(insertPos);\n let isNode = slice.openStart == 0 && slice.openEnd == 0 && slice.content.childCount == 1;\n let beforeInsert = tr.doc;\n if (isNode)\n tr.replaceRangeWith(pos, pos, slice.content.firstChild);\n else\n tr.replaceRange(pos, pos, slice);\n if (tr.doc.eq(beforeInsert))\n return;\n let $pos = tr.doc.resolve(pos);\n if (isNode && NodeSelection.isSelectable(slice.content.firstChild) &&\n $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice.content.firstChild)) {\n tr.setSelection(new NodeSelection($pos));\n }\n else {\n let end = tr.mapping.map(insertPos);\n tr.mapping.maps[tr.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);\n tr.setSelection(selectionBetween(view, $pos, tr.doc.resolve(end)));\n }\n view.focus();\n view.dispatch(tr.setMeta(\"uiEvent\", \"drop\"));\n}\nhandlers.focus = view => {\n view.input.lastFocus = Date.now();\n if (!view.focused) {\n view.domObserver.stop();\n view.dom.classList.add(\"ProseMirror-focused\");\n view.domObserver.start();\n view.focused = true;\n setTimeout(() => {\n if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))\n selectionToDOM(view);\n }, 20);\n }\n};\nhandlers.blur = (view, _event) => {\n let event = _event;\n if (view.focused) {\n view.domObserver.stop();\n view.dom.classList.remove(\"ProseMirror-focused\");\n view.domObserver.start();\n if (event.relatedTarget && view.dom.contains(event.relatedTarget))\n view.domObserver.currentSelection.clear();\n view.focused = false;\n }\n};\nhandlers.beforeinput = (view, _event) => {\n let event = _event;\n // We should probably do more with beforeinput events, but support\n // is so spotty that I'm still waiting to see where they are going.\n // Very specific hack to deal with backspace sometimes failing on\n // Chrome Android when after an uneditable node.\n if (chrome && android && event.inputType == \"deleteContentBackward\") {\n view.domObserver.flushSoon();\n let { domChangeCount } = view.input;\n setTimeout(() => {\n if (view.input.domChangeCount != domChangeCount)\n return; // Event already had some effect\n // This bug tends to close the virtual keyboard, so we refocus\n view.dom.blur();\n view.focus();\n if (view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\"))))\n return;\n let { $cursor } = view.state.selection;\n // Crude approximation of backspace behavior when no command handled it\n if ($cursor && $cursor.pos > 0)\n view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());\n }, 50);\n }\n};\n// Make sure all handlers get registered\nfor (let prop in editHandlers)\n handlers[prop] = editHandlers[prop];\n\nfunction compareObjs(a, b) {\n if (a == b)\n return true;\n for (let p in a)\n if (a[p] !== b[p])\n return false;\n for (let p in b)\n if (!(p in a))\n return false;\n return true;\n}\nclass WidgetType {\n constructor(toDOM, spec) {\n this.toDOM = toDOM;\n this.spec = spec || noSpec;\n this.side = this.spec.side || 0;\n }\n map(mapping, span, offset, oldOffset) {\n let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);\n return deleted ? null : new Decoration(pos - offset, pos - offset, this);\n }\n valid() { return true; }\n eq(other) {\n return this == other ||\n (other instanceof WidgetType &&\n (this.spec.key && this.spec.key == other.spec.key ||\n this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)));\n }\n destroy(node) {\n if (this.spec.destroy)\n this.spec.destroy(node);\n }\n}\nclass InlineType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;\n let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;\n return from >= to ? null : new Decoration(from, to, this);\n }\n valid(_, span) { return span.from < span.to; }\n eq(other) {\n return this == other ||\n (other instanceof InlineType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n static is(span) { return span.type instanceof InlineType; }\n destroy() { }\n}\nclass NodeType {\n constructor(attrs, spec) {\n this.attrs = attrs;\n this.spec = spec || noSpec;\n }\n map(mapping, span, offset, oldOffset) {\n let from = mapping.mapResult(span.from + oldOffset, 1);\n if (from.deleted)\n return null;\n let to = mapping.mapResult(span.to + oldOffset, -1);\n if (to.deleted || to.pos <= from.pos)\n return null;\n return new Decoration(from.pos - offset, to.pos - offset, this);\n }\n valid(node, span) {\n let { index, offset } = node.content.findIndex(span.from), child;\n return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to;\n }\n eq(other) {\n return this == other ||\n (other instanceof NodeType && compareObjs(this.attrs, other.attrs) &&\n compareObjs(this.spec, other.spec));\n }\n destroy() { }\n}\n/**\nDecoration objects can be provided to the view through the\n[`decorations` prop](https://prosemirror.net/docs/ref/#view.EditorProps.decorations). They come in\nseveral variants—see the static members of this class for details.\n*/\nclass Decoration {\n /**\n @internal\n */\n constructor(\n /**\n The start position of the decoration.\n */\n from, \n /**\n The end position. Will be the same as `from` for [widget\n decorations](https://prosemirror.net/docs/ref/#view.Decoration^widget).\n */\n to, \n /**\n @internal\n */\n type) {\n this.from = from;\n this.to = to;\n this.type = type;\n }\n /**\n @internal\n */\n copy(from, to) {\n return new Decoration(from, to, this.type);\n }\n /**\n @internal\n */\n eq(other, offset = 0) {\n return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;\n }\n /**\n @internal\n */\n map(mapping, offset, oldOffset) {\n return this.type.map(mapping, this, offset, oldOffset);\n }\n /**\n Creates a widget decoration, which is a DOM node that's shown in\n the document at the given position. It is recommended that you\n delay rendering the widget by passing a function that will be\n called when the widget is actually drawn in a view, but you can\n also directly pass a DOM node. `getPos` can be used to find the\n widget's current document position.\n */\n static widget(pos, toDOM, spec) {\n return new Decoration(pos, pos, new WidgetType(toDOM, spec));\n }\n /**\n Creates an inline decoration, which adds the given attributes to\n each inline node between `from` and `to`.\n */\n static inline(from, to, attrs, spec) {\n return new Decoration(from, to, new InlineType(attrs, spec));\n }\n /**\n Creates a node decoration. `from` and `to` should point precisely\n before and after a node in the document. That node, and only that\n node, will receive the given attributes.\n */\n static node(from, to, attrs, spec) {\n return new Decoration(from, to, new NodeType(attrs, spec));\n }\n /**\n The spec provided when creating this decoration. Can be useful\n if you've stored extra information in that object.\n */\n get spec() { return this.type.spec; }\n /**\n @internal\n */\n get inline() { return this.type instanceof InlineType; }\n /**\n @internal\n */\n get widget() { return this.type instanceof WidgetType; }\n}\nconst none = [], noSpec = {};\n/**\nA collection of [decorations](https://prosemirror.net/docs/ref/#view.Decoration), organized in such\na way that the drawing algorithm can efficiently use and compare\nthem. This is a persistent data structure—it is not modified,\nupdates create a new value.\n*/\nclass DecorationSet {\n /**\n @internal\n */\n constructor(local, children) {\n this.local = local.length ? local : none;\n this.children = children.length ? children : none;\n }\n /**\n Create a set of decorations, using the structure of the given\n document. This will consume (modify) the `decorations` array, so\n you must make a copy if you want need to preserve that.\n */\n static create(doc, decorations) {\n return decorations.length ? buildTree(decorations, doc, 0, noSpec) : empty;\n }\n /**\n Find all decorations in this set which touch the given range\n (including decorations that start or end directly at the\n boundaries) and match the given predicate on their spec. When\n `start` and `end` are omitted, all decorations in the set are\n considered. When `predicate` isn't given, all decorations are\n assumed to match.\n */\n find(start, end, predicate) {\n let result = [];\n this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);\n return result;\n }\n findInner(start, end, result, offset, predicate) {\n for (let i = 0; i < this.local.length; i++) {\n let span = this.local[i];\n if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))\n result.push(span.copy(span.from + offset, span.to + offset));\n }\n for (let i = 0; i < this.children.length; i += 3) {\n if (this.children[i] < end && this.children[i + 1] > start) {\n let childOff = this.children[i] + 1;\n this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);\n }\n }\n }\n /**\n Map the set of decorations in response to a change in the\n document.\n */\n map(mapping, doc, options) {\n if (this == empty || mapping.maps.length == 0)\n return this;\n return this.mapInner(mapping, doc, 0, 0, options || noSpec);\n }\n /**\n @internal\n */\n mapInner(mapping, node, offset, oldOffset, options) {\n let newLocal;\n for (let i = 0; i < this.local.length; i++) {\n let mapped = this.local[i].map(mapping, offset, oldOffset);\n if (mapped && mapped.type.valid(node, mapped))\n (newLocal || (newLocal = [])).push(mapped);\n else if (options.onRemove)\n options.onRemove(this.local[i].spec);\n }\n if (this.children.length)\n return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);\n else\n return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty;\n }\n /**\n Add the given array of decorations to the ones in the set,\n producing a new set. Consumes the `decorations` array. Needs\n access to the current document to create the appropriate tree\n structure.\n */\n add(doc, decorations) {\n if (!decorations.length)\n return this;\n if (this == empty)\n return DecorationSet.create(doc, decorations);\n return this.addInner(doc, decorations, 0);\n }\n addInner(doc, decorations, offset) {\n let children, childIndex = 0;\n doc.forEach((childNode, childOffset) => {\n let baseOffset = childOffset + offset, found;\n if (!(found = takeSpansForNode(decorations, childNode, baseOffset)))\n return;\n if (!children)\n children = this.children.slice();\n while (childIndex < children.length && children[childIndex] < childOffset)\n childIndex += 3;\n if (children[childIndex] == childOffset)\n children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found, baseOffset + 1);\n else\n children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found, childNode, baseOffset + 1, noSpec));\n childIndex += 3;\n });\n let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);\n for (let i = 0; i < local.length; i++)\n if (!local[i].type.valid(doc, local[i]))\n local.splice(i--, 1);\n return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);\n }\n /**\n Create a new set that contains the decorations in this set, minus\n the ones in the given array.\n */\n remove(decorations) {\n if (decorations.length == 0 || this == empty)\n return this;\n return this.removeInner(decorations, 0);\n }\n removeInner(decorations, offset) {\n let children = this.children, local = this.local;\n for (let i = 0; i < children.length; i += 3) {\n let found;\n let from = children[i] + offset, to = children[i + 1] + offset;\n for (let j = 0, span; j < decorations.length; j++)\n if (span = decorations[j]) {\n if (span.from > from && span.to < to) {\n decorations[j] = null;\n (found || (found = [])).push(span);\n }\n }\n if (!found)\n continue;\n if (children == this.children)\n children = this.children.slice();\n let removed = children[i + 2].removeInner(found, from + 1);\n if (removed != empty) {\n children[i + 2] = removed;\n }\n else {\n children.splice(i, 3);\n i -= 3;\n }\n }\n if (local.length)\n for (let i = 0, span; i < decorations.length; i++)\n if (span = decorations[i]) {\n for (let j = 0; j < local.length; j++)\n if (local[j].eq(span, offset)) {\n if (local == this.local)\n local = this.local.slice();\n local.splice(j--, 1);\n }\n }\n if (children == this.children && local == this.local)\n return this;\n return local.length || children.length ? new DecorationSet(local, children) : empty;\n }\n forChild(offset, node) {\n if (this == empty)\n return this;\n if (node.isLeaf)\n return DecorationSet.empty;\n let child, local;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] >= offset) {\n if (this.children[i] == offset)\n child = this.children[i + 2];\n break;\n }\n let start = offset + 1, end = start + node.content.size;\n for (let i = 0; i < this.local.length; i++) {\n let dec = this.local[i];\n if (dec.from < end && dec.to > start && (dec.type instanceof InlineType)) {\n let from = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;\n if (from < to)\n (local || (local = [])).push(dec.copy(from, to));\n }\n }\n if (local) {\n let localSet = new DecorationSet(local.sort(byPos), none);\n return child ? new DecorationGroup([localSet, child]) : localSet;\n }\n return child || empty;\n }\n /**\n @internal\n */\n eq(other) {\n if (this == other)\n return true;\n if (!(other instanceof DecorationSet) ||\n this.local.length != other.local.length ||\n this.children.length != other.children.length)\n return false;\n for (let i = 0; i < this.local.length; i++)\n if (!this.local[i].eq(other.local[i]))\n return false;\n for (let i = 0; i < this.children.length; i += 3)\n if (this.children[i] != other.children[i] ||\n this.children[i + 1] != other.children[i + 1] ||\n !this.children[i + 2].eq(other.children[i + 2]))\n return false;\n return true;\n }\n /**\n @internal\n */\n locals(node) {\n return removeOverlap(this.localsInner(node));\n }\n /**\n @internal\n */\n localsInner(node) {\n if (this == empty)\n return none;\n if (node.inlineContent || !this.local.some(InlineType.is))\n return this.local;\n let result = [];\n for (let i = 0; i < this.local.length; i++) {\n if (!(this.local[i].type instanceof InlineType))\n result.push(this.local[i]);\n }\n return result;\n }\n forEachSet(f) { f(this); }\n}\n/**\nThe empty set of decorations.\n*/\nDecorationSet.empty = new DecorationSet([], []);\n/**\n@internal\n*/\nDecorationSet.removeOverlap = removeOverlap;\nconst empty = DecorationSet.empty;\n// An abstraction that allows the code dealing with decorations to\n// treat multiple DecorationSet objects as if it were a single object\n// with (a subset of) the same interface.\nclass DecorationGroup {\n constructor(members) {\n this.members = members;\n }\n map(mapping, doc) {\n const mappedDecos = this.members.map(member => member.map(mapping, doc, noSpec));\n return DecorationGroup.from(mappedDecos);\n }\n forChild(offset, child) {\n if (child.isLeaf)\n return DecorationSet.empty;\n let found = [];\n for (let i = 0; i < this.members.length; i++) {\n let result = this.members[i].forChild(offset, child);\n if (result == empty)\n continue;\n if (result instanceof DecorationGroup)\n found = found.concat(result.members);\n else\n found.push(result);\n }\n return DecorationGroup.from(found);\n }\n eq(other) {\n if (!(other instanceof DecorationGroup) ||\n other.members.length != this.members.length)\n return false;\n for (let i = 0; i < this.members.length; i++)\n if (!this.members[i].eq(other.members[i]))\n return false;\n return true;\n }\n locals(node) {\n let result, sorted = true;\n for (let i = 0; i < this.members.length; i++) {\n let locals = this.members[i].localsInner(node);\n if (!locals.length)\n continue;\n if (!result) {\n result = locals;\n }\n else {\n if (sorted) {\n result = result.slice();\n sorted = false;\n }\n for (let j = 0; j < locals.length; j++)\n result.push(locals[j]);\n }\n }\n return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;\n }\n // Create a group for the given array of decoration sets, or return\n // a single set when possible.\n static from(members) {\n switch (members.length) {\n case 0: return empty;\n case 1: return members[0];\n default: return new DecorationGroup(members.every(m => m instanceof DecorationSet) ? members :\n members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), []));\n }\n }\n forEachSet(f) {\n for (let i = 0; i < this.members.length; i++)\n this.members[i].forEachSet(f);\n }\n}\nfunction mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {\n let children = oldChildren.slice();\n // Mark the children that are directly touched by changes, and\n // move those that are after the changes.\n for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {\n let moved = 0;\n mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {\n let dSize = (newEnd - newStart) - (oldEnd - oldStart);\n for (let i = 0; i < children.length; i += 3) {\n let end = children[i + 1];\n if (end < 0 || oldStart > end + baseOffset - moved)\n continue;\n let start = children[i] + baseOffset - moved;\n if (oldEnd >= start) {\n children[i + 1] = oldStart <= start ? -2 : -1;\n }\n else if (oldStart >= baseOffset && dSize) {\n children[i] += dSize;\n children[i + 1] += dSize;\n }\n }\n moved += dSize;\n });\n baseOffset = mapping.maps[i].map(baseOffset, -1);\n }\n // Find the child nodes that still correspond to a single node,\n // recursively call mapInner on them and update their positions.\n let mustRebuild = false;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) { // Touched nodes\n if (children[i + 1] == -2) {\n mustRebuild = true;\n children[i + 1] = -1;\n continue;\n }\n let from = mapping.map(oldChildren[i] + oldOffset), fromLocal = from - offset;\n if (fromLocal < 0 || fromLocal >= node.content.size) {\n mustRebuild = true;\n continue;\n }\n // Must read oldChildren because children was tagged with -1\n let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;\n let { index, offset: childOffset } = node.content.findIndex(fromLocal);\n let childNode = node.maybeChild(index);\n if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {\n let mapped = children[i + 2]\n .mapInner(mapping, childNode, from + 1, oldChildren[i] + oldOffset + 1, options);\n if (mapped != empty) {\n children[i] = fromLocal;\n children[i + 1] = toLocal;\n children[i + 2] = mapped;\n }\n else {\n children[i + 1] = -2;\n mustRebuild = true;\n }\n }\n else {\n mustRebuild = true;\n }\n }\n // Remaining children must be collected and rebuilt into the appropriate structure\n if (mustRebuild) {\n let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);\n let built = buildTree(decorations, node, 0, options);\n newLocal = built.local;\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] < 0) {\n children.splice(i, 3);\n i -= 3;\n }\n for (let i = 0, j = 0; i < built.children.length; i += 3) {\n let from = built.children[i];\n while (j < children.length && children[j] < from)\n j += 3;\n children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);\n }\n }\n return new DecorationSet(newLocal.sort(byPos), children);\n}\nfunction moveSpans(spans, offset) {\n if (!offset || !spans.length)\n return spans;\n let result = [];\n for (let i = 0; i < spans.length; i++) {\n let span = spans[i];\n result.push(new Decoration(span.from + offset, span.to + offset, span.type));\n }\n return result;\n}\nfunction mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {\n // Gather all decorations from the remaining marked children\n function gather(set, oldOffset) {\n for (let i = 0; i < set.local.length; i++) {\n let mapped = set.local[i].map(mapping, offset, oldOffset);\n if (mapped)\n decorations.push(mapped);\n else if (options.onRemove)\n options.onRemove(set.local[i].spec);\n }\n for (let i = 0; i < set.children.length; i += 3)\n gather(set.children[i + 2], set.children[i] + oldOffset + 1);\n }\n for (let i = 0; i < children.length; i += 3)\n if (children[i + 1] == -1)\n gather(children[i + 2], oldChildren[i] + oldOffset + 1);\n return decorations;\n}\nfunction takeSpansForNode(spans, node, offset) {\n if (node.isLeaf)\n return null;\n let end = offset + node.nodeSize, found = null;\n for (let i = 0, span; i < spans.length; i++) {\n if ((span = spans[i]) && span.from > offset && span.to < end) {\n (found || (found = [])).push(span);\n spans[i] = null;\n }\n }\n return found;\n}\nfunction withoutNulls(array) {\n let result = [];\n for (let i = 0; i < array.length; i++)\n if (array[i] != null)\n result.push(array[i]);\n return result;\n}\n// Build up a tree that corresponds to a set of decorations. `offset`\n// is a base offset that should be subtracted from the `from` and `to`\n// positions in the spans (so that we don't have to allocate new spans\n// for recursive calls).\nfunction buildTree(spans, node, offset, options) {\n let children = [], hasNulls = false;\n node.forEach((childNode, localStart) => {\n let found = takeSpansForNode(spans, childNode, localStart + offset);\n if (found) {\n hasNulls = true;\n let subtree = buildTree(found, childNode, offset + localStart + 1, options);\n if (subtree != empty)\n children.push(localStart, localStart + childNode.nodeSize, subtree);\n }\n });\n let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);\n for (let i = 0; i < locals.length; i++)\n if (!locals[i].type.valid(node, locals[i])) {\n if (options.onRemove)\n options.onRemove(locals[i].spec);\n locals.splice(i--, 1);\n }\n return locals.length || children.length ? new DecorationSet(locals, children) : empty;\n}\n// Used to sort decorations so that ones with a low start position\n// come first, and within a set with the same start position, those\n// with an smaller end position come first.\nfunction byPos(a, b) {\n return a.from - b.from || a.to - b.to;\n}\n// Scan a sorted array of decorations for partially overlapping spans,\n// and split those so that only fully overlapping spans are left (to\n// make subsequent rendering easier). Will return the input array if\n// no partially overlapping spans are found (the common case).\nfunction removeOverlap(spans) {\n let working = spans;\n for (let i = 0; i < working.length - 1; i++) {\n let span = working[i];\n if (span.from != span.to)\n for (let j = i + 1; j < working.length; j++) {\n let next = working[j];\n if (next.from == span.from) {\n if (next.to != span.to) {\n if (working == spans)\n working = spans.slice();\n // Followed by a partially overlapping larger span. Split that\n // span.\n working[j] = next.copy(next.from, span.to);\n insertAhead(working, j + 1, next.copy(span.to, next.to));\n }\n continue;\n }\n else {\n if (next.from < span.to) {\n if (working == spans)\n working = spans.slice();\n // The end of this one overlaps with a subsequent span. Split\n // this one.\n working[i] = span.copy(span.from, next.from);\n insertAhead(working, j, span.copy(next.from, span.to));\n }\n break;\n }\n }\n }\n return working;\n}\nfunction insertAhead(array, i, deco) {\n while (i < array.length && byPos(deco, array[i]) > 0)\n i++;\n array.splice(i, 0, deco);\n}\n// Get the decorations associated with the current props of a view.\nfunction viewDecorations(view) {\n let found = [];\n view.someProp(\"decorations\", f => {\n let result = f(view.state);\n if (result && result != empty)\n found.push(result);\n });\n if (view.cursorWrapper)\n found.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));\n return DecorationGroup.from(found);\n}\n\nconst observeOptions = {\n childList: true,\n characterData: true,\n characterDataOldValue: true,\n attributes: true,\n attributeOldValue: true,\n subtree: true\n};\n// IE11 has very broken mutation observers, so we also listen to DOMCharacterDataModified\nconst useCharData = ie && ie_version <= 11;\nclass SelectionState {\n constructor() {\n this.anchorNode = null;\n this.anchorOffset = 0;\n this.focusNode = null;\n this.focusOffset = 0;\n }\n set(sel) {\n this.anchorNode = sel.anchorNode;\n this.anchorOffset = sel.anchorOffset;\n this.focusNode = sel.focusNode;\n this.focusOffset = sel.focusOffset;\n }\n clear() {\n this.anchorNode = this.focusNode = null;\n }\n eq(sel) {\n return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset &&\n sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;\n }\n}\nclass DOMObserver {\n constructor(view, handleDOMChange) {\n this.view = view;\n this.handleDOMChange = handleDOMChange;\n this.queue = [];\n this.flushingSoon = -1;\n this.observer = null;\n this.currentSelection = new SelectionState;\n this.onCharData = null;\n this.suppressingSelectionUpdates = false;\n this.lastChangedTextNode = null;\n this.observer = window.MutationObserver &&\n new window.MutationObserver(mutations => {\n for (let i = 0; i < mutations.length; i++)\n this.queue.push(mutations[i]);\n if (ie && ie_version <= 11 && mutations.some(m => m.type == \"childList\" && m.removedNodes.length ||\n m.type == \"characterData\" && m.oldValue.length > m.target.nodeValue.length)) {\n // IE11 will sometimes (on backspacing out a single character\n // text node after a BR node) call the observer callback\n // before actually updating the DOM, which will cause\n // ProseMirror to miss the change (see #930)\n this.flushSoon();\n }\n else if (safari && view.composing && mutations.some(m => m.type == \"childList\" && m.target.nodeName == \"TR\")) {\n // Safari does weird stuff when finishing a composition in a\n // table cell, which tends to involve inserting inappropriate\n // nodes in the table row.\n view.input.badSafariComposition = true;\n this.flushSoon();\n }\n else {\n this.flush();\n }\n });\n if (useCharData) {\n this.onCharData = e => {\n this.queue.push({ target: e.target, type: \"characterData\", oldValue: e.prevValue });\n this.flushSoon();\n };\n }\n this.onSelectionChange = this.onSelectionChange.bind(this);\n }\n flushSoon() {\n if (this.flushingSoon < 0)\n this.flushingSoon = window.setTimeout(() => { this.flushingSoon = -1; this.flush(); }, 20);\n }\n forceFlush() {\n if (this.flushingSoon > -1) {\n window.clearTimeout(this.flushingSoon);\n this.flushingSoon = -1;\n this.flush();\n }\n }\n start() {\n if (this.observer) {\n this.observer.takeRecords();\n this.observer.observe(this.view.dom, observeOptions);\n }\n if (this.onCharData)\n this.view.dom.addEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.connectSelection();\n }\n stop() {\n if (this.observer) {\n let take = this.observer.takeRecords();\n if (take.length) {\n for (let i = 0; i < take.length; i++)\n this.queue.push(take[i]);\n window.setTimeout(() => this.flush(), 20);\n }\n this.observer.disconnect();\n }\n if (this.onCharData)\n this.view.dom.removeEventListener(\"DOMCharacterDataModified\", this.onCharData);\n this.disconnectSelection();\n }\n connectSelection() {\n this.view.dom.ownerDocument.addEventListener(\"selectionchange\", this.onSelectionChange);\n }\n disconnectSelection() {\n this.view.dom.ownerDocument.removeEventListener(\"selectionchange\", this.onSelectionChange);\n }\n suppressSelectionUpdates() {\n this.suppressingSelectionUpdates = true;\n setTimeout(() => this.suppressingSelectionUpdates = false, 50);\n }\n onSelectionChange() {\n if (!hasFocusAndSelection(this.view))\n return;\n if (this.suppressingSelectionUpdates)\n return selectionToDOM(this.view);\n // Deletions on IE11 fire their events in the wrong order, giving\n // us a selection change event before the DOM changes are\n // reported.\n if (ie && ie_version <= 11 && !this.view.state.selection.empty) {\n let sel = this.view.domSelectionRange();\n // Selection.isCollapsed isn't reliable on IE\n if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))\n return this.flushSoon();\n }\n this.flush();\n }\n setCurSelection() {\n this.currentSelection.set(this.view.domSelectionRange());\n }\n ignoreSelectionChange(sel) {\n if (!sel.focusNode)\n return true;\n let ancestors = new Set, container;\n for (let scan = sel.focusNode; scan; scan = parentNode(scan))\n ancestors.add(scan);\n for (let scan = sel.anchorNode; scan; scan = parentNode(scan))\n if (ancestors.has(scan)) {\n container = scan;\n break;\n }\n let desc = container && this.view.docView.nearestDesc(container);\n if (desc && desc.ignoreMutation({\n type: \"selection\",\n target: container.nodeType == 3 ? container.parentNode : container\n })) {\n this.setCurSelection();\n return true;\n }\n }\n pendingRecords() {\n if (this.observer)\n for (let mut of this.observer.takeRecords())\n this.queue.push(mut);\n return this.queue;\n }\n flush() {\n let { view } = this;\n if (!view.docView || this.flushingSoon > -1)\n return;\n let mutations = this.pendingRecords();\n if (mutations.length)\n this.queue = [];\n let sel = view.domSelectionRange();\n let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);\n let from = -1, to = -1, typeOver = false, added = [];\n if (view.editable) {\n for (let i = 0; i < mutations.length; i++) {\n let result = this.registerMutation(mutations[i], added);\n if (result) {\n from = from < 0 ? result.from : Math.min(result.from, from);\n to = to < 0 ? result.to : Math.max(result.to, to);\n if (result.typeOver)\n typeOver = true;\n }\n }\n }\n if (added.some(n => n.nodeName == \"BR\") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) {\n // Browsers sometimes insert a bogus break node if you\n // backspace out the last bit of text before an inline-flex node (#1552)\n for (let node of added)\n if (node.nodeName == \"BR\" && node.parentNode) {\n let after = node.nextSibling;\n if (after && after.nodeType == 1 && after.contentEditable == \"false\")\n node.parentNode.removeChild(node);\n }\n }\n else if (gecko && added.length) {\n let brs = added.filter(n => n.nodeName == \"BR\");\n if (brs.length == 2) {\n let [a, b] = brs;\n if (a.parentNode && a.parentNode.parentNode == b.parentNode)\n b.remove();\n else\n a.remove();\n }\n else {\n let { focusNode } = this.currentSelection;\n for (let br of brs) {\n let parent = br.parentNode;\n if (parent && parent.nodeName == \"LI\" && (!focusNode || blockParent(view, focusNode) != parent))\n br.remove();\n }\n }\n }\n let readSel = null;\n // If it looks like the browser has reset the selection to the\n // start of the document after focus, restore the selection from\n // the state\n if (from < 0 && newSel && view.input.lastFocus > Date.now() - 200 &&\n Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 &&\n selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) &&\n readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {\n view.input.lastFocus = 0;\n selectionToDOM(view);\n this.currentSelection.set(sel);\n view.scrollToSelection();\n }\n else if (from > -1 || newSel) {\n if (from > -1) {\n view.docView.markDirty(from, to);\n checkCSS(view);\n }\n if (view.input.badSafariComposition) {\n view.input.badSafariComposition = false;\n fixUpBadSafariComposition(view, added);\n }\n this.handleDOMChange(from, to, typeOver, added);\n if (view.docView && view.docView.dirty)\n view.updateState(view.state);\n else if (!this.currentSelection.eq(sel))\n selectionToDOM(view);\n this.currentSelection.set(sel);\n }\n }\n registerMutation(mut, added) {\n // Ignore mutations inside nodes that were already noted as inserted\n if (added.indexOf(mut.target) > -1)\n return null;\n let desc = this.view.docView.nearestDesc(mut.target);\n if (mut.type == \"attributes\" &&\n (desc == this.view.docView || mut.attributeName == \"contenteditable\" ||\n // Firefox sometimes fires spurious events for null/empty styles\n (mut.attributeName == \"style\" && !mut.oldValue && !mut.target.getAttribute(\"style\"))))\n return null;\n if (!desc || desc.ignoreMutation(mut))\n return null;\n if (mut.type == \"childList\") {\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let node = mut.addedNodes[i];\n added.push(node);\n if (node.nodeType == 3)\n this.lastChangedTextNode = node;\n }\n if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))\n return { from: desc.posBefore, to: desc.posAfter };\n let prev = mut.previousSibling, next = mut.nextSibling;\n if (ie && ie_version <= 11 && mut.addedNodes.length) {\n // IE11 gives us incorrect next/prev siblings for some\n // insertions, so if there are added nodes, recompute those\n for (let i = 0; i < mut.addedNodes.length; i++) {\n let { previousSibling, nextSibling } = mut.addedNodes[i];\n if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)\n prev = previousSibling;\n if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)\n next = nextSibling;\n }\n }\n let fromOffset = prev && prev.parentNode == mut.target\n ? domIndex(prev) + 1 : 0;\n let from = desc.localPosFromDOM(mut.target, fromOffset, -1);\n let toOffset = next && next.parentNode == mut.target\n ? domIndex(next) : mut.target.childNodes.length;\n let to = desc.localPosFromDOM(mut.target, toOffset, 1);\n return { from, to };\n }\n else if (mut.type == \"attributes\") {\n return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };\n }\n else { // \"characterData\"\n this.lastChangedTextNode = mut.target;\n return {\n from: desc.posAtStart,\n to: desc.posAtEnd,\n // An event was generated for a text change that didn't change\n // any text. Mark the dom change to fall back to assuming the\n // selection was typed over with an identical value if it can't\n // find another change.\n typeOver: mut.target.nodeValue == mut.oldValue\n };\n }\n }\n}\nlet cssChecked = new WeakMap();\nlet cssCheckWarned = false;\nfunction checkCSS(view) {\n if (cssChecked.has(view))\n return;\n cssChecked.set(view, null);\n if (['normal', 'nowrap', 'pre-line'].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {\n view.requiresGeckoHackNode = gecko;\n if (cssCheckWarned)\n return;\n console[\"warn\"](\"ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.\");\n cssCheckWarned = true;\n }\n}\nfunction rangeToSelectionRange(view, range) {\n let anchorNode = range.startContainer, anchorOffset = range.startOffset;\n let focusNode = range.endContainer, focusOffset = range.endOffset;\n let currentAnchor = view.domAtPos(view.state.selection.anchor);\n // Since such a range doesn't distinguish between anchor and head,\n // use a heuristic that flips it around if its end matches the\n // current anchor.\n if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))\n [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];\n return { anchorNode, anchorOffset, focusNode, focusOffset };\n}\n// Used to work around a Safari Selection/shadow DOM bug\n// Based on https://github.com/codemirror/dev/issues/414 fix\nfunction safariShadowSelectionRange(view, selection) {\n if (selection.getComposedRanges) {\n let range = selection.getComposedRanges(view.root)[0];\n if (range)\n return rangeToSelectionRange(view, range);\n }\n let found;\n function read(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n found = event.getTargetRanges()[0];\n }\n // Because Safari (at least in 2018-2022) doesn't provide regular\n // access to the selection inside a shadowRoot, we have to perform a\n // ridiculous hack to get at it—using `execCommand` to trigger a\n // `beforeInput` event so that we can read the target range from the\n // event.\n view.dom.addEventListener(\"beforeinput\", read, true);\n document.execCommand(\"indent\");\n view.dom.removeEventListener(\"beforeinput\", read, true);\n return found ? rangeToSelectionRange(view, found) : null;\n}\nfunction blockParent(view, node) {\n for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) {\n let desc = view.docView.nearestDesc(p, true);\n if (desc && desc.node.isBlock)\n return p;\n }\n return null;\n}\n// Kludge for a Safari bug where, on ending a composition in an\n// otherwise empty table cell, it randomly moves the composed text\n// into the table row around that cell, greatly confusing everything\n// (#188).\nfunction fixUpBadSafariComposition(view, addedNodes) {\n var _a;\n let { focusNode, focusOffset } = view.domSelectionRange();\n for (let node of addedNodes) {\n if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == \"TR\") {\n let nextCell = node.nextSibling;\n while (nextCell && (nextCell.nodeName != \"TD\" && nextCell.nodeName != \"TH\"))\n nextCell = nextCell.nextSibling;\n if (nextCell) {\n let parent = nextCell;\n for (;;) {\n let first = parent.firstChild;\n if (!first || first.nodeType != 1 || first.contentEditable == \"false\" ||\n /^(BR|IMG)$/.test(first.nodeName))\n break;\n parent = first;\n }\n parent.insertBefore(node, parent.firstChild);\n if (focusNode == node)\n view.domSelection().collapse(node, focusOffset);\n }\n else {\n node.parentNode.removeChild(node);\n }\n }\n }\n}\n\n// Note that all referencing and parsing is done with the\n// start-of-operation selection and document, since that's the one\n// that the DOM represents. If any changes came in in the meantime,\n// the modification is mapped over those before it is applied, in\n// readDOMChange.\nfunction parseBetween(view, from_, to_) {\n let { node: parent, fromOffset, toOffset, from, to } = view.docView.parseRange(from_, to_);\n let domSel = view.domSelectionRange();\n let find;\n let anchor = domSel.anchorNode;\n if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {\n find = [{ node: anchor, offset: domSel.anchorOffset }];\n if (!selectionCollapsed(domSel))\n find.push({ node: domSel.focusNode, offset: domSel.focusOffset });\n }\n // Work around issue in Chrome where backspacing sometimes replaces\n // the deleted content with a random BR node (issues #799, #831)\n if (chrome && view.input.lastKeyCode === 8) {\n for (let off = toOffset; off > fromOffset; off--) {\n let node = parent.childNodes[off - 1], desc = node.pmViewDesc;\n if (node.nodeName == \"BR\" && !desc) {\n toOffset = off;\n break;\n }\n if (!desc || desc.size)\n break;\n }\n }\n let startDoc = view.state.doc;\n let parser = view.someProp(\"domParser\") || DOMParser.fromSchema(view.state.schema);\n let $from = startDoc.resolve(from);\n let sel = null, doc = parser.parse(parent, {\n topNode: $from.parent,\n topMatch: $from.parent.contentMatchAt($from.index()),\n topOpen: true,\n from: fromOffset,\n to: toOffset,\n preserveWhitespace: $from.parent.type.whitespace == \"pre\" ? \"full\" : true,\n findPositions: find,\n ruleFromNode,\n context: $from\n });\n if (find && find[0].pos != null) {\n let anchor = find[0].pos, head = find[1] && find[1].pos;\n if (head == null)\n head = anchor;\n sel = { anchor: anchor + from, head: head + from };\n }\n return { doc, sel, from, to };\n}\nfunction ruleFromNode(dom) {\n let desc = dom.pmViewDesc;\n if (desc) {\n return desc.parseRule();\n }\n else if (dom.nodeName == \"BR\" && dom.parentNode) {\n // Safari replaces the list item or table cell with a BR\n // directly in the list node (?!) if you delete the last\n // character in a list item or table cell (#708, #862)\n if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {\n let skip = document.createElement(\"div\");\n skip.appendChild(document.createElement(\"li\"));\n return { skip };\n }\n else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {\n return { ignore: true };\n }\n }\n else if (dom.nodeName == \"IMG\" && dom.getAttribute(\"mark-placeholder\")) {\n return { ignore: true };\n }\n return null;\n}\nconst isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;\nfunction readDOMChange(view, from, to, typeOver, addedNodes) {\n let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);\n view.input.compositionPendingChanges = 0;\n if (from < 0) {\n let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;\n let newSel = selectionFromDOM(view, origin);\n if (newSel && !view.state.selection.eq(newSel)) {\n if (chrome && android &&\n view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\"))))\n return;\n let tr = view.state.tr.setSelection(newSel);\n if (origin == \"pointer\")\n tr.setMeta(\"pointer\", true);\n else if (origin == \"key\")\n tr.scrollIntoView();\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n return;\n }\n let $before = view.state.doc.resolve(from);\n let shared = $before.sharedDepth(to);\n from = $before.before(shared + 1);\n to = view.state.doc.resolve(to).after(shared + 1);\n let sel = view.state.selection;\n let parse = parseBetween(view, from, to);\n let doc = view.state.doc, compare = doc.slice(parse.from, parse.to);\n let preferredPos, preferredSide;\n // Prefer anchoring to end when Backspace is pressed\n if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {\n preferredPos = view.state.selection.to;\n preferredSide = \"end\";\n }\n else {\n preferredPos = view.state.selection.from;\n preferredSide = \"start\";\n }\n view.input.lastKeyCode = null;\n let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);\n if (change)\n view.input.domChangeCount++;\n if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) &&\n addedNodes.some(n => n.nodeType == 1 && !isInline.test(n.nodeName)) &&\n (!change || change.endA >= change.endB) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n if (!change) {\n if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) &&\n !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {\n change = { start: sel.from, endA: sel.to, endB: sel.to };\n }\n else {\n if (parse.sel) {\n let sel = resolveSelection(view, view.state.doc, parse.sel);\n if (sel && !sel.eq(view.state.selection)) {\n let tr = view.state.tr.setSelection(sel);\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n view.dispatch(tr);\n }\n }\n return;\n }\n }\n // Handle the case where overwriting a selection by typing matches\n // the start or end of the selected content, creating a change\n // that's smaller than what was actually overwritten.\n if (view.state.selection.from < view.state.selection.to &&\n change.start == change.endB &&\n view.state.selection instanceof TextSelection) {\n if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 &&\n view.state.selection.from >= parse.from) {\n change.start = view.state.selection.from;\n }\n else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 &&\n view.state.selection.to <= parse.to) {\n change.endB += (view.state.selection.to - change.endA);\n change.endA = view.state.selection.to;\n }\n }\n // IE11 will insert a non-breaking space _ahead_ of the space after\n // the cursor space when adding a space before another space. When\n // that happened, adjust the change to cover the space instead.\n if (ie && ie_version <= 11 && change.endB == change.start + 1 &&\n change.endA == change.start && change.start > parse.from &&\n parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == \" \\u00a0\") {\n change.start--;\n change.endA--;\n change.endB--;\n }\n let $from = parse.doc.resolveNoCache(change.start - parse.from);\n let $to = parse.doc.resolveNoCache(change.endB - parse.from);\n let $fromA = doc.resolve(change.start);\n let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;\n // If this looks like the effect of pressing Enter (or was recorded\n // as being an iOS enter press), just dispatch an Enter key instead.\n if (((ios && view.input.lastIOSEnter > Date.now() - 225 &&\n (!inlineChange || addedNodes.some(n => n.nodeName == \"DIV\" || n.nodeName == \"P\"))) ||\n (!inlineChange && $from.pos < parse.doc.content.size &&\n (!$from.sameParent($to) || !$from.parent.inlineContent) &&\n $from.pos < $to.pos && !/\\S/.test(parse.doc.textBetween($from.pos, $to.pos, \"\", \"\")))) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(13, \"Enter\")))) {\n view.input.lastIOSEnter = 0;\n return;\n }\n // Same for backspace\n if (view.state.selection.anchor > change.start &&\n looksLikeBackspace(doc, change.start, change.endA, $from, $to) &&\n view.someProp(\"handleKeyDown\", f => f(view, keyEvent(8, \"Backspace\")))) {\n if (android && chrome)\n view.domObserver.suppressSelectionUpdates(); // #820\n return;\n }\n // Chrome will occasionally, during composition, delete the\n // entire composition and then immediately insert it again. This is\n // used to detect that situation.\n if (chrome && change.endB == change.start)\n view.input.lastChromeDelete = Date.now();\n // This tries to detect Android virtual keyboard\n // enter-and-pick-suggestion action. That sometimes (see issue\n // #1059) first fires a DOM mutation, before moving the selection to\n // the newly created block. And then, because ProseMirror cleans up\n // the DOM selection, it gives up moving the selection entirely,\n // leaving the cursor in the wrong place. When that happens, we drop\n // the new paragraph from the initial change, and fire a simulated\n // enter key afterwards.\n if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth &&\n parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {\n change.endB -= 2;\n $to = parse.doc.resolveNoCache(change.endB - parse.from);\n setTimeout(() => {\n view.someProp(\"handleKeyDown\", function (f) { return f(view, keyEvent(13, \"Enter\")); });\n }, 20);\n }\n let chFrom = change.start, chTo = change.endA;\n let mkTr = (base) => {\n let tr = base || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));\n if (parse.sel) {\n let sel = resolveSelection(view, tr.doc, parse.sel);\n // Chrome will sometimes, during composition, report the\n // selection in the wrong place. If it looks like that is\n // happening, don't update the selection.\n // Edge just doesn't move the cursor forward when you start typing\n // in an empty block or between br nodes.\n if (sel && !(chrome && view.composing && sel.empty &&\n (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) &&\n (sel.head == chFrom || sel.head == tr.mapping.map(chTo) - 1) ||\n ie && sel.empty && sel.head == chFrom))\n tr.setSelection(sel);\n }\n if (compositionID)\n tr.setMeta(\"composition\", compositionID);\n return tr.scrollIntoView();\n };\n let markChange;\n if (inlineChange) {\n if ($from.pos == $to.pos) { // Deletion\n // IE11 sometimes weirdly moves the DOM selection around after\n // backspacing out the first element in a textblock\n if (ie && ie_version <= 11 && $from.parentOffset == 0) {\n view.domObserver.suppressSelectionUpdates();\n setTimeout(() => selectionToDOM(view), 20);\n }\n let tr = mkTr(view.state.tr.delete(chFrom, chTo));\n let marks = doc.resolve(change.start).marksAcross(doc.resolve(change.endA));\n if (marks)\n tr.ensureMarks(marks);\n view.dispatch(tr);\n }\n else if ( // Adding or removing a mark\n change.endA == change.endB &&\n (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))) {\n let tr = mkTr(view.state.tr);\n if (markChange.type == \"add\")\n tr.addMark(chFrom, chTo, markChange.mark);\n else\n tr.removeMark(chFrom, chTo, markChange.mark);\n view.dispatch(tr);\n }\n else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {\n // Both positions in the same text node -- simply insert text\n let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset);\n let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo));\n if (!view.someProp(\"handleTextInput\", f => f(view, chFrom, chTo, text, deflt)))\n view.dispatch(deflt());\n }\n else {\n view.dispatch(mkTr());\n }\n }\n else {\n view.dispatch(mkTr());\n }\n}\nfunction resolveSelection(view, doc, parsedSel) {\n if (Math.max(parsedSel.anchor, parsedSel.head) > doc.content.size)\n return null;\n return selectionBetween(view, doc.resolve(parsedSel.anchor), doc.resolve(parsedSel.head));\n}\n// Given two same-length, non-empty fragments of inline content,\n// determine whether the first could be created from the second by\n// removing or adding a single mark type.\nfunction isMarkChange(cur, prev) {\n let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;\n let added = curMarks, removed = prevMarks, type, mark, update;\n for (let i = 0; i < prevMarks.length; i++)\n added = prevMarks[i].removeFromSet(added);\n for (let i = 0; i < curMarks.length; i++)\n removed = curMarks[i].removeFromSet(removed);\n if (added.length == 1 && removed.length == 0) {\n mark = added[0];\n type = \"add\";\n update = (node) => node.mark(mark.addToSet(node.marks));\n }\n else if (added.length == 0 && removed.length == 1) {\n mark = removed[0];\n type = \"remove\";\n update = (node) => node.mark(mark.removeFromSet(node.marks));\n }\n else {\n return null;\n }\n let updated = [];\n for (let i = 0; i < prev.childCount; i++)\n updated.push(update(prev.child(i)));\n if (Fragment.from(updated).eq(cur))\n return { mark, type };\n}\nfunction looksLikeBackspace(old, start, end, $newStart, $newEnd) {\n if ( // The content must have shrunk\n end - start <= $newEnd.pos - $newStart.pos ||\n // newEnd must point directly at or after the end of the block that newStart points into\n skipClosingAndOpening($newStart, true, false) < $newEnd.pos)\n return false;\n let $start = old.resolve(start);\n // Handle the case where, rather than joining blocks, the change just removed an entire block\n if (!$newStart.parent.isTextblock) {\n let after = $start.nodeAfter;\n return after != null && end == start + after.nodeSize;\n }\n // Start must be at the end of a block\n if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)\n return false;\n let $next = old.resolve(skipClosingAndOpening($start, true, true));\n // The next textblock must start before end and end near it\n if (!$next.parent.isTextblock || $next.pos > end ||\n skipClosingAndOpening($next, true, false) < end)\n return false;\n // The fragments after the join point must match\n return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);\n}\nfunction skipClosingAndOpening($pos, fromEnd, mayOpen) {\n let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;\n while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {\n depth--;\n end++;\n fromEnd = false;\n }\n if (mayOpen) {\n let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));\n while (next && !next.isLeaf) {\n next = next.firstChild;\n end++;\n }\n }\n return end;\n}\nfunction findDiff(a, b, pos, preferredPos, preferredSide) {\n let start = a.findDiffStart(b, pos);\n if (start == null)\n return null;\n let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size);\n if (preferredSide == \"end\") {\n let adjust = Math.max(0, start - Math.min(endA, endB));\n preferredPos -= endA + adjust - start;\n }\n if (endA < start && a.size < b.size) {\n let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;\n start -= move;\n if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endB = start + (endB - endA);\n endA = start;\n }\n else if (endB < start) {\n let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;\n start -= move;\n if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1)))\n start += move ? 1 : -1;\n endA = start + (endA - endB);\n endB = start;\n }\n return { start, endA, endB };\n}\nfunction isSurrogatePair(str) {\n if (str.length != 2)\n return false;\n let a = str.charCodeAt(0), b = str.charCodeAt(1);\n return a >= 0xDC00 && a <= 0xDFFF && b >= 0xD800 && b <= 0xDBFF;\n}\n\n/**\n@internal\n*/\nconst __parseFromClipboard = parseFromClipboard;\n/**\n@internal\n*/\nconst __endComposition = endComposition;\n/**\nAn editor view manages the DOM structure that represents an\neditable document. Its state and behavior are determined by its\n[props](https://prosemirror.net/docs/ref/#view.DirectEditorProps).\n*/\nclass EditorView {\n /**\n Create a view. `place` may be a DOM node that the editor should\n be appended to, a function that will place it into the document,\n or an object whose `mount` property holds the node to use as the\n document container. If it is `null`, the editor will not be\n added to the document.\n */\n constructor(place, props) {\n this._root = null;\n /**\n @internal\n */\n this.focused = false;\n /**\n Kludge used to work around a Chrome bug @internal\n */\n this.trackWrites = null;\n this.mounted = false;\n /**\n @internal\n */\n this.markCursor = null;\n /**\n @internal\n */\n this.cursorWrapper = null;\n /**\n @internal\n */\n this.lastSelectedViewDesc = undefined;\n /**\n @internal\n */\n this.input = new InputState;\n this.prevDirectPlugins = [];\n this.pluginViews = [];\n /**\n Holds `true` when a hack node is needed in Firefox to prevent the\n [space is eaten issue](https://github.com/ProseMirror/prosemirror/issues/651)\n @internal\n */\n this.requiresGeckoHackNode = false;\n /**\n When editor content is being dragged, this object contains\n information about the dragged slice and whether it is being\n copied or moved. At any other time, it is null.\n */\n this.dragging = null;\n this._props = props;\n this.state = props.state;\n this.directPlugins = props.plugins || [];\n this.directPlugins.forEach(checkStateComponent);\n this.dispatch = this.dispatch.bind(this);\n this.dom = (place && place.mount) || document.createElement(\"div\");\n if (place) {\n if (place.appendChild)\n place.appendChild(this.dom);\n else if (typeof place == \"function\")\n place(this.dom);\n else if (place.mount)\n this.mounted = true;\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n this.nodeViews = buildNodeViews(this);\n this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);\n this.domObserver = new DOMObserver(this, (from, to, typeOver, added) => readDOMChange(this, from, to, typeOver, added));\n this.domObserver.start();\n initInput(this);\n this.updatePluginViews();\n }\n /**\n Holds `true` when a\n [composition](https://w3c.github.io/uievents/#events-compositionevents)\n is active.\n */\n get composing() { return this.input.composing; }\n /**\n The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).\n */\n get props() {\n if (this._props.state != this.state) {\n let prev = this._props;\n this._props = {};\n for (let name in prev)\n this._props[name] = prev[name];\n this._props.state = this.state;\n }\n return this._props;\n }\n /**\n Update the view's props. Will immediately cause an update to\n the DOM.\n */\n update(props) {\n if (props.handleDOMEvents != this._props.handleDOMEvents)\n ensureListeners(this);\n let prevProps = this._props;\n this._props = props;\n if (props.plugins) {\n props.plugins.forEach(checkStateComponent);\n this.directPlugins = props.plugins;\n }\n this.updateStateInner(props.state, prevProps);\n }\n /**\n Update the view by updating existing props object with the object\n given as argument. Equivalent to `view.update(Object.assign({},\n view.props, props))`.\n */\n setProps(props) {\n let updated = {};\n for (let name in this._props)\n updated[name] = this._props[name];\n updated.state = this.state;\n for (let name in props)\n updated[name] = props[name];\n this.update(updated);\n }\n /**\n Update the editor's `state` prop, without touching any of the\n other props.\n */\n updateState(state) {\n this.updateStateInner(state, this._props);\n }\n updateStateInner(state, prevProps) {\n var _a;\n let prev = this.state, redraw = false, updateSel = false;\n // When stored marks are added, stop composition, so that they can\n // be displayed.\n if (state.storedMarks && this.composing) {\n clearComposition(this);\n updateSel = true;\n }\n this.state = state;\n let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;\n if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {\n let nodeViews = buildNodeViews(this);\n if (changedNodeViews(nodeViews, this.nodeViews)) {\n this.nodeViews = nodeViews;\n redraw = true;\n }\n }\n if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {\n ensureListeners(this);\n }\n this.editable = getEditable(this);\n updateCursorWrapper(this);\n let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);\n let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? \"reset\"\n : state.scrollToSelection > prev.scrollToSelection ? \"to selection\" : \"preserve\";\n let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);\n if (updateDoc || !state.selection.eq(prev.selection))\n updateSel = true;\n let oldScrollPos = scroll == \"preserve\" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);\n if (updateSel) {\n this.domObserver.stop();\n // Work around an issue in Chrome, IE, and Edge where changing\n // the DOM around an active selection puts it into a broken\n // state where the thing the user sees differs from the\n // selection reported by the Selection object (#710, #973,\n // #1011, #1013, #1035).\n let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing &&\n !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);\n if (updateDoc) {\n // If the node that the selection points into is written to,\n // Chrome sometimes starts misreporting the selection, so this\n // tracks that and forces a selection reset when our update\n // did write to the node.\n let chromeKludge = chrome ? (this.trackWrites = this.domSelectionRange().focusNode) : null;\n if (this.composing)\n this.input.compositionNode = findCompositionNode(this);\n if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {\n this.docView.updateOuterDeco(outerDeco);\n this.docView.destroy();\n this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);\n }\n if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites)))\n forceSelUpdate = true;\n }\n // Work around for an issue where an update arriving right between\n // a DOM selection change and the \"selectionchange\" event for it\n // can cause a spurious DOM selection update, disrupting mouse\n // drag selection.\n if (forceSelUpdate ||\n !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) &&\n anchorInRightPlace(this))) {\n selectionToDOM(this, forceSelUpdate);\n }\n else {\n syncNodeSelection(this, state.selection);\n this.domObserver.setCurSelection();\n }\n this.domObserver.start();\n }\n this.updatePluginViews(prev);\n if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))\n this.updateDraggedNode(this.dragging, prev);\n if (scroll == \"reset\") {\n this.dom.scrollTop = 0;\n }\n else if (scroll == \"to selection\") {\n this.scrollToSelection();\n }\n else if (oldScrollPos) {\n resetScrollPos(oldScrollPos);\n }\n }\n /**\n @internal\n */\n scrollToSelection() {\n let startDOM = this.domSelectionRange().focusNode;\n if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ;\n else if (this.someProp(\"handleScrollToSelection\", f => f(this))) ;\n else if (this.state.selection instanceof NodeSelection) {\n let target = this.docView.domAfterPos(this.state.selection.from);\n if (target.nodeType == 1)\n scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);\n }\n else {\n scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);\n }\n }\n destroyPluginViews() {\n let view;\n while (view = this.pluginViews.pop())\n if (view.destroy)\n view.destroy();\n }\n updatePluginViews(prevState) {\n if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {\n this.prevDirectPlugins = this.directPlugins;\n this.destroyPluginViews();\n for (let i = 0; i < this.directPlugins.length; i++) {\n let plugin = this.directPlugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n for (let i = 0; i < this.state.plugins.length; i++) {\n let plugin = this.state.plugins[i];\n if (plugin.spec.view)\n this.pluginViews.push(plugin.spec.view(this));\n }\n }\n else {\n for (let i = 0; i < this.pluginViews.length; i++) {\n let pluginView = this.pluginViews[i];\n if (pluginView.update)\n pluginView.update(this, prevState);\n }\n }\n }\n updateDraggedNode(dragging, prev) {\n let sel = dragging.node, found = -1;\n if (this.state.doc.nodeAt(sel.from) == sel.node) {\n found = sel.from;\n }\n else {\n let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);\n let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);\n if (moved == sel.node)\n found = movedPos;\n }\n this.dragging = new Dragging(dragging.slice, dragging.move, found < 0 ? undefined : NodeSelection.create(this.state.doc, found));\n }\n someProp(propName, f) {\n let prop = this._props && this._props[propName], value;\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n for (let i = 0; i < this.directPlugins.length; i++) {\n let prop = this.directPlugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n let plugins = this.state.plugins;\n if (plugins)\n for (let i = 0; i < plugins.length; i++) {\n let prop = plugins[i].props[propName];\n if (prop != null && (value = f ? f(prop) : prop))\n return value;\n }\n }\n /**\n Query whether the view has focus.\n */\n hasFocus() {\n // Work around IE not handling focus correctly if resize handles are shown.\n // If the cursor is inside an element with resize handles, activeElement\n // will be that element instead of this.dom.\n if (ie) {\n // If activeElement is within this.dom, and there are no other elements\n // setting `contenteditable` to false in between, treat it as focused.\n let node = this.root.activeElement;\n if (node == this.dom)\n return true;\n if (!node || !this.dom.contains(node))\n return false;\n while (node && this.dom != node && this.dom.contains(node)) {\n if (node.contentEditable == 'false')\n return false;\n node = node.parentElement;\n }\n return true;\n }\n return this.root.activeElement == this.dom;\n }\n /**\n Focus the editor.\n */\n focus() {\n this.domObserver.stop();\n if (this.editable)\n focusPreventScroll(this.dom);\n selectionToDOM(this);\n this.domObserver.start();\n }\n /**\n Get the document root in which the editor exists. This will\n usually be the top-level `document`, but might be a [shadow\n DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)\n root if the editor is inside one.\n */\n get root() {\n let cached = this._root;\n if (cached == null)\n for (let search = this.dom.parentNode; search; search = search.parentNode) {\n if (search.nodeType == 9 || (search.nodeType == 11 && search.host)) {\n if (!search.getSelection)\n Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();\n return this._root = search;\n }\n }\n return cached || document;\n }\n /**\n When an existing editor view is moved to a new document or\n shadow tree, call this to make it recompute its root.\n */\n updateRoot() {\n this._root = null;\n }\n /**\n Given a pair of viewport coordinates, return the document\n position that corresponds to them. May return null if the given\n coordinates aren't inside of the editor. When an object is\n returned, its `pos` property is the position nearest to the\n coordinates, and its `inside` property holds the position of the\n inner node that the position falls inside of, or -1 if it is at\n the top level, not in any node.\n */\n posAtCoords(coords) {\n return posAtCoords(this, coords);\n }\n /**\n Returns the viewport rectangle at a given document position.\n `left` and `right` will be the same number, as this returns a\n flat cursor-ish rectangle. If the position is between two things\n that aren't directly adjacent, `side` determines which element\n is used. When < 0, the element before the position is used,\n otherwise the element after.\n */\n coordsAtPos(pos, side = 1) {\n return coordsAtPos(this, pos, side);\n }\n /**\n Find the DOM position that corresponds to the given document\n position. When `side` is negative, find the position as close as\n possible to the content before the position. When positive,\n prefer positions close to the content after the position. When\n zero, prefer as shallow a position as possible.\n \n Note that you should **not** mutate the editor's internal DOM,\n only inspect it (and even that is usually not necessary).\n */\n domAtPos(pos, side = 0) {\n return this.docView.domFromPos(pos, side);\n }\n /**\n Find the DOM node that represents the document node after the\n given position. May return `null` when the position doesn't point\n in front of a node or if the node is inside an opaque node view.\n \n This is intended to be able to call things like\n `getBoundingClientRect` on that DOM node. Do **not** mutate the\n editor DOM directly, or add styling this way, since that will be\n immediately overriden by the editor as it redraws the node.\n */\n nodeDOM(pos) {\n let desc = this.docView.descAt(pos);\n return desc ? desc.nodeDOM : null;\n }\n /**\n Find the document position that corresponds to a given DOM\n position. (Whenever possible, it is preferable to inspect the\n document structure directly, rather than poking around in the\n DOM, but sometimes—for example when interpreting an event\n target—you don't have a choice.)\n \n The `bias` parameter can be used to influence which side of a DOM\n node to use when the position is inside a leaf node.\n */\n posAtDOM(node, offset, bias = -1) {\n let pos = this.docView.posFromDOM(node, offset, bias);\n if (pos == null)\n throw new RangeError(\"DOM position not inside the editor\");\n return pos;\n }\n /**\n Find out whether the selection is at the end of a textblock when\n moving in a given direction. When, for example, given `\"left\"`,\n it will return true if moving left from the current cursor\n position would leave that position's parent textblock. Will apply\n to the view's current state by default, but it is possible to\n pass a different state.\n */\n endOfTextblock(dir, state) {\n return endOfTextblock(this, state || this.state, dir);\n }\n /**\n Run the editor's paste logic with the given HTML string. The\n `event`, if given, will be passed to the\n [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.\n */\n pasteHTML(html, event) {\n return doPaste(this, \"\", html, false, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Run the editor's paste logic with the given plain-text input.\n */\n pasteText(text, event) {\n return doPaste(this, text, null, true, event || new ClipboardEvent(\"paste\"));\n }\n /**\n Serialize the given slice as it would be if it was copied from\n this editor. Returns a DOM element that contains a\n representation of the slice as its children, a textual\n representation, and the transformed slice (which can be\n different from the given input due to hooks like\n [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).\n */\n serializeForClipboard(slice) {\n return serializeForClipboard(this, slice);\n }\n /**\n Removes the editor from the DOM and destroys all [node\n views](https://prosemirror.net/docs/ref/#view.NodeView).\n */\n destroy() {\n if (!this.docView)\n return;\n destroyInput(this);\n this.destroyPluginViews();\n if (this.mounted) {\n this.docView.update(this.state.doc, [], viewDecorations(this), this);\n this.dom.textContent = \"\";\n }\n else if (this.dom.parentNode) {\n this.dom.parentNode.removeChild(this.dom);\n }\n this.docView.destroy();\n this.docView = null;\n clearReusedRange();\n }\n /**\n This is true when the view has been\n [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be\n used anymore).\n */\n get isDestroyed() {\n return this.docView == null;\n }\n /**\n Used for testing.\n */\n dispatchEvent(event) {\n return dispatchEvent(this, event);\n }\n /**\n @internal\n */\n domSelectionRange() {\n let sel = this.domSelection();\n if (!sel)\n return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };\n return safari && this.root.nodeType === 11 &&\n deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;\n }\n /**\n @internal\n */\n domSelection() {\n return this.root.getSelection();\n }\n}\nEditorView.prototype.dispatch = function (tr) {\n let dispatchTransaction = this._props.dispatchTransaction;\n if (dispatchTransaction)\n dispatchTransaction.call(this, tr);\n else\n this.updateState(this.state.apply(tr));\n};\nfunction computeDocDeco(view) {\n let attrs = Object.create(null);\n attrs.class = \"ProseMirror\";\n attrs.contenteditable = String(view.editable);\n view.someProp(\"attributes\", value => {\n if (typeof value == \"function\")\n value = value(view.state);\n if (value)\n for (let attr in value) {\n if (attr == \"class\")\n attrs.class += \" \" + value[attr];\n else if (attr == \"style\")\n attrs.style = (attrs.style ? attrs.style + \";\" : \"\") + value[attr];\n else if (!attrs[attr] && attr != \"contenteditable\" && attr != \"nodeName\")\n attrs[attr] = String(value[attr]);\n }\n });\n if (!attrs.translate)\n attrs.translate = \"no\";\n return [Decoration.node(0, view.state.doc.content.size, attrs)];\n}\nfunction updateCursorWrapper(view) {\n if (view.markCursor) {\n let dom = document.createElement(\"img\");\n dom.className = \"ProseMirror-separator\";\n dom.setAttribute(\"mark-placeholder\", \"true\");\n dom.setAttribute(\"alt\", \"\");\n view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };\n }\n else {\n view.cursorWrapper = null;\n }\n}\nfunction getEditable(view) {\n return !view.someProp(\"editable\", value => value(view.state) === false);\n}\nfunction selectionContextChanged(sel1, sel2) {\n let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));\n return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);\n}\nfunction buildNodeViews(view) {\n let result = Object.create(null);\n function add(obj) {\n for (let prop in obj)\n if (!Object.prototype.hasOwnProperty.call(result, prop))\n result[prop] = obj[prop];\n }\n view.someProp(\"nodeViews\", add);\n view.someProp(\"markViews\", add);\n return result;\n}\nfunction changedNodeViews(a, b) {\n let nA = 0, nB = 0;\n for (let prop in a) {\n if (a[prop] != b[prop])\n return true;\n nA++;\n }\n for (let _ in b)\n nB++;\n return nA != nB;\n}\nfunction checkStateComponent(plugin) {\n if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)\n throw new RangeError(\"Plugins passed directly to the view must not have a state component\");\n}\n\nexport { Decoration, DecorationSet, EditorView, __endComposition, __parseFromClipboard };\n", "export var base = {\n 8: \"Backspace\",\n 9: \"Tab\",\n 10: \"Enter\",\n 12: \"NumLock\",\n 13: \"Enter\",\n 16: \"Shift\",\n 17: \"Control\",\n 18: \"Alt\",\n 20: \"CapsLock\",\n 27: \"Escape\",\n 32: \" \",\n 33: \"PageUp\",\n 34: \"PageDown\",\n 35: \"End\",\n 36: \"Home\",\n 37: \"ArrowLeft\",\n 38: \"ArrowUp\",\n 39: \"ArrowRight\",\n 40: \"ArrowDown\",\n 44: \"PrintScreen\",\n 45: \"Insert\",\n 46: \"Delete\",\n 59: \";\",\n 61: \"=\",\n 91: \"Meta\",\n 92: \"Meta\",\n 106: \"*\",\n 107: \"+\",\n 108: \",\",\n 109: \"-\",\n 110: \".\",\n 111: \"/\",\n 144: \"NumLock\",\n 145: \"ScrollLock\",\n 160: \"Shift\",\n 161: \"Shift\",\n 162: \"Control\",\n 163: \"Control\",\n 164: \"Alt\",\n 165: \"Alt\",\n 173: \"-\",\n 186: \";\",\n 187: \"=\",\n 188: \",\",\n 189: \"-\",\n 190: \".\",\n 191: \"/\",\n 192: \"`\",\n 219: \"[\",\n 220: \"\\\\\",\n 221: \"]\",\n 222: \"'\"\n}\n\nexport var shift = {\n 48: \")\",\n 49: \"!\",\n 50: \"@\",\n 51: \"#\",\n 52: \"$\",\n 53: \"%\",\n 54: \"^\",\n 55: \"&\",\n 56: \"*\",\n 57: \"(\",\n 59: \":\",\n 61: \"+\",\n 173: \"_\",\n 186: \":\",\n 187: \"+\",\n 188: \"<\",\n 189: \"_\",\n 190: \">\",\n 191: \"?\",\n 192: \"~\",\n 219: \"{\",\n 220: \"|\",\n 221: \"}\",\n 222: \"\\\"\"\n}\n\nvar mac = typeof navigator != \"undefined\" && /Mac/.test(navigator.platform)\nvar ie = typeof navigator != \"undefined\" && /MSIE \\d|Trident\\/(?:[7-9]|\\d{2,})\\..*rv:(\\d+)/.exec(navigator.userAgent)\n\n// Fill in the digit keys\nfor (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i)\n\n// The function keys\nfor (var i = 1; i <= 24; i++) base[i + 111] = \"F\" + i\n\n// And the alphabetic keys\nfor (var i = 65; i <= 90; i++) {\n base[i] = String.fromCharCode(i + 32)\n shift[i] = String.fromCharCode(i)\n}\n\n// For each code that doesn't have a shift-equivalent, copy the base name\nfor (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]\n\nexport function keyName(event) {\n // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.\n // On IE, shift effect is never included in `.key`.\n var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||\n ie && event.shiftKey && event.key && event.key.length == 1 ||\n event.key == \"Unidentified\"\n var name = (!ignoreKey && event.key) ||\n (event.shiftKey ? shift : base)[event.keyCode] ||\n event.key || \"Unidentified\"\n // Edge sometimes produces wrong names (Issue #3)\n if (name == \"Esc\") name = \"Escape\"\n if (name == \"Del\") name = \"Delete\"\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/\n if (name == \"Left\") name = \"ArrowLeft\"\n if (name == \"Up\") name = \"ArrowUp\"\n if (name == \"Right\") name = \"ArrowRight\"\n if (name == \"Down\") name = \"ArrowDown\"\n return name\n}\n", "import { keyName, base } from 'w3c-keyname';\nimport { Plugin } from 'prosemirror-state';\n\nconst mac = typeof navigator != \"undefined\" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);\nconst windows = typeof navigator != \"undefined\" && /Win/.test(navigator.platform);\nfunction normalizeKeyName(name) {\n let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];\n if (result == \"Space\")\n result = \" \";\n let alt, ctrl, shift, meta;\n for (let i = 0; i < parts.length - 1; i++) {\n let mod = parts[i];\n if (/^(cmd|meta|m)$/i.test(mod))\n meta = true;\n else if (/^a(lt)?$/i.test(mod))\n alt = true;\n else if (/^(c|ctrl|control)$/i.test(mod))\n ctrl = true;\n else if (/^s(hift)?$/i.test(mod))\n shift = true;\n else if (/^mod$/i.test(mod)) {\n if (mac)\n meta = true;\n else\n ctrl = true;\n }\n else\n throw new Error(\"Unrecognized modifier name: \" + mod);\n }\n if (alt)\n result = \"Alt-\" + result;\n if (ctrl)\n result = \"Ctrl-\" + result;\n if (meta)\n result = \"Meta-\" + result;\n if (shift)\n result = \"Shift-\" + result;\n return result;\n}\nfunction normalize(map) {\n let copy = Object.create(null);\n for (let prop in map)\n copy[normalizeKeyName(prop)] = map[prop];\n return copy;\n}\nfunction modifiers(name, event, shift = true) {\n if (event.altKey)\n name = \"Alt-\" + name;\n if (event.ctrlKey)\n name = \"Ctrl-\" + name;\n if (event.metaKey)\n name = \"Meta-\" + name;\n if (shift && event.shiftKey)\n name = \"Shift-\" + name;\n return name;\n}\n/**\nCreate a keymap plugin for the given set of bindings.\n\nBindings should map key names to [command](https://prosemirror.net/docs/ref/#commands)-style\nfunctions, which will be called with `(EditorState, dispatch,\nEditorView)` arguments, and should return true when they've handled\nthe key. Note that the view argument isn't part of the command\nprotocol, but can be used as an escape hatch if a binding needs to\ndirectly interact with the UI.\n\nKey names may be strings like `\"Shift-Ctrl-Enter\"`—a key\nidentifier prefixed with zero or more modifiers. Key identifiers\nare based on the strings that can appear in\n[`KeyEvent.key`](https:developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key).\nUse lowercase letters to refer to letter keys (or uppercase letters\nif you want shift to be held). You may use `\"Space\"` as an alias\nfor the `\" \"` name.\n\nModifiers can be given in any order. `Shift-` (or `s-`), `Alt-` (or\n`a-`), `Ctrl-` (or `c-` or `Control-`) and `Cmd-` (or `m-` or\n`Meta-`) are recognized. For characters that are created by holding\nshift, the `Shift-` prefix is implied, and should not be added\nexplicitly.\n\nYou can use `Mod-` as a shorthand for `Cmd-` on Mac and `Ctrl-` on\nother platforms.\n\nYou can add multiple keymap plugins to an editor. The order in\nwhich they appear determines their precedence (the ones early in\nthe array get to dispatch first).\n*/\nfunction keymap(bindings) {\n return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });\n}\n/**\nGiven a set of bindings (using the same format as\n[`keymap`](https://prosemirror.net/docs/ref/#keymap.keymap)), return a [keydown\nhandler](https://prosemirror.net/docs/ref/#view.EditorProps.handleKeyDown) that handles them.\n*/\nfunction keydownHandler(bindings) {\n let map = normalize(bindings);\n return function (view, event) {\n let name = keyName(event), baseName, direct = map[modifiers(name, event)];\n if (direct && direct(view.state, view.dispatch, view))\n return true;\n // A character key\n if (name.length == 1 && name != \" \") {\n if (event.shiftKey) {\n // In case the name was already modified by shift, try looking\n // it up without its shift modifier\n let noShift = map[modifiers(name, event, false)];\n if (noShift && noShift(view.state, view.dispatch, view))\n return true;\n }\n if ((event.altKey || event.metaKey || event.ctrlKey) &&\n // Ctrl-Alt may be used for AltGr on Windows\n !(windows && event.ctrlKey && event.altKey) &&\n (baseName = base[event.keyCode]) && baseName != name) {\n // Try falling back to the keyCode when there's a modifier\n // active or the character produced isn't ASCII, and our table\n // produces a different name from the the keyCode. See #668,\n // #1060, #1529.\n let fromCode = map[modifiers(baseName, event)];\n if (fromCode && fromCode(view.state, view.dispatch, view))\n return true;\n }\n }\n return false;\n };\n}\n\nexport { keydownHandler, keymap };\n", "import type { EditorState, Transaction } from '@tiptap/pm/state'\n\n/**\n * Takes a Transaction & Editor State and turns it into a chainable state object\n * @param config The transaction and state to create the chainable state from\n * @returns A chainable Editor state object\n */\nexport function createChainableState(config: { transaction: Transaction; state: EditorState }): EditorState {\n const { state, transaction } = config\n let { selection } = transaction\n let { doc } = transaction\n let { storedMarks } = transaction\n\n return {\n ...state,\n apply: state.apply.bind(state),\n applyTransaction: state.applyTransaction.bind(state),\n plugins: state.plugins,\n schema: state.schema,\n reconfigure: state.reconfigure.bind(state),\n toJSON: state.toJSON.bind(state),\n get storedMarks() {\n return storedMarks\n },\n get selection() {\n return selection\n },\n get doc() {\n return doc\n },\n get tr() {\n selection = transaction.selection\n doc = transaction.doc\n storedMarks = transaction.storedMarks\n\n return transaction\n },\n }\n}\n", "import type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport type { AnyCommands, CanCommands, ChainedCommands, CommandProps, SingleCommands } from './types.js'\n\nexport class CommandManager {\n editor: Editor\n\n rawCommands: AnyCommands\n\n customState?: EditorState\n\n constructor(props: { editor: Editor; state?: EditorState }) {\n this.editor = props.editor\n this.rawCommands = this.editor.extensionManager.commands\n this.customState = props.state\n }\n\n get hasCustomState(): boolean {\n return !!this.customState\n }\n\n get state(): EditorState {\n return this.customState || this.editor.state\n }\n\n get commands(): SingleCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const { tr } = state\n const props = this.buildProps(tr)\n\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const method = (...args: any[]) => {\n const callback = command(...args)(props)\n\n if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callback\n }\n\n return [name, method]\n }),\n ) as unknown as SingleCommands\n }\n\n get chain(): () => ChainedCommands {\n return () => this.createChain()\n }\n\n get can(): () => CanCommands {\n return () => this.createCan()\n }\n\n public createChain(startTr?: Transaction, shouldDispatch = true): ChainedCommands {\n const { rawCommands, editor, state } = this\n const { view } = editor\n const callbacks: boolean[] = []\n const hasStartTransaction = !!startTr\n const tr = startTr || state.tr\n\n const run = () => {\n if (!hasStartTransaction && shouldDispatch && !tr.getMeta('preventDispatch') && !this.hasCustomState) {\n view.dispatch(tr)\n }\n\n return callbacks.every(callback => callback === true)\n }\n\n const chain = {\n ...Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n const chainedCommand = (...args: never[]) => {\n const props = this.buildProps(tr, shouldDispatch)\n const callback = command(...args)(props)\n\n callbacks.push(callback)\n\n return chain\n }\n\n return [name, chainedCommand]\n }),\n ),\n run,\n } as unknown as ChainedCommands\n\n return chain\n }\n\n public createCan(startTr?: Transaction): CanCommands {\n const { rawCommands, state } = this\n const dispatch = false\n const tr = startTr || state.tr\n const props = this.buildProps(tr, dispatch)\n const formattedCommands = Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)({ ...props, dispatch: undefined })]\n }),\n ) as unknown as SingleCommands\n\n return {\n ...formattedCommands,\n chain: () => this.createChain(tr, dispatch),\n } as CanCommands\n }\n\n public buildProps(tr: Transaction, shouldDispatch = true): CommandProps {\n const { rawCommands, editor, state } = this\n const { view } = editor\n\n const props: CommandProps = {\n tr,\n editor,\n view,\n state: createChainableState({\n state,\n transaction: tr,\n }),\n dispatch: shouldDispatch ? () => undefined : undefined,\n chain: () => this.createChain(tr, shouldDispatch),\n can: () => this.createCan(tr),\n get commands() {\n return Object.fromEntries(\n Object.entries(rawCommands).map(([name, command]) => {\n return [name, (...args: never[]) => command(...args)(props)]\n }),\n ) as unknown as SingleCommands\n },\n }\n\n return props\n }\n}\n", "export * from './blur.js'\nexport * from './clearContent.js'\nexport * from './clearNodes.js'\nexport * from './command.js'\nexport * from './createParagraphNear.js'\nexport * from './cut.js'\nexport * from './deleteCurrentNode.js'\nexport * from './deleteNode.js'\nexport * from './deleteRange.js'\nexport * from './deleteSelection.js'\nexport * from './enter.js'\nexport * from './exitCode.js'\nexport * from './extendMarkRange.js'\nexport * from './first.js'\nexport * from './focus.js'\nexport * from './forEach.js'\nexport * from './insertContent.js'\nexport * from './insertContentAt.js'\nexport * from './join.js'\nexport * from './joinItemBackward.js'\nexport * from './joinItemForward.js'\nexport * from './joinTextblockBackward.js'\nexport * from './joinTextblockForward.js'\nexport * from './keyboardShortcut.js'\nexport * from './lift.js'\nexport * from './liftEmptyBlock.js'\nexport * from './liftListItem.js'\nexport * from './newlineInCode.js'\nexport * from './resetAttributes.js'\nexport * from './scrollIntoView.js'\nexport * from './selectAll.js'\nexport * from './selectNodeBackward.js'\nexport * from './selectNodeForward.js'\nexport * from './selectParentNode.js'\nexport * from './selectTextblockEnd.js'\nexport * from './selectTextblockStart.js'\nexport * from './setContent.js'\nexport * from './setMark.js'\nexport * from './setMeta.js'\nexport * from './setNode.js'\nexport * from './setNodeSelection.js'\nexport * from './setTextDirection.js'\nexport * from './setTextSelection.js'\nexport * from './sinkListItem.js'\nexport * from './splitBlock.js'\nexport * from './splitListItem.js'\nexport * from './toggleList.js'\nexport * from './toggleMark.js'\nexport * from './toggleNode.js'\nexport * from './toggleWrap.js'\nexport * from './undoInputRule.js'\nexport * from './unsetAllMarks.js'\nexport * from './unsetMark.js'\nexport * from './unsetTextDirection.js'\nexport * from './updateAttributes.js'\nexport * from './wrapIn.js'\nexport * from './wrapInList.js'\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n blur: {\n /**\n * Removes focus from the editor.\n * @example editor.commands.blur()\n */\n blur: () => ReturnType\n }\n }\n}\n\nexport const blur: RawCommands['blur'] =\n () =>\n ({ editor, view }) => {\n requestAnimationFrame(() => {\n if (!editor.isDestroyed) {\n ;(view.dom as HTMLElement).blur()\n\n // Browsers should remove the caret on blur but safari does not.\n // See: https://github.com/ueberdosis/tiptap/issues/2405\n window?.getSelection()?.removeAllRanges()\n }\n })\n\n return true\n }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n clearContent: {\n /**\n * Clear the whole document.\n * @example editor.commands.clearContent()\n */\n clearContent: (\n /**\n * Whether to emit an update event.\n * @default true\n */\n emitUpdate?: boolean,\n ) => ReturnType\n }\n }\n}\n\nexport const clearContent: RawCommands['clearContent'] =\n (emitUpdate = true) =>\n ({ commands }) => {\n return commands.setContent('', { emitUpdate })\n }\n", "import { liftTarget } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n clearNodes: {\n /**\n * Normalize nodes to a simple paragraph.\n * @example editor.commands.clearNodes()\n */\n clearNodes: () => ReturnType\n }\n }\n}\n\nexport const clearNodes: RawCommands['clearNodes'] =\n () =>\n ({ state, tr, dispatch }) => {\n const { selection } = tr\n const { ranges } = selection\n\n if (!dispatch) {\n return true\n }\n\n ranges.forEach(({ $from, $to }) => {\n state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.type.isText) {\n return\n }\n\n const { doc, mapping } = tr\n const $mappedFrom = doc.resolve(mapping.map(pos))\n const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize))\n const nodeRange = $mappedFrom.blockRange($mappedTo)\n\n if (!nodeRange) {\n return\n }\n\n const targetLiftDepth = liftTarget(nodeRange)\n\n if (node.type.isTextblock) {\n const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index())\n\n tr.setNodeMarkup(nodeRange.start, defaultType)\n }\n\n if (targetLiftDepth || targetLiftDepth === 0) {\n tr.lift(nodeRange, targetLiftDepth)\n }\n })\n })\n\n return true\n }\n", "import type { Command, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n command: {\n /**\n * Define a command inline.\n * @param fn The command function.\n * @example\n * editor.commands.command(({ tr, state }) => {\n * ...\n * return true\n * })\n */\n command: (fn: (props: Parameters[0]) => boolean) => ReturnType\n }\n }\n}\n\nexport const command: RawCommands['command'] = fn => props => {\n return fn(props)\n}\n", "import { createParagraphNear as originalCreateParagraphNear } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n createParagraphNear: {\n /**\n * Create a paragraph nearby.\n * @example editor.commands.createParagraphNear()\n */\n createParagraphNear: () => ReturnType\n }\n }\n}\n\nexport const createParagraphNear: RawCommands['createParagraphNear'] =\n () =>\n ({ state, dispatch }) => {\n return originalCreateParagraphNear(state, dispatch)\n }\n", "import { TextSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n cut: {\n /**\n * Cuts content from a range and inserts it at a given position.\n * @param range The range to cut.\n * @param range.from The start position of the range.\n * @param range.to The end position of the range.\n * @param targetPos The position to insert the content at.\n * @example editor.commands.cut({ from: 1, to: 3 }, 5)\n */\n cut: ({ from, to }: { from: number; to: number }, targetPos: number) => ReturnType\n }\n }\n}\n\nexport const cut: RawCommands['cut'] =\n (originRange, targetPos) =>\n ({ editor, tr }) => {\n const { state } = editor\n\n const contentSlice = state.doc.slice(originRange.from, originRange.to)\n\n tr.deleteRange(originRange.from, originRange.to)\n const newPos = tr.mapping.map(targetPos)\n\n tr.insert(newPos, contentSlice.content)\n\n tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))))\n\n return true\n }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n deleteCurrentNode: {\n /**\n * Delete the node that currently has the selection anchor.\n * @example editor.commands.deleteCurrentNode()\n */\n deleteCurrentNode: () => ReturnType\n }\n }\n}\n\nexport const deleteCurrentNode: RawCommands['deleteCurrentNode'] =\n () =>\n ({ tr, dispatch }) => {\n const { selection } = tr\n const currentNode = selection.$anchor.node()\n\n // if there is content inside the current node, break out of this command\n if (currentNode.content.size > 0) {\n return false\n }\n\n const $pos = tr.selection.$anchor\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth)\n\n if (node.type === currentNode.type) {\n if (dispatch) {\n const from = $pos.before(depth)\n const to = $pos.after(depth)\n\n tr.delete(from, to).scrollIntoView()\n }\n\n return true\n }\n }\n\n return false\n }\n", "import type { NodeType, Schema } from '@tiptap/pm/model'\n\nexport function getNodeType(nameOrType: string | NodeType, schema: Schema): NodeType {\n if (typeof nameOrType === 'string') {\n if (!schema.nodes[nameOrType]) {\n throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`)\n }\n\n return schema.nodes[nameOrType]\n }\n\n return nameOrType\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n deleteNode: {\n /**\n * Delete a node with a given type or name.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.deleteNode('paragraph')\n */\n deleteNode: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const deleteNode: RawCommands['deleteNode'] =\n typeOrName =>\n ({ tr, state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n const $pos = tr.selection.$anchor\n\n for (let depth = $pos.depth; depth > 0; depth -= 1) {\n const node = $pos.node(depth)\n\n if (node.type === type) {\n if (dispatch) {\n const from = $pos.before(depth)\n const to = $pos.after(depth)\n\n tr.delete(from, to).scrollIntoView()\n }\n\n return true\n }\n }\n\n return false\n }\n", "import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n deleteRange: {\n /**\n * Delete a given range.\n * @param range The range to delete.\n * @example editor.commands.deleteRange({ from: 1, to: 3 })\n */\n deleteRange: (range: Range) => ReturnType\n }\n }\n}\n\nexport const deleteRange: RawCommands['deleteRange'] =\n range =>\n ({ tr, dispatch }) => {\n const { from, to } = range\n\n if (dispatch) {\n tr.delete(from, to)\n }\n\n return true\n }\n", "import { deleteSelection as originalDeleteSelection } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n deleteSelection: {\n /**\n * Delete the selection, if there is one.\n * @example editor.commands.deleteSelection()\n */\n deleteSelection: () => ReturnType\n }\n }\n}\n\nexport const deleteSelection: RawCommands['deleteSelection'] =\n () =>\n ({ state, dispatch }) => {\n return originalDeleteSelection(state, dispatch)\n }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n enter: {\n /**\n * Trigger enter.\n * @example editor.commands.enter()\n */\n enter: () => ReturnType\n }\n }\n}\n\nexport const enter: RawCommands['enter'] =\n () =>\n ({ commands }) => {\n return commands.keyboardShortcut('Enter')\n }\n", "import { exitCode as originalExitCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n exitCode: {\n /**\n * Exit from a code block.\n * @example editor.commands.exitCode()\n */\n exitCode: () => ReturnType\n }\n }\n}\n\nexport const exitCode: RawCommands['exitCode'] =\n () =>\n ({ state, dispatch }) => {\n return originalExitCode(state, dispatch)\n }\n", "import type { MarkType } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n extendMarkRange: {\n /**\n * Extends the text selection to the current mark by type or name.\n * @param typeOrName The type or name of the mark.\n * @param attributes The attributes of the mark.\n * @example editor.commands.extendMarkRange('bold')\n * @example editor.commands.extendMarkRange('mention', { userId: \"1\" })\n */\n extendMarkRange: (\n /**\n * The type or name of the mark.\n */\n typeOrName: string | MarkType,\n\n /**\n * The attributes of the mark.\n */\n attributes?: Record,\n ) => ReturnType\n }\n }\n}\n\nexport const extendMarkRange: RawCommands['extendMarkRange'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n const type = getMarkType(typeOrName, state.schema)\n const { doc, selection } = tr\n const { $from, from, to } = selection\n\n if (dispatch) {\n const range = getMarkRange($from, type, attributes)\n\n if (range && range.from <= from && range.to >= to) {\n const newSelection = TextSelection.create(doc, range.from, range.to)\n\n tr.setSelection(newSelection)\n }\n }\n\n return true\n }\n", "export function isRegExp(value: any): value is RegExp {\n return Object.prototype.toString.call(value) === '[object RegExp]'\n}\n", "import { isRegExp } from './isRegExp.js'\n\n/**\n * Check if object1 includes object2\n * @param object1 Object\n * @param object2 Object\n */\nexport function objectIncludes(\n object1: Record,\n object2: Record,\n options: { strict: boolean } = { strict: true },\n): boolean {\n const keys = Object.keys(object2)\n\n if (!keys.length) {\n return true\n }\n\n return keys.every(key => {\n if (options.strict) {\n return object2[key] === object1[key]\n }\n\n if (isRegExp(object2[key])) {\n return object2[key].test(object1[key])\n }\n\n return object2[key] === object1[key]\n })\n}\n", "import type { Mark as ProseMirrorMark, MarkType, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Range } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\n\nfunction findMarkInSet(\n marks: ProseMirrorMark[],\n type: MarkType,\n attributes: Record = {},\n): ProseMirrorMark | undefined {\n return marks.find(item => {\n return (\n item.type === type &&\n objectIncludes(\n // Only check equality for the attributes that are provided\n Object.fromEntries(Object.keys(attributes).map(k => [k, item.attrs[k]])),\n attributes,\n )\n )\n })\n}\n\nfunction isMarkInSet(marks: ProseMirrorMark[], type: MarkType, attributes: Record = {}): boolean {\n return !!findMarkInSet(marks, type, attributes)\n}\n\n/**\n * Get the range of a mark at a resolved position.\n */\nexport function getMarkRange(\n /**\n * The position to get the mark range for.\n */\n $pos: ResolvedPos,\n /**\n * The mark type to get the range for.\n */\n type: MarkType,\n /**\n * The attributes to match against.\n * If not provided, only the first mark at the position will be matched.\n */\n attributes?: Record,\n): Range | void {\n if (!$pos || !type) {\n return\n }\n let start = $pos.parent.childAfter($pos.parentOffset)\n\n // If the cursor is at the start of a text node that does not have the mark, look backward\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n start = $pos.parent.childBefore($pos.parentOffset)\n }\n\n // If there is no text node with the mark even backward, return undefined\n if (!start.node || !start.node.marks.some(mark => mark.type === type)) {\n return\n }\n\n // Default to only matching against the first mark's attributes\n attributes = attributes || start.node.marks[0]?.attrs\n\n // We now know that the cursor is either at the start, middle or end of a text node with the specified mark\n // so we can look it up on the targeted mark\n const mark = findMarkInSet([...start.node.marks], type, attributes)\n\n if (!mark) {\n return\n }\n\n let startIndex = start.index\n let startPos = $pos.start() + start.offset\n let endIndex = startIndex + 1\n let endPos = startPos + start.node.nodeSize\n\n while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {\n startIndex -= 1\n startPos -= $pos.parent.child(startIndex).nodeSize\n }\n\n while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {\n endPos += $pos.parent.child(endIndex).nodeSize\n endIndex += 1\n }\n\n return {\n from: startPos,\n to: endPos,\n }\n}\n", "import type { MarkType, Schema } from '@tiptap/pm/model'\n\nexport function getMarkType(nameOrType: string | MarkType, schema: Schema): MarkType {\n if (typeof nameOrType === 'string') {\n if (!schema.marks[nameOrType]) {\n throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`)\n }\n\n return schema.marks[nameOrType]\n }\n\n return nameOrType\n}\n", "import type { Command, CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n first: {\n /**\n * Runs one command after the other and stops at the first which returns true.\n * @param commands The commands to run.\n * @example editor.commands.first([command1, command2])\n */\n first: (commands: Command[] | ((props: CommandProps) => Command[])) => ReturnType\n }\n }\n}\n\nexport const first: RawCommands['first'] = commands => props => {\n const items = typeof commands === 'function' ? commands(props) : commands\n\n for (let i = 0; i < items.length; i += 1) {\n if (items[i](props)) {\n return true\n }\n }\n\n return false\n}\n", "import { TextSelection } from '@tiptap/pm/state'\n\nexport function isTextSelection(value: unknown): value is TextSelection {\n return value instanceof TextSelection\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Selection, TextSelection } from '@tiptap/pm/state'\n\nimport type { FocusPosition } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\nexport function resolveFocusPosition(doc: ProseMirrorNode, position: FocusPosition = null): Selection | null {\n if (!position) {\n return null\n }\n\n const selectionAtStart = Selection.atStart(doc)\n const selectionAtEnd = Selection.atEnd(doc)\n\n if (position === 'start' || position === true) {\n return selectionAtStart\n }\n\n if (position === 'end') {\n return selectionAtEnd\n }\n\n const minPos = selectionAtStart.from\n const maxPos = selectionAtEnd.to\n\n if (position === 'all') {\n return TextSelection.create(doc, minMax(0, minPos, maxPos), minMax(doc.content.size, minPos, maxPos))\n }\n\n return TextSelection.create(doc, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos))\n}\n", "export function minMax(value = 0, min = 0, max = 0): number {\n return Math.min(Math.max(value, min), max)\n}\n", "export function isAndroid(): boolean {\n return navigator.platform === 'Android' || /android/i.test(navigator.userAgent)\n}\n", "export function isiOS(): boolean {\n return (\n ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator.platform) ||\n // iPad on iOS 13 detection\n (navigator.userAgent.includes('Mac') && 'ontouchend' in document)\n )\n}\n", "/**\n * Detects if the current browser is Safari (but not iOS Safari or Chrome).\n * @returns `true` if the browser is Safari, `false` otherwise.\n * @example\n * if (isSafari()) {\n * // Safari-specific handling\n * }\n */\nexport function isSafari(): boolean {\n return typeof navigator !== 'undefined' ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false\n}\n", "import { isTextSelection } from '../helpers/isTextSelection.js'\nimport { resolveFocusPosition } from '../helpers/resolveFocusPosition.js'\nimport type { FocusPosition, RawCommands } from '../types.js'\nimport { isAndroid } from '../utilities/isAndroid.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isSafari } from '../utilities/isSafari.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n focus: {\n /**\n * Focus the editor at the given position.\n * @param position The position to focus at.\n * @param options.scrollIntoView Scroll the focused position into view after focusing\n * @example editor.commands.focus()\n * @example editor.commands.focus(32, { scrollIntoView: false })\n */\n focus: (\n /**\n * The position to focus at.\n */\n position?: FocusPosition,\n\n /**\n * Optional options\n * @default { scrollIntoView: true }\n */\n options?: {\n scrollIntoView?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const focus: RawCommands['focus'] =\n (position = null, options = {}) =>\n ({ editor, view, tr, dispatch }) => {\n options = {\n scrollIntoView: true,\n ...options,\n }\n\n const delayedFocus = () => {\n // focus within `requestAnimationFrame` breaks focus on iOS and Android\n // so we have to call this\n if (isiOS() || isAndroid()) {\n ;(view.dom as HTMLElement).focus()\n }\n\n // Safari requires preventScroll to avoid the browser scrolling to the\n // top of the editor when focus is called before the selection is set.\n // We exclude iOS and Android since they are already handled above.\n // see: https://github.com/ueberdosis/tiptap/issues/7318\n if (isSafari() && !isiOS() && !isAndroid()) {\n ;(view.dom as HTMLElement).focus({ preventScroll: true })\n }\n\n // For React we have to focus asynchronously. Otherwise wild things happen.\n // see: https://github.com/ueberdosis/tiptap/issues/1520\n requestAnimationFrame(() => {\n if (!editor.isDestroyed) {\n view.focus()\n\n if (options?.scrollIntoView) {\n editor.commands.scrollIntoView()\n }\n }\n })\n }\n\n try {\n if ((view.hasFocus() && position === null) || position === false) {\n return true\n }\n } catch {\n // if view.hasFocus fails (view not mounted yet)\n // we will return false because there's nothing to focus\n return false\n }\n\n // we don’t try to resolve a NodeSelection or CellSelection\n if (dispatch && position === null && !isTextSelection(editor.state.selection)) {\n delayedFocus()\n return true\n }\n\n // pass through tr.doc instead of editor.state.doc\n // since transactions could change the editors state before this command has been run\n const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection\n const isSameSelection = editor.state.selection.eq(selection)\n\n if (dispatch) {\n if (!isSameSelection) {\n tr.setSelection(selection)\n }\n\n // `tr.setSelection` resets the stored marks\n // so we’ll restore them if the selection is the same as before\n if (isSameSelection && tr.storedMarks) {\n tr.setStoredMarks(tr.storedMarks)\n }\n\n delayedFocus()\n }\n\n return true\n }\n", "import type { CommandProps, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n forEach: {\n /**\n * Loop through an array of items.\n */\n forEach: (\n items: T[],\n fn: (\n item: T,\n props: CommandProps & {\n index: number\n },\n ) => boolean,\n ) => ReturnType\n }\n }\n}\n\nexport const forEach: RawCommands['forEach'] = (items, fn) => props => {\n return items.every((item, index) => fn(item, { ...props, index }))\n}\n", "import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport type { Content, RawCommands } from '../types.js'\n\nexport interface InsertContentOptions {\n /**\n * Options for parsing the content.\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to update the selection after inserting the content.\n */\n updateSelection?: boolean\n applyInputRules?: boolean\n applyPasteRules?: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n insertContent: {\n /**\n * Insert a node or string of HTML at the current position.\n * @example editor.commands.insertContent('

      Example

      ')\n * @example editor.commands.insertContent('

      Example

      ', { updateSelection: false })\n */\n insertContent: (\n /**\n * The ProseMirror content to insert.\n */\n value: Content | ProseMirrorNode | Fragment,\n\n /**\n * Optional options\n */\n options?: InsertContentOptions,\n ) => ReturnType\n }\n }\n}\n\nexport const insertContent: RawCommands['insertContent'] =\n (value, options) =>\n ({ tr, commands }) => {\n return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options)\n }\n", "import type { Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\n\nimport { createNodeFromContent } from '../helpers/createNodeFromContent.js'\nimport { selectionToInsertionEnd } from '../helpers/selectionToInsertionEnd.js'\nimport type { Content, Range, RawCommands } from '../types.js'\n\nexport interface InsertContentAtOptions {\n /**\n * Options for parsing the content.\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to update the selection after inserting the content.\n */\n updateSelection?: boolean\n\n /**\n * Whether to apply input rules after inserting the content.\n */\n applyInputRules?: boolean\n\n /**\n * Whether to apply paste rules after inserting the content.\n */\n applyPasteRules?: boolean\n\n /**\n * Whether to throw an error if the content is invalid.\n */\n errorOnInvalidContent?: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n insertContentAt: {\n /**\n * Insert a node or string of HTML at a specific position.\n * @example editor.commands.insertContentAt(0, '

      Example

      ')\n */\n insertContentAt: (\n /**\n * The position to insert the content at.\n */\n position: number | Range,\n\n /**\n * The ProseMirror content to insert.\n */\n value: Content | ProseMirrorNode | Fragment,\n\n /**\n * Optional options\n */\n options?: InsertContentAtOptions,\n ) => ReturnType\n }\n }\n}\n\nconst isFragment = (nodeOrFragment: ProseMirrorNode | Fragment): nodeOrFragment is Fragment => {\n return !('type' in nodeOrFragment)\n}\n\nexport const insertContentAt: RawCommands['insertContentAt'] =\n (position, value, options) =>\n ({ tr, dispatch, editor }) => {\n if (dispatch) {\n options = {\n parseOptions: editor.options.parseOptions,\n updateSelection: true,\n applyInputRules: false,\n applyPasteRules: false,\n ...options,\n }\n\n let content: Fragment | ProseMirrorNode\n\n const emitContentError = (error: Error) => {\n editor.emit('contentError', {\n editor,\n error,\n disableCollaboration: () => {\n if (\n 'collaboration' in editor.storage &&\n typeof editor.storage.collaboration === 'object' &&\n editor.storage.collaboration\n ) {\n ;(editor.storage.collaboration as any).isDisabled = true\n }\n },\n })\n }\n\n const parseOptions: ParseOptions = {\n preserveWhitespace: 'full',\n ...options.parseOptions,\n }\n\n // If `emitContentError` is enabled, we want to check the content for errors\n // but ignore them (do not remove the invalid content from the document)\n if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {\n try {\n createNodeFromContent(value, editor.schema, {\n parseOptions,\n errorOnInvalidContent: true,\n })\n } catch (e) {\n emitContentError(e as Error)\n }\n }\n\n try {\n content = createNodeFromContent(value, editor.schema, {\n parseOptions,\n errorOnInvalidContent: options.errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n } catch (e) {\n emitContentError(e as Error)\n return false\n }\n\n let { from, to } =\n typeof position === 'number' ? { from: position, to: position } : { from: position.from, to: position.to }\n\n let isOnlyTextContent = true\n let isOnlyBlockContent = true\n const nodes = isFragment(content) ? content : [content]\n\n nodes.forEach(node => {\n // check if added node is valid\n node.check()\n\n isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false\n\n isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false\n })\n\n // check if we can replace the wrapping node by\n // the newly inserted content\n // example:\n // replace an empty paragraph by an inserted image\n // instead of inserting the image below the paragraph\n if (from === to && isOnlyBlockContent) {\n const { parent } = tr.doc.resolve(from)\n const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount\n\n if (isEmptyTextBlock) {\n from -= 1\n to += 1\n }\n }\n\n let newContent\n\n // if there is only plain text we have to use `insertText`\n // because this will keep the current marks\n if (isOnlyTextContent) {\n // if value is string, we can use it directly\n // otherwise if it is an array, we have to join it\n if (Array.isArray(value)) {\n newContent = value.map(v => v.text || '').join('')\n } else if (value instanceof Fragment) {\n let text = ''\n\n value.forEach(node => {\n if (node.text) {\n text += node.text\n }\n })\n\n newContent = text\n } else if (typeof value === 'object' && !!value && !!value.text) {\n newContent = value.text\n } else {\n newContent = value as string\n }\n\n tr.insertText(newContent, from, to)\n } else {\n newContent = content\n\n const $from = tr.doc.resolve(from)\n const $fromNode = $from.node()\n const fromSelectionAtStart = $from.parentOffset === 0\n const isTextSelection = $fromNode.isText || $fromNode.isTextblock\n const hasContent = $fromNode.content.size > 0\n\n if (fromSelectionAtStart && isTextSelection && hasContent) {\n from = Math.max(0, from - 1)\n }\n\n tr.replaceWith(from, to, newContent)\n }\n\n // set cursor at end of inserted content\n if (options.updateSelection) {\n selectionToInsertionEnd(tr, tr.steps.length - 1, -1)\n }\n\n if (options.applyInputRules) {\n tr.setMeta('applyInputRules', { from, text: newContent })\n }\n\n if (options.applyPasteRules) {\n tr.setMeta('applyPasteRules', { from, text: newContent })\n }\n }\n\n return true\n }\n", "import type { ParseOptions } from '@tiptap/pm/model'\nimport { DOMParser, Fragment, Node as ProseMirrorNode, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\n\nexport type CreateNodeFromContentOptions = {\n slice?: boolean\n parseOptions?: ParseOptions\n errorOnInvalidContent?: boolean\n}\n\n/**\n * Takes a JSON or HTML content and creates a Prosemirror node or fragment from it.\n * @param content The JSON or HTML content to create the node from\n * @param schema The Prosemirror schema to use for the node\n * @param options Options for the parser\n * @returns The created Prosemirror node or fragment\n */\nexport function createNodeFromContent(\n content: Content | ProseMirrorNode | Fragment,\n schema: Schema,\n options?: CreateNodeFromContentOptions,\n): ProseMirrorNode | Fragment {\n if (content instanceof ProseMirrorNode || content instanceof Fragment) {\n return content\n }\n options = {\n slice: true,\n parseOptions: {},\n ...options,\n }\n\n const isJSONContent = typeof content === 'object' && content !== null\n const isTextContent = typeof content === 'string'\n\n if (isJSONContent) {\n try {\n const isArrayContent = Array.isArray(content) && content.length > 0\n\n // if the JSON Content is an array of nodes, create a fragment for each node\n if (isArrayContent) {\n return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)))\n }\n\n const node = schema.nodeFromJSON(content)\n\n if (options.errorOnInvalidContent) {\n node.check()\n }\n\n return node\n } catch (error) {\n if (options.errorOnInvalidContent) {\n throw new Error('[tiptap error]: Invalid JSON content', { cause: error as Error })\n }\n\n console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error)\n\n return createNodeFromContent('', schema, options)\n }\n }\n\n if (isTextContent) {\n // Check for invalid content\n if (options.errorOnInvalidContent) {\n let hasInvalidContent = false\n let invalidContent = ''\n\n // A copy of the current schema with a catch-all node at the end\n const contentCheckSchema = new Schema({\n topNode: schema.spec.topNode,\n marks: schema.spec.marks,\n // Prosemirror's schemas are executed such that: the last to execute, matches last\n // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle\n nodes: schema.spec.nodes.append({\n __tiptap__private__unknown__catch__all__node: {\n content: 'inline*',\n group: 'block',\n parseDOM: [\n {\n tag: '*',\n getAttrs: e => {\n // If this is ever called, we know that the content has something that we don't know how to handle in the schema\n hasInvalidContent = true\n // Try to stringify the element for a more helpful error message\n invalidContent = typeof e === 'string' ? e : e.outerHTML\n return null\n },\n },\n ],\n },\n }),\n })\n\n if (options.slice) {\n DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions)\n } else {\n DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions)\n }\n\n if (options.errorOnInvalidContent && hasInvalidContent) {\n throw new Error('[tiptap error]: Invalid HTML content', {\n cause: new Error(`Invalid element found: ${invalidContent}`),\n })\n }\n }\n\n const parser = DOMParser.fromSchema(schema)\n\n if (options.slice) {\n return parser.parseSlice(elementFromString(content), options.parseOptions).content\n }\n\n return parser.parse(elementFromString(content), options.parseOptions)\n }\n\n return createNodeFromContent('', schema, options)\n}\n", "const removeWhitespaces = (node: HTMLElement) => {\n const children = node.childNodes\n\n for (let i = children.length - 1; i >= 0; i -= 1) {\n const child = children[i]\n\n if (child.nodeType === 3 && child.nodeValue && /^(\\n\\s\\s|\\n)$/.test(child.nodeValue)) {\n node.removeChild(child)\n } else if (child.nodeType === 1) {\n removeWhitespaces(child as HTMLElement)\n }\n }\n\n return node\n}\n\nexport function elementFromString(value: string): HTMLElement {\n if (typeof window === 'undefined') {\n throw new Error('[tiptap error]: there is no window object available, so this function cannot be used')\n }\n // add a wrapper to preserve leading and trailing whitespace\n const wrappedValue = `${value}`\n\n const html = new window.DOMParser().parseFromString(wrappedValue, 'text/html').body\n\n return removeWhitespaces(html)\n}\n", "import type { Transaction } from '@tiptap/pm/state'\nimport { Selection } from '@tiptap/pm/state'\nimport { ReplaceAroundStep, ReplaceStep } from '@tiptap/pm/transform'\n\n// source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466\nexport function selectionToInsertionEnd(tr: Transaction, startLen: number, bias: number) {\n const last = tr.steps.length - 1\n\n if (last < startLen) {\n return\n }\n\n const step = tr.steps[last]\n\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {\n return\n }\n\n const map = tr.mapping.maps[last]\n let end = 0\n\n map.forEach((_from, _to, _newFrom, newTo) => {\n if (end === 0) {\n end = newTo\n }\n })\n\n tr.setSelection(Selection.near(tr.doc.resolve(end), bias))\n}\n", "import {\n joinBackward as originalJoinBackward,\n joinDown as originalJoinDown,\n joinForward as originalJoinForward,\n joinUp as originalJoinUp,\n} from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n joinUp: {\n /**\n * Join the selected block or, if there is a text selection, the closest ancestor block of the selection that can be joined, with the sibling above it.\n * @example editor.commands.joinUp()\n */\n joinUp: () => ReturnType\n }\n joinDown: {\n /**\n * Join the selected block, or the closest ancestor of the selection that can be joined, with the sibling after it.\n * @example editor.commands.joinDown()\n */\n joinDown: () => ReturnType\n }\n joinBackward: {\n /**\n * If the selection is empty and at the start of a textblock, try to reduce the distance between that block and the one before it—if there's a block directly before it that can be joined, join them.\n * If not, try to move the selected block closer to the next one in the document structure by lifting it out of its\n * parent or moving it into a parent of the previous block. Will use the view for accurate (bidi-aware) start-of-textblock detection if given.\n * @example editor.commands.joinBackward()\n */\n joinBackward: () => ReturnType\n }\n joinForward: {\n /**\n * If the selection is empty and the cursor is at the end of a textblock, try to reduce or remove the boundary between that block and the one after it,\n * either by joining them or by moving the other block closer to this one in the tree structure.\n * Will use the view for accurate start-of-textblock detection if given.\n * @example editor.commands.joinForward()\n */\n joinForward: () => ReturnType\n }\n }\n}\n\nexport const joinUp: RawCommands['joinUp'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinUp(state, dispatch)\n }\n\nexport const joinDown: RawCommands['joinDown'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinDown(state, dispatch)\n }\n\nexport const joinBackward: RawCommands['joinBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinBackward(state, dispatch)\n }\n\nexport const joinForward: RawCommands['joinForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalJoinForward(state, dispatch)\n }\n", "import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n joinItemBackward: {\n /**\n * Join two items backward.\n * @example editor.commands.joinItemBackward()\n */\n joinItemBackward: () => ReturnType\n }\n }\n}\n\nexport const joinItemBackward: RawCommands['joinItemBackward'] =\n () =>\n ({ state, dispatch, tr }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, -1)\n\n if (point === null || point === undefined) {\n return false\n }\n\n tr.join(point, 2)\n\n if (dispatch) {\n dispatch(tr)\n }\n\n return true\n } catch {\n return false\n }\n }\n", "import { joinPoint } from '@tiptap/pm/transform'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n joinItemForward: {\n /**\n * Join two items Forwards.\n * @example editor.commands.joinItemForward()\n */\n joinItemForward: () => ReturnType\n }\n }\n}\n\nexport const joinItemForward: RawCommands['joinItemForward'] =\n () =>\n ({ state, dispatch, tr }) => {\n try {\n const point = joinPoint(state.doc, state.selection.$from.pos, +1)\n\n if (point === null || point === undefined) {\n return false\n }\n\n tr.join(point, 2)\n\n if (dispatch) {\n dispatch(tr)\n }\n\n return true\n } catch {\n return false\n }\n }\n", "import { joinTextblockBackward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n joinTextblockBackward: {\n /**\n * A more limited form of joinBackward that only tries to join the current textblock to the one before it, if the cursor is at the start of a textblock.\n */\n joinTextblockBackward: () => ReturnType\n }\n }\n}\n\nexport const joinTextblockBackward: RawCommands['joinTextblockBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalCommand(state, dispatch)\n }\n", "import { joinTextblockForward as originalCommand } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n joinTextblockForward: {\n /**\n * A more limited form of joinForward that only tries to join the current textblock to the one after it, if the cursor is at the end of a textblock.\n */\n joinTextblockForward: () => ReturnType\n }\n }\n}\n\nexport const joinTextblockForward: RawCommands['joinTextblockForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalCommand(state, dispatch)\n }\n", "export function isMacOS(): boolean {\n return typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false\n}\n", "import type { RawCommands } from '../types.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nfunction normalizeKeyName(name: string) {\n const parts = name.split(/-(?!$)/)\n let result = parts[parts.length - 1]\n\n if (result === 'Space') {\n result = ' '\n }\n\n let alt\n let ctrl\n let shift\n let meta\n\n for (let i = 0; i < parts.length - 1; i += 1) {\n const mod = parts[i]\n\n if (/^(cmd|meta|m)$/i.test(mod)) {\n meta = true\n } else if (/^a(lt)?$/i.test(mod)) {\n alt = true\n } else if (/^(c|ctrl|control)$/i.test(mod)) {\n ctrl = true\n } else if (/^s(hift)?$/i.test(mod)) {\n shift = true\n } else if (/^mod$/i.test(mod)) {\n if (isiOS() || isMacOS()) {\n meta = true\n } else {\n ctrl = true\n }\n } else {\n throw new Error(`Unrecognized modifier name: ${mod}`)\n }\n }\n\n if (alt) {\n result = `Alt-${result}`\n }\n\n if (ctrl) {\n result = `Ctrl-${result}`\n }\n\n if (meta) {\n result = `Meta-${result}`\n }\n\n if (shift) {\n result = `Shift-${result}`\n }\n\n return result\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n keyboardShortcut: {\n /**\n * Trigger a keyboard shortcut.\n * @param name The name of the keyboard shortcut.\n * @example editor.commands.keyboardShortcut('Mod-b')\n */\n keyboardShortcut: (name: string) => ReturnType\n }\n }\n}\n\nexport const keyboardShortcut: RawCommands['keyboardShortcut'] =\n name =>\n ({ editor, view, tr, dispatch }) => {\n const keys = normalizeKeyName(name).split(/-(?!$)/)\n const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item))\n const event = new KeyboardEvent('keydown', {\n key: key === 'Space' ? ' ' : key,\n altKey: keys.includes('Alt'),\n ctrlKey: keys.includes('Ctrl'),\n metaKey: keys.includes('Meta'),\n shiftKey: keys.includes('Shift'),\n bubbles: true,\n cancelable: true,\n })\n\n const capturedTransaction = editor.captureTransaction(() => {\n view.someProp('handleKeyDown', f => f(view, event))\n })\n\n capturedTransaction?.steps.forEach(step => {\n const newStep = step.map(tr.mapping)\n\n if (newStep && dispatch) {\n tr.maybeStep(newStep)\n }\n })\n\n return true\n }\n", "import { lift as originalLift } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n lift: {\n /**\n * Removes an existing wrap if possible lifting the node out of it\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.lift('paragraph')\n * @example editor.commands.lift('heading', { level: 1 })\n */\n lift: (typeOrName: string | NodeType, attributes?: Record) => ReturnType\n }\n }\n}\n\nexport const lift: RawCommands['lift'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n if (!isActive) {\n return false\n }\n\n return originalLift(state, dispatch)\n }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { NodeRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getNodeType } from './getNodeType.js'\n\nexport function isNodeActive(\n state: EditorState,\n typeOrName: NodeType | string | null,\n attributes: Record = {},\n): boolean {\n const { from, to, empty } = state.selection\n const type = typeOrName ? getNodeType(typeOrName, state.schema) : null\n\n const nodeRanges: NodeRange[] = []\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isText) {\n return\n }\n\n const relativeFrom = Math.max(from, pos)\n const relativeTo = Math.min(to, pos + node.nodeSize)\n\n nodeRanges.push({\n node,\n from: relativeFrom,\n to: relativeTo,\n })\n })\n\n const selectionRange = to - from\n const matchedNodeRanges = nodeRanges\n .filter(nodeRange => {\n if (!type) {\n return true\n }\n\n return type.name === nodeRange.node.type.name\n })\n .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }))\n\n if (empty) {\n return !!matchedNodeRanges.length\n }\n\n const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0)\n\n return range >= selectionRange\n}\n", "import { liftEmptyBlock as originalLiftEmptyBlock } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n liftEmptyBlock: {\n /**\n * If the cursor is in an empty textblock that can be lifted, lift the block.\n * @example editor.commands.liftEmptyBlock()\n */\n liftEmptyBlock: () => ReturnType\n }\n }\n}\n\nexport const liftEmptyBlock: RawCommands['liftEmptyBlock'] =\n () =>\n ({ state, dispatch }) => {\n return originalLiftEmptyBlock(state, dispatch)\n }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { liftListItem as originalLiftListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n liftListItem: {\n /**\n * Create a command to lift the list item around the selection up into a wrapping list.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.liftListItem('listItem')\n */\n liftListItem: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const liftListItem: RawCommands['liftListItem'] =\n typeOrName =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalLiftListItem(type)(state, dispatch)\n }\n", "import { newlineInCode as originalNewlineInCode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n newlineInCode: {\n /**\n * Add a newline character in code.\n * @example editor.commands.newlineInCode()\n */\n newlineInCode: () => ReturnType\n }\n }\n}\n\nexport const newlineInCode: RawCommands['newlineInCode'] =\n () =>\n ({ state, dispatch }) => {\n return originalNewlineInCode(state, dispatch)\n }\n", "import type { Schema } from '@tiptap/pm/model'\n\n/**\n * Get the type of a schema item by its name.\n * @param name The name of the schema item\n * @param schema The Prosemiror schema to search in\n * @returns The type of the schema item (`node` or `mark`), or null if it doesn't exist\n */\nexport function getSchemaTypeNameByName(name: string, schema: Schema): 'node' | 'mark' | null {\n if (schema.nodes[name]) {\n return 'node'\n }\n\n if (schema.marks[name]) {\n return 'mark'\n }\n\n return null\n}\n", "/**\n * Remove a property or an array of properties from an object\n * @param obj Object\n * @param key Key to remove\n */\nexport function deleteProps(obj: Record, propOrProps: string | string[]): Record {\n const props = typeof propOrProps === 'string' ? [propOrProps] : propOrProps\n\n return Object.keys(obj).reduce((newObj: Record, prop) => {\n if (!props.includes(prop)) {\n newObj[prop] = obj[prop]\n }\n\n return newObj\n }, {})\n}\n", "import type { MarkType, NodeType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\nimport { deleteProps } from '../utilities/deleteProps.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n resetAttributes: {\n /**\n * Resets some node attributes to the default value.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node to reset.\n * @example editor.commands.resetAttributes('heading', 'level')\n */\n resetAttributes: (typeOrName: string | NodeType | MarkType, attributes: string | string[]) => ReturnType\n }\n }\n}\n\nexport const resetAttributes: RawCommands['resetAttributes'] =\n (typeOrName, attributes) =>\n ({ tr, state, dispatch }) => {\n let nodeType: NodeType | null = null\n let markType: MarkType | null = null\n\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (!schemaType) {\n return false\n }\n\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName as NodeType, state.schema)\n }\n\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName as MarkType, state.schema)\n }\n\n let canReset = false\n\n tr.selection.ranges.forEach(range => {\n state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {\n if (nodeType && nodeType === node.type) {\n canReset = true\n\n if (dispatch) {\n tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes))\n }\n }\n\n if (markType && node.marks.length) {\n node.marks.forEach(mark => {\n if (markType === mark.type) {\n canReset = true\n\n if (dispatch) {\n tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)))\n }\n }\n })\n }\n })\n })\n\n return canReset\n }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n scrollIntoView: {\n /**\n * Scroll the selection into view.\n * @example editor.commands.scrollIntoView()\n */\n scrollIntoView: () => ReturnType\n }\n }\n}\n\nexport const scrollIntoView: RawCommands['scrollIntoView'] =\n () =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n tr.scrollIntoView()\n }\n\n return true\n }\n", "import { AllSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n selectAll: {\n /**\n * Select the whole document.\n * @example editor.commands.selectAll()\n */\n selectAll: () => ReturnType\n }\n }\n}\n\nexport const selectAll: RawCommands['selectAll'] =\n () =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const selection = new AllSelection(tr.doc)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n", "import { selectNodeBackward as originalSelectNodeBackward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n selectNodeBackward: {\n /**\n * Select a node backward.\n * @example editor.commands.selectNodeBackward()\n */\n selectNodeBackward: () => ReturnType\n }\n }\n}\n\nexport const selectNodeBackward: RawCommands['selectNodeBackward'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectNodeBackward(state, dispatch)\n }\n", "import { selectNodeForward as originalSelectNodeForward } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n selectNodeForward: {\n /**\n * Select a node forward.\n * @example editor.commands.selectNodeForward()\n */\n selectNodeForward: () => ReturnType\n }\n }\n}\n\nexport const selectNodeForward: RawCommands['selectNodeForward'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectNodeForward(state, dispatch)\n }\n", "import { selectParentNode as originalSelectParentNode } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n selectParentNode: {\n /**\n * Select the parent node.\n * @example editor.commands.selectParentNode()\n */\n selectParentNode: () => ReturnType\n }\n }\n}\n\nexport const selectParentNode: RawCommands['selectParentNode'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectParentNode(state, dispatch)\n }\n", "// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockEnd as originalSelectTextblockEnd } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n selectTextblockEnd: {\n /**\n * Moves the cursor to the end of current text block.\n * @example editor.commands.selectTextblockEnd()\n */\n selectTextblockEnd: () => ReturnType\n }\n }\n}\n\nexport const selectTextblockEnd: RawCommands['selectTextblockEnd'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectTextblockEnd(state, dispatch)\n }\n", "// @ts-ignore\n// TODO: add types to @types/prosemirror-commands\nimport { selectTextblockStart as originalSelectTextblockStart } from '@tiptap/pm/commands'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n selectTextblockStart: {\n /**\n * Moves the cursor to the start of current text block.\n * @example editor.commands.selectTextblockStart()\n */\n selectTextblockStart: () => ReturnType\n }\n }\n}\n\nexport const selectTextblockStart: RawCommands['selectTextblockStart'] =\n () =>\n ({ state, dispatch }) => {\n return originalSelectTextblockStart(state, dispatch)\n }\n", "import type { Fragment, Node as ProseMirrorNode, ParseOptions, Schema } from '@tiptap/pm/model'\n\nimport type { Content } from '../types.js'\nimport { createNodeFromContent } from './createNodeFromContent.js'\n\n/**\n * Create a new Prosemirror document node from content.\n * @param content The JSON or HTML content to create the document from\n * @param schema The Prosemirror schema to use for the document\n * @param parseOptions Options for the parser\n * @returns The created Prosemirror document node\n */\nexport function createDocument(\n content: Content | ProseMirrorNode | Fragment,\n schema: Schema,\n parseOptions: ParseOptions = {},\n options: { errorOnInvalidContent?: boolean } = {},\n): ProseMirrorNode {\n return createNodeFromContent(content, schema, {\n slice: false,\n parseOptions,\n errorOnInvalidContent: options.errorOnInvalidContent,\n }) as ProseMirrorNode\n}\n", "import type { Fragment, Node as ProseMirrorNode, ParseOptions } from '@tiptap/pm/model'\n\nimport { createDocument } from '../helpers/createDocument.js'\nimport type { Content, RawCommands } from '../types.js'\n\nexport interface SetContentOptions {\n /**\n * Options for parsing the content.\n * @default {}\n */\n parseOptions?: ParseOptions\n\n /**\n * Whether to throw an error if the content is invalid.\n */\n errorOnInvalidContent?: boolean\n\n /**\n * Whether to emit an update event.\n * @default true\n */\n emitUpdate?: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n setContent: {\n /**\n * Replace the whole document with new content.\n * @param content The new content.\n * @param emitUpdate Whether to emit an update event.\n * @param parseOptions Options for parsing the content.\n * @example editor.commands.setContent('

      Example text

      ')\n */\n setContent: (\n /**\n * The new content.\n */\n content: Content | Fragment | ProseMirrorNode,\n\n /**\n * Options for `setContent`.\n */\n options?: SetContentOptions,\n ) => ReturnType\n }\n }\n}\n\nexport const setContent: RawCommands['setContent'] =\n (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) =>\n ({ editor, tr, dispatch, commands }) => {\n const { doc } = tr\n\n // This is to keep backward compatibility with the previous behavior\n // TODO remove this in the next major version\n if (parseOptions.preserveWhitespace !== 'full') {\n const document = createDocument(content, editor.schema, parseOptions, {\n errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n\n if (dispatch) {\n tr.replaceWith(0, doc.content.size, document).setMeta('preventUpdate', !emitUpdate)\n }\n return true\n }\n\n if (dispatch) {\n tr.setMeta('preventUpdate', !emitUpdate)\n }\n\n return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {\n parseOptions,\n errorOnInvalidContent: errorOnInvalidContent ?? editor.options.enableContentCheck,\n })\n }\n", "import type { Mark, MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkType } from './getMarkType.js'\n\nexport function getMarkAttributes(state: EditorState, typeOrName: string | MarkType): Record {\n const type = getMarkType(typeOrName, state.schema)\n const { from, to, empty } = state.selection\n const marks: Mark[] = []\n\n if (empty) {\n if (state.storedMarks) {\n marks.push(...state.storedMarks)\n }\n\n marks.push(...state.selection.$head.marks())\n } else {\n state.doc.nodesBetween(from, to, node => {\n marks.push(...node.marks)\n })\n }\n\n const mark = marks.find(markItem => markItem.type.name === type.name)\n\n if (!mark) {\n return {}\n }\n\n return { ...mark.attrs }\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { Transform } from '@tiptap/pm/transform'\n\n/**\n * Returns a new `Transform` based on all steps of the passed transactions.\n * @param oldDoc The Prosemirror node to start from\n * @param transactions The transactions to combine\n * @returns A new `Transform` with all steps of the passed transactions\n */\nexport function combineTransactionSteps(oldDoc: ProseMirrorNode, transactions: Transaction[]): Transform {\n const transform = new Transform(oldDoc)\n\n transactions.forEach(transaction => {\n transaction.steps.forEach(step => {\n transform.step(step)\n })\n })\n\n return transform\n}\n", "import type { ContentMatch, NodeType } from '@tiptap/pm/model'\n\n/**\n * Gets the default block type at a given match\n * @param match The content match to get the default block type from\n * @returns The default block type or null\n */\nexport function defaultBlockAt(match: ContentMatch): NodeType | null {\n for (let i = 0; i < match.edgeCount; i += 1) {\n const { type } = match.edge(i)\n\n if (type.isTextblock && !type.hasRequiredAttrs()) {\n return type\n }\n }\n\n return null\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate } from '../types.js'\n\n/**\n * Find children inside a Prosemirror node that match a predicate.\n * @param node The Prosemirror node to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildren(node: ProseMirrorNode, predicate: Predicate): NodeWithPos[] {\n const nodesWithPos: NodeWithPos[] = []\n\n node.descendants((child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n })\n }\n })\n\n return nodesWithPos\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { NodeWithPos, Predicate, Range } from '../types.js'\n\n/**\n * Same as `findChildren` but searches only within a `range`.\n * @param node The Prosemirror node to search in\n * @param range The range to search in\n * @param predicate The predicate to match\n * @returns An array of nodes with their positions\n */\nexport function findChildrenInRange(node: ProseMirrorNode, range: Range, predicate: Predicate): NodeWithPos[] {\n const nodesWithPos: NodeWithPos[] = []\n\n // if (range.from === range.to) {\n // const nodeAt = node.nodeAt(range.from)\n\n // if (nodeAt) {\n // nodesWithPos.push({\n // node: nodeAt,\n // pos: range.from,\n // })\n // }\n // }\n\n node.nodesBetween(range.from, range.to, (child, pos) => {\n if (predicate(child)) {\n nodesWithPos.push({\n node: child,\n pos,\n })\n }\n })\n\n return nodesWithPos\n}\n", "import type { Node as ProseMirrorNode, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Predicate } from '../types.js'\n\n/**\n * Finds the closest parent node to a resolved position that matches a predicate.\n * @param $pos The resolved position to search from\n * @param predicate The predicate to match\n * @returns The closest parent node to the resolved position that matches the predicate\n * @example ```js\n * findParentNodeClosestToPos($from, node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNodeClosestToPos(\n $pos: ResolvedPos,\n predicate: Predicate,\n):\n | {\n pos: number\n start: number\n depth: number\n node: ProseMirrorNode\n }\n | undefined {\n for (let i = $pos.depth; i > 0; i -= 1) {\n const node = $pos.node(i)\n\n if (predicate(node)) {\n return {\n pos: i > 0 ? $pos.before(i) : 0,\n start: $pos.start(i),\n depth: i,\n node,\n }\n }\n }\n}\n", "import type { Selection } from '@tiptap/pm/state'\n\nimport type { Predicate } from '../types.js'\nimport { findParentNodeClosestToPos } from './findParentNodeClosestToPos.js'\n\n/**\n * Finds the closest parent node to the current selection that matches a predicate.\n * @param predicate The predicate to match\n * @returns A command that finds the closest parent node to the current selection that matches the predicate\n * @example ```js\n * findParentNode(node => node.type.name === 'paragraph')\n * ```\n */\nexport function findParentNode(\n predicate: Predicate,\n): (selection: Selection) => ReturnType {\n return (selection: Selection) => findParentNodeClosestToPos(selection.$from, predicate)\n}\n", "import type { ExtensionConfig } from '../Extension.js'\nimport type { MarkConfig } from '../Mark.js'\nimport type { NodeConfig } from '../Node.js'\nimport type { AnyExtension, MaybeThisParameterType, RemoveThis } from '../types.js'\n\n/**\n * Returns a field from an extension\n * @param extension The Tiptap extension\n * @param field The field, for example `renderHTML` or `priority`\n * @param context The context object that should be passed as `this` into the function\n * @returns The field value\n */\nexport function getExtensionField(\n extension: E,\n field: keyof ExtensionConfig | keyof MarkConfig | keyof NodeConfig,\n context?: Omit, 'parent'>,\n): RemoveThis {\n if (extension.config[field as keyof typeof extension.config] === undefined && extension.parent) {\n return getExtensionField(extension.parent, field, context)\n }\n\n if (typeof extension.config[field as keyof typeof extension.config] === 'function') {\n const value = (extension.config[field as keyof typeof extension.config] as any).bind({\n ...context,\n parent: extension.parent ? getExtensionField(extension.parent, field, context) : null,\n })\n\n return value\n }\n\n return extension.config[field as keyof typeof extension.config] as RemoveThis\n}\n", "import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Create a flattened array of extensions by traversing the `addExtensions` field.\n * @param extensions An array of Tiptap extensions\n * @returns A flattened array of Tiptap extensions\n */\nexport function flattenExtensions(extensions: Extensions): Extensions {\n return (\n extensions\n .map(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n\n const addExtensions = getExtensionField(extension, 'addExtensions', context)\n\n if (addExtensions) {\n return [extension, ...flattenExtensions(addExtensions())]\n }\n\n return extension\n })\n // `Infinity` will break TypeScript so we set a number that is probably high enough\n .flat(10)\n )\n}\n", "import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent } from '../types.js'\nimport { getHTMLFromFragment } from './getHTMLFromFragment.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate HTML from a JSONContent\n * @param doc The JSONContent to generate HTML from\n * @param extensions The extensions to use for the schema\n * @returns The generated HTML\n */\nexport function generateHTML(doc: JSONContent, extensions: Extensions): string {\n const schema = getSchema(extensions)\n const contentNode = Node.fromJSON(schema, doc)\n\n return getHTMLFromFragment(contentNode.content, schema)\n}\n", "import type { Fragment, Schema } from '@tiptap/pm/model'\nimport { DOMSerializer } from '@tiptap/pm/model'\n\nexport function getHTMLFromFragment(fragment: Fragment, schema: Schema): string {\n const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment)\n\n const temporaryDocument = document.implementation.createHTMLDocument()\n const container = temporaryDocument.createElement('div')\n\n container.appendChild(documentFragment)\n\n return container.innerHTML\n}\n", "import type { MarkSpec, NodeSpec, TagParseRule } from '@tiptap/pm/model'\nimport { Schema } from '@tiptap/pm/model'\n\nimport type { Editor, MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { isEmptyObject } from '../utilities/isEmptyObject.js'\nimport { getAttributesFromExtensions } from './getAttributesFromExtensions.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { getRenderedAttributes } from './getRenderedAttributes.js'\nimport { injectExtensionAttributesToParseRule } from './injectExtensionAttributesToParseRule.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nfunction cleanUpSchemaItem(data: T) {\n return Object.fromEntries(\n // @ts-ignore\n Object.entries(data).filter(([key, value]) => {\n if (key === 'attrs' && isEmptyObject(value as object | undefined)) {\n return false\n }\n\n return value !== null && value !== undefined\n }),\n ) as T\n}\n\n/**\n * Builds an attribute spec tuple for ProseMirror schema from an extension attribute.\n * @param extensionAttribute The extension attribute to build the spec for\n * @returns A tuple of [attributeName, spec]\n */\nfunction buildAttributeSpec(\n extensionAttribute: ReturnType[number],\n): [string, Record] {\n const spec: Record = {}\n\n // Only include 'default' if the attribute is not required and default is set on the attribute\n if (!extensionAttribute?.attribute?.isRequired && 'default' in (extensionAttribute?.attribute || {})) {\n spec.default = extensionAttribute.attribute.default\n }\n\n // Only include 'validate' if it's defined\n if (extensionAttribute?.attribute?.validate !== undefined) {\n spec.validate = extensionAttribute.attribute.validate\n }\n\n return [extensionAttribute.name, spec]\n}\n\n/**\n * Creates a new Prosemirror schema based on the given extensions.\n * @param extensions An array of Tiptap extensions\n * @param editor The editor instance\n * @returns A Prosemirror schema\n */\nexport function getSchemaByResolvedExtensions(extensions: Extensions, editor?: Editor): Schema {\n const allAttributes = getAttributesFromExtensions(extensions)\n const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n const topNode = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))?.name\n\n const nodes = Object.fromEntries(\n nodeExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n }\n\n const extraNodeFields = extensions.reduce((fields, e) => {\n const extendNodeSchema = getExtensionField(e, 'extendNodeSchema', context)\n\n return {\n ...fields,\n ...(extendNodeSchema ? extendNodeSchema(extension) : {}),\n }\n }, {})\n\n const schema: NodeSpec = cleanUpSchemaItem({\n ...extraNodeFields,\n content: callOrReturn(getExtensionField(extension, 'content', context)),\n marks: callOrReturn(getExtensionField(extension, 'marks', context)),\n group: callOrReturn(getExtensionField(extension, 'group', context)),\n inline: callOrReturn(getExtensionField(extension, 'inline', context)),\n atom: callOrReturn(getExtensionField(extension, 'atom', context)),\n selectable: callOrReturn(getExtensionField(extension, 'selectable', context)),\n draggable: callOrReturn(getExtensionField(extension, 'draggable', context)),\n code: callOrReturn(getExtensionField(extension, 'code', context)),\n whitespace: callOrReturn(getExtensionField(extension, 'whitespace', context)),\n linebreakReplacement: callOrReturn(\n getExtensionField(extension, 'linebreakReplacement', context),\n ),\n defining: callOrReturn(getExtensionField(extension, 'defining', context)),\n isolating: callOrReturn(getExtensionField(extension, 'isolating', context)),\n attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)),\n })\n\n const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context))\n\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule =>\n injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n ) as TagParseRule[]\n }\n\n const renderHTML = getExtensionField(extension, 'renderHTML', context)\n\n if (renderHTML) {\n schema.toDOM = node =>\n renderHTML({\n node,\n HTMLAttributes: getRenderedAttributes(node, extensionAttributes),\n })\n }\n\n const renderText = getExtensionField(extension, 'renderText', context)\n\n if (renderText) {\n schema.toText = renderText\n }\n\n return [extension.name, schema]\n }),\n )\n\n const marks = Object.fromEntries(\n markExtensions.map(extension => {\n const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n editor,\n }\n\n const extraMarkFields = extensions.reduce((fields, e) => {\n const extendMarkSchema = getExtensionField(e, 'extendMarkSchema', context)\n\n return {\n ...fields,\n ...(extendMarkSchema ? extendMarkSchema(extension as any) : {}),\n }\n }, {})\n\n const schema: MarkSpec = cleanUpSchemaItem({\n ...extraMarkFields,\n inclusive: callOrReturn(getExtensionField(extension, 'inclusive', context)),\n excludes: callOrReturn(getExtensionField(extension, 'excludes', context)),\n group: callOrReturn(getExtensionField(extension, 'group', context)),\n spanning: callOrReturn(getExtensionField(extension, 'spanning', context)),\n code: callOrReturn(getExtensionField(extension, 'code', context)),\n attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)),\n })\n\n const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context))\n\n if (parseHTML) {\n schema.parseDOM = parseHTML.map(parseRule =>\n injectExtensionAttributesToParseRule(parseRule, extensionAttributes),\n )\n }\n\n const renderHTML = getExtensionField(extension, 'renderHTML', context)\n\n if (renderHTML) {\n schema.toDOM = mark =>\n renderHTML({\n mark,\n HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),\n })\n }\n\n return [extension.name, schema]\n }),\n )\n\n return new Schema({\n topNode,\n nodes,\n marks,\n })\n}\n", "// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport function isFunction(value: any): value is Function {\n return typeof value === 'function'\n}\n", "import type { MaybeReturnType } from '../types.js'\nimport { isFunction } from './isFunction.js'\n\n/**\n * Optionally calls `value` as a function.\n * Otherwise it is returned directly.\n * @param value Function or any value.\n * @param context Optional context to bind to function.\n * @param props Optional props to pass to function.\n */\nexport function callOrReturn(value: T, context: any = undefined, ...props: any[]): MaybeReturnType {\n if (isFunction(value)) {\n if (context) {\n return value.bind(context)(...props)\n }\n\n return value(...props)\n }\n\n return value as MaybeReturnType\n}\n", "export function isEmptyObject(value = {}): boolean {\n return Object.keys(value).length === 0 && value.constructor === Object\n}\n", "import type { Extension } from '../Extension.js'\nimport type { Mark } from '../Mark.js'\nimport type { Node } from '../Node.js'\nimport type { Extensions } from '../types.js'\n\nexport function splitExtensions(extensions: Extensions) {\n const baseExtensions = extensions.filter(extension => extension.type === 'extension') as Extension[]\n const nodeExtensions = extensions.filter(extension => extension.type === 'node') as Node[]\n const markExtensions = extensions.filter(extension => extension.type === 'mark') as Mark[]\n\n return {\n baseExtensions,\n nodeExtensions,\n markExtensions,\n }\n}\n", "import type { MarkConfig, NodeConfig } from '../index.js'\nimport type { AnyConfig, Attribute, Attributes, ExtensionAttribute, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\nimport { splitExtensions } from './splitExtensions.js'\n\n/**\n * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.\n * @param extensions List of extensions\n */\nexport function getAttributesFromExtensions(extensions: Extensions): ExtensionAttribute[] {\n const extensionAttributes: ExtensionAttribute[] = []\n const { nodeExtensions, markExtensions } = splitExtensions(extensions)\n const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]\n const defaultAttribute: Required> & Pick = {\n default: null,\n validate: undefined,\n rendered: true,\n renderHTML: null,\n parseHTML: null,\n keepOnSplit: true,\n isRequired: false,\n }\n\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n extensions: nodeAndMarkExtensions,\n }\n\n const addGlobalAttributes = getExtensionField(\n extension,\n 'addGlobalAttributes',\n context,\n )\n\n if (!addGlobalAttributes) {\n return\n }\n\n const globalAttributes = addGlobalAttributes()\n\n globalAttributes.forEach(globalAttribute => {\n globalAttribute.types.forEach(type => {\n Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => {\n extensionAttributes.push({\n type,\n name,\n attribute: {\n ...defaultAttribute,\n ...attribute,\n },\n })\n })\n })\n })\n })\n\n nodeAndMarkExtensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n\n const addAttributes = getExtensionField(\n extension,\n 'addAttributes',\n context,\n )\n\n if (!addAttributes) {\n return\n }\n\n // TODO: remove `as Attributes`\n const attributes = addAttributes() as Attributes\n\n Object.entries(attributes).forEach(([name, attribute]) => {\n const mergedAttr = {\n ...defaultAttribute,\n ...attribute,\n }\n\n if (typeof mergedAttr?.default === 'function') {\n mergedAttr.default = mergedAttr.default()\n }\n\n if (mergedAttr?.isRequired && mergedAttr?.default === undefined) {\n delete mergedAttr.default\n }\n\n extensionAttributes.push({\n type: extension.name,\n name,\n attribute: mergedAttr,\n })\n })\n })\n\n return extensionAttributes\n}\n", "export function mergeAttributes(...objects: Record[]): Record {\n return objects\n .filter(item => !!item)\n .reduce((items, item) => {\n const mergedAttributes = { ...items }\n\n Object.entries(item).forEach(([key, value]) => {\n const exists = mergedAttributes[key]\n\n if (!exists) {\n mergedAttributes[key] = value\n\n return\n }\n\n if (key === 'class') {\n const valueClasses: string[] = value ? String(value).split(' ') : []\n const existingClasses: string[] = mergedAttributes[key] ? mergedAttributes[key].split(' ') : []\n\n const insertClasses = valueClasses.filter(valueClass => !existingClasses.includes(valueClass))\n\n mergedAttributes[key] = [...existingClasses, ...insertClasses].join(' ')\n } else if (key === 'style') {\n const newStyles: string[] = value\n ? value\n .split(';')\n .map((style: string) => style.trim())\n .filter(Boolean)\n : []\n const existingStyles: string[] = mergedAttributes[key]\n ? mergedAttributes[key]\n .split(';')\n .map((style: string) => style.trim())\n .filter(Boolean)\n : []\n\n const styleMap = new Map()\n\n existingStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim())\n\n styleMap.set(property, val)\n })\n\n newStyles.forEach(style => {\n const [property, val] = style.split(':').map(part => part.trim())\n\n styleMap.set(property, val)\n })\n\n mergedAttributes[key] = Array.from(styleMap.entries())\n .map(([property, val]) => `${property}: ${val}`)\n .join('; ')\n } else {\n mergedAttributes[key] = value\n }\n })\n\n return mergedAttributes\n }, {})\n}\n", "import type { Mark, Node } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { mergeAttributes } from '../utilities/mergeAttributes.js'\n\nexport function getRenderedAttributes(\n nodeOrMark: Node | Mark,\n extensionAttributes: ExtensionAttribute[],\n): Record {\n return extensionAttributes\n .filter(attribute => attribute.type === nodeOrMark.type.name)\n .filter(item => item.attribute.rendered)\n .map(item => {\n if (!item.attribute.renderHTML) {\n return {\n [item.name]: nodeOrMark.attrs[item.name],\n }\n }\n\n return item.attribute.renderHTML(nodeOrMark.attrs) || {}\n })\n .reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {})\n}\n", "export function fromString(value: any): any {\n if (typeof value !== 'string') {\n return value\n }\n\n if (value.match(/^[+-]?(?:\\d*\\.)?\\d+$/)) {\n return Number(value)\n }\n\n if (value === 'true') {\n return true\n }\n\n if (value === 'false') {\n return false\n }\n\n return value\n}\n", "import type { ParseRule } from '@tiptap/pm/model'\n\nimport type { ExtensionAttribute } from '../types.js'\nimport { fromString } from '../utilities/fromString.js'\n\n/**\n * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).\n * Cancels when `getAttrs` returned `false`.\n * @param parseRule ProseMirror ParseRule\n * @param extensionAttributes List of attributes to inject\n */\nexport function injectExtensionAttributesToParseRule(\n parseRule: ParseRule,\n extensionAttributes: ExtensionAttribute[],\n): ParseRule {\n if ('style' in parseRule) {\n return parseRule\n }\n\n return {\n ...parseRule,\n getAttrs: (node: HTMLElement) => {\n const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs\n\n if (oldAttributes === false) {\n return false\n }\n\n const newAttributes = extensionAttributes.reduce((items, item) => {\n const value = item.attribute.parseHTML\n ? item.attribute.parseHTML(node)\n : fromString(node.getAttribute(item.name))\n\n if (value === null || value === undefined) {\n return items\n }\n\n return {\n ...items,\n [item.name]: value,\n }\n }, {})\n\n return { ...oldAttributes, ...newAttributes }\n },\n }\n}\n", "/**\n * Find duplicates in an array.\n */\nexport function findDuplicates(items: T[]): T[] {\n const filtered = items.filter((el, index) => items.indexOf(el) !== index)\n\n return Array.from(new Set(filtered))\n}\n", "import type { AnyConfig, Extensions } from '../types.js'\nimport { getExtensionField } from './getExtensionField.js'\n\n/**\n * Sort extensions by priority.\n * @param extensions An array of Tiptap extensions\n * @returns A sorted array of Tiptap extensions by priority\n */\nexport function sortExtensions(extensions: Extensions): Extensions {\n const defaultPriority = 100\n\n return extensions.sort((a, b) => {\n const priorityA = getExtensionField(a, 'priority') || defaultPriority\n const priorityB = getExtensionField(b, 'priority') || defaultPriority\n\n if (priorityA > priorityB) {\n return -1\n }\n\n if (priorityA < priorityB) {\n return 1\n }\n\n return 0\n })\n}\n", "import type { Extensions } from '../types.js'\nimport { findDuplicates } from '../utilities/findDuplicates.js'\nimport { flattenExtensions } from './flattenExtensions.js'\nimport { sortExtensions } from './sortExtensions.js'\n\n/**\n * Returns a flattened and sorted extension list while\n * also checking for duplicated extensions and warns the user.\n * @param extensions An array of Tiptap extensions\n * @returns An flattened and sorted array of Tiptap extensions\n */\nexport function resolveExtensions(extensions: Extensions): Extensions {\n const resolvedExtensions = sortExtensions(flattenExtensions(extensions))\n const duplicatedNames = findDuplicates(resolvedExtensions.map(extension => extension.name))\n\n if (duplicatedNames.length) {\n console.warn(\n `[tiptap warn]: Duplicate extension names found: [${duplicatedNames\n .map(item => `'${item}'`)\n .join(', ')}]. This can lead to issues.`,\n )\n }\n\n return resolvedExtensions\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { Editor } from '../Editor.js'\nimport type { Extensions } from '../types.js'\nimport { getSchemaByResolvedExtensions } from './getSchemaByResolvedExtensions.js'\nimport { resolveExtensions } from './resolveExtensions.js'\n\nexport function getSchema(extensions: Extensions, editor?: Editor): Schema {\n const resolvedExtensions = resolveExtensions(extensions)\n\n return getSchemaByResolvedExtensions(resolvedExtensions, editor)\n}\n", "import { DOMParser } from '@tiptap/pm/model'\n\nimport type { Extensions } from '../types.js'\nimport { elementFromString } from '../utilities/elementFromString.js'\nimport { getSchema } from './getSchema.js'\n\n/**\n * Generate JSONContent from HTML\n * @param html The HTML to generate JSONContent from\n * @param extensions The extensions to use for the schema\n * @returns The generated JSONContent\n */\nexport function generateJSON(html: string, extensions: Extensions): Record {\n const schema = getSchema(extensions)\n const dom = elementFromString(html)\n\n return DOMParser.fromSchema(schema).parse(dom).toJSON()\n}\n", "import { Node } from '@tiptap/pm/model'\n\nimport type { Extensions, JSONContent, TextSerializer } from '../types.js'\nimport { getSchema } from './getSchema.js'\nimport { getText } from './getText.js'\nimport { getTextSerializersFromSchema } from './getTextSerializersFromSchema.js'\n\n/**\n * Generate raw text from a JSONContent\n * @param doc The JSONContent to generate text from\n * @param extensions The extensions to use for the schema\n * @param options Options for the text generation f.e. blockSeparator or textSerializers\n * @returns The generated text\n */\nexport function generateText(\n doc: JSONContent,\n extensions: Extensions,\n options?: {\n blockSeparator?: string\n textSerializers?: Record\n },\n): string {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n const schema = getSchema(extensions)\n const contentNode = Node.fromJSON(schema, doc)\n\n return getText(contentNode, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(schema),\n ...textSerializers,\n },\n })\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { Range, TextSerializer } from '../types.js'\n\n/**\n * Gets the text between two positions in a Prosemirror node\n * and serializes it using the given text serializers and block separator (see getText)\n * @param startNode The Prosemirror node to start from\n * @param range The range of the text to get\n * @param options Options for the text serializer & block separator\n * @returns The text between the two positions\n */\nexport function getTextBetween(\n startNode: ProseMirrorNode,\n range: Range,\n options?: {\n blockSeparator?: string\n textSerializers?: Record\n },\n): string {\n const { from, to } = range\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n let text = ''\n\n startNode.nodesBetween(from, to, (node, pos, parent, index) => {\n if (node.isBlock && pos > from) {\n text += blockSeparator\n }\n\n const textSerializer = textSerializers?.[node.type.name]\n\n if (textSerializer) {\n if (parent) {\n text += textSerializer({\n node,\n pos,\n parent,\n index,\n range,\n })\n }\n // do not descend into child nodes when there exists a serializer\n return false\n }\n\n if (node.isText) {\n text += node?.text?.slice(Math.max(from, pos) - pos, to - pos) // eslint-disable-line\n }\n })\n\n return text\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\nimport { getTextBetween } from './getTextBetween.js'\n\n/**\n * Gets the text of a Prosemirror node\n * @param node The Prosemirror node\n * @param options Options for the text serializer & block separator\n * @returns The text of the node\n * @example ```js\n * const text = getText(node, { blockSeparator: '\\n' })\n * ```\n */\nexport function getText(\n node: ProseMirrorNode,\n options?: {\n blockSeparator?: string\n textSerializers?: Record\n },\n) {\n const range = {\n from: 0,\n to: node.content.size,\n }\n\n return getTextBetween(node, range, options)\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { TextSerializer } from '../types.js'\n\n/**\n * Find text serializers `toText` in a Prosemirror schema\n * @param schema The Prosemirror schema to search in\n * @returns A record of text serializers by node name\n */\nexport function getTextSerializersFromSchema(schema: Schema): Record {\n return Object.fromEntries(\n Object.entries(schema.nodes)\n .filter(([, node]) => node.spec.toText)\n .map(([name, node]) => [name, node.spec.toText]),\n )\n}\n", "import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getNodeType } from './getNodeType.js'\n\nexport function getNodeAttributes(state: EditorState, typeOrName: string | NodeType): Record {\n const type = getNodeType(typeOrName, state.schema)\n const { from, to } = state.selection\n const nodes: Node[] = []\n\n state.doc.nodesBetween(from, to, node => {\n nodes.push(node)\n })\n\n const node = nodes.reverse().find(nodeItem => nodeItem.type.name === type.name)\n\n if (!node) {\n return {}\n }\n\n return { ...node.attrs }\n}\n", "import type { MarkType, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from './getMarkAttributes.js'\nimport { getNodeAttributes } from './getNodeAttributes.js'\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\n\n/**\n * Get node or mark attributes by type or name on the current editor state\n * @param state The current editor state\n * @param typeOrName The node or mark type or name\n * @returns The attributes of the node or mark or an empty object\n */\nexport function getAttributes(state: EditorState, typeOrName: string | NodeType | MarkType): Record {\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (schemaType === 'node') {\n return getNodeAttributes(state, typeOrName as NodeType)\n }\n\n if (schemaType === 'mark') {\n return getMarkAttributes(state, typeOrName as MarkType)\n }\n\n return {}\n}\n", "/**\n * Removes duplicated values within an array.\n * Supports numbers, strings and objects.\n */\nexport function removeDuplicates(array: T[], by = JSON.stringify): T[] {\n const seen: Record = {}\n\n return array.filter(item => {\n const key = by(item)\n\n return Object.prototype.hasOwnProperty.call(seen, key) ? false : (seen[key] = true)\n })\n}\n", "import type { Step, Transform } from '@tiptap/pm/transform'\n\nimport type { Range } from '../types.js'\nimport { removeDuplicates } from '../utilities/removeDuplicates.js'\n\nexport type ChangedRange = {\n oldRange: Range\n newRange: Range\n}\n\n/**\n * Removes duplicated ranges and ranges that are\n * fully captured by other ranges.\n */\nfunction simplifyChangedRanges(changes: ChangedRange[]): ChangedRange[] {\n const uniqueChanges = removeDuplicates(changes)\n\n return uniqueChanges.length === 1\n ? uniqueChanges\n : uniqueChanges.filter((change, index) => {\n const rest = uniqueChanges.filter((_, i) => i !== index)\n\n return !rest.some(otherChange => {\n return (\n change.oldRange.from >= otherChange.oldRange.from &&\n change.oldRange.to <= otherChange.oldRange.to &&\n change.newRange.from >= otherChange.newRange.from &&\n change.newRange.to <= otherChange.newRange.to\n )\n })\n })\n}\n\n/**\n * Returns a list of changed ranges\n * based on the first and last state of all steps.\n */\nexport function getChangedRanges(transform: Transform): ChangedRange[] {\n const { mapping, steps } = transform\n const changes: ChangedRange[] = []\n\n mapping.maps.forEach((stepMap, index) => {\n const ranges: Range[] = []\n\n // This accounts for step changes where no range was actually altered\n // e.g. when setting a mark, node attribute, etc.\n // @ts-ignore\n if (!stepMap.ranges.length) {\n const { from, to } = steps[index] as Step & {\n from?: number\n to?: number\n }\n\n if (from === undefined || to === undefined) {\n return\n }\n\n ranges.push({ from, to })\n } else {\n stepMap.forEach((from, to) => {\n ranges.push({ from, to })\n })\n }\n\n ranges.forEach(({ from, to }) => {\n const newStart = mapping.slice(index).map(from, -1)\n const newEnd = mapping.slice(index).map(to)\n const oldStart = mapping.invert().map(newStart, -1)\n const oldEnd = mapping.invert().map(newEnd)\n\n changes.push({\n oldRange: {\n from: oldStart,\n to: oldEnd,\n },\n newRange: {\n from: newStart,\n to: newEnd,\n },\n })\n })\n })\n\n return simplifyChangedRanges(changes)\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ninterface DebugJSONContent extends JSONContent {\n from: number\n to: number\n}\n\nexport function getDebugJSON(node: ProseMirrorNode, startOffset = 0): DebugJSONContent {\n const isTopNode = node.type === node.type.schema.topNodeType\n const increment = isTopNode ? 0 : 1\n const from = startOffset\n const to = from + node.nodeSize\n const marks = node.marks.map(mark => {\n const output: { type: string; attrs?: Record } = {\n type: mark.type.name,\n }\n\n if (Object.keys(mark.attrs).length) {\n output.attrs = { ...mark.attrs }\n }\n\n return output\n })\n const attrs = { ...node.attrs }\n const output: DebugJSONContent = {\n type: node.type.name,\n from,\n to,\n }\n\n if (Object.keys(attrs).length) {\n output.attrs = attrs\n }\n\n if (marks.length) {\n output.marks = marks\n }\n\n if (node.content.childCount) {\n output.content = []\n\n node.forEach((child, offset) => {\n output.content?.push(getDebugJSON(child, startOffset + offset + increment))\n })\n }\n\n if (node.text) {\n output.text = node.text\n }\n\n return output\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\nimport type { MarkRange } from '../types.js'\nimport { getMarkRange } from './getMarkRange.js'\n\nexport function getMarksBetween(from: number, to: number, doc: ProseMirrorNode): MarkRange[] {\n const marks: MarkRange[] = []\n\n // get all inclusive marks on empty selection\n if (from === to) {\n doc\n .resolve(from)\n .marks()\n .forEach(mark => {\n const $pos = doc.resolve(from)\n const range = getMarkRange($pos, mark.type)\n\n if (!range) {\n return\n }\n\n marks.push({\n mark,\n ...range,\n })\n })\n } else {\n doc.nodesBetween(from, to, (node, pos) => {\n if (!node || node?.nodeSize === undefined) {\n return\n }\n\n marks.push(\n ...node.marks.map(mark => ({\n from: pos,\n to: pos + node.nodeSize,\n mark,\n })),\n )\n })\n }\n\n return marks\n}\n", "import type { Node, NodeType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\n/**\n * Finds the first node of a given type or name in the current selection.\n * @param state The editor state.\n * @param typeOrName The node type or name.\n * @param pos The position to start searching from.\n * @param maxDepth The maximum depth to search.\n * @returns The node and the depth as an array.\n */\nexport const getNodeAtPosition = (state: EditorState, typeOrName: string | NodeType, pos: number, maxDepth = 20) => {\n const $pos = state.doc.resolve(pos)\n\n let currentDepth = maxDepth\n let node: Node | null = null\n\n while (currentDepth > 0 && node === null) {\n const currentNode = $pos.node(currentDepth)\n\n if (currentNode?.type.name === typeOrName) {\n node = currentNode\n } else {\n currentDepth -= 1\n }\n }\n\n return [node, currentDepth] as [Node | null, number]\n}\n", "import type { MarkType, NodeType, Schema } from '@tiptap/pm/model'\n\n/**\n * Tries to get a node or mark type by its name.\n * @param name The name of the node or mark type\n * @param schema The Prosemiror schema to search in\n * @returns The node or mark type, or null if it doesn't exist\n */\nexport function getSchemaTypeByName(name: string, schema: Schema): NodeType | MarkType | null {\n return schema.nodes[name] || schema.marks[name] || null\n}\n", "import type { ExtensionAttribute } from '../types.js'\n\n/**\n * Return attributes of an extension that should be splitted by keepOnSplit flag\n * @param extensionAttributes Array of extension attributes\n * @param typeName The type of the extension\n * @param attributes The attributes of the extension\n * @returns The splitted attributes\n */\nexport function getSplittedAttributes(\n extensionAttributes: ExtensionAttribute[],\n typeName: string,\n attributes: Record,\n): Record {\n return Object.fromEntries(\n Object.entries(attributes).filter(([name]) => {\n const extensionAttribute = extensionAttributes.find(item => {\n return item.type === typeName && item.name === name\n })\n\n if (!extensionAttribute) {\n return false\n }\n\n return extensionAttribute.attribute.keepOnSplit\n }),\n )\n}\n", "import type { ResolvedPos } from '@tiptap/pm/model'\n\n/**\n * Returns the text content of a resolved prosemirror position\n * @param $from The resolved position to get the text content from\n * @param maxMatch The maximum number of characters to match\n * @returns The text content\n */\nexport const getTextContentFromNodes = ($from: ResolvedPos, maxMatch = 500) => {\n let textBefore = ''\n\n const sliceEndPos = $from.parentOffset\n\n $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => {\n const chunk =\n node.type.spec.toText?.({\n node,\n pos,\n parent,\n index,\n }) ||\n node.textContent ||\n '%leaf%'\n\n textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos))\n })\n\n return textBefore\n}\n", "import type { MarkType } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\n\nimport type { MarkRange } from '../types.js'\nimport { objectIncludes } from '../utilities/objectIncludes.js'\nimport { getMarkType } from './getMarkType.js'\n\nexport function isMarkActive(\n state: EditorState,\n typeOrName: MarkType | string | null,\n attributes: Record = {},\n): boolean {\n const { empty, ranges } = state.selection\n const type = typeOrName ? getMarkType(typeOrName, state.schema) : null\n\n if (empty) {\n return !!(state.storedMarks || state.selection.$from.marks())\n .filter(mark => {\n if (!type) {\n return true\n }\n\n return type.name === mark.type.name\n })\n .find(mark => objectIncludes(mark.attrs, attributes, { strict: false }))\n }\n\n let selectionRange = 0\n const markRanges: MarkRange[] = []\n\n ranges.forEach(({ $from, $to }) => {\n const from = $from.pos\n const to = $to.pos\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (!node.isText && !node.marks.length) {\n return\n }\n\n const relativeFrom = Math.max(from, pos)\n const relativeTo = Math.min(to, pos + node.nodeSize)\n const range = relativeTo - relativeFrom\n\n selectionRange += range\n\n markRanges.push(\n ...node.marks.map(mark => ({\n mark,\n from: relativeFrom,\n to: relativeTo,\n })),\n )\n })\n })\n\n if (selectionRange === 0) {\n return false\n }\n\n // calculate range of matched mark\n const matchedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true\n }\n\n return type.name === markRange.mark.type.name\n })\n .filter(markRange => objectIncludes(markRange.mark.attrs, attributes, { strict: false }))\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n // calculate range of marks that excludes the searched mark\n // for example `code` doesn’t allow any other marks\n const excludedRange = markRanges\n .filter(markRange => {\n if (!type) {\n return true\n }\n\n return markRange.mark.type !== type && markRange.mark.type.excludes(type)\n })\n .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0)\n\n // we only include the result of `excludedRange`\n // if there is a match at all\n const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange\n\n return range >= selectionRange\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { getSchemaTypeNameByName } from './getSchemaTypeNameByName.js'\nimport { isMarkActive } from './isMarkActive.js'\nimport { isNodeActive } from './isNodeActive.js'\n\nexport function isActive(state: EditorState, name: string | null, attributes: Record = {}): boolean {\n if (!name) {\n return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes)\n }\n\n const schemaType = getSchemaTypeNameByName(name, state.schema)\n\n if (schemaType === 'node') {\n return isNodeActive(state, name, attributes)\n }\n\n if (schemaType === 'mark') {\n return isMarkActive(state, name, attributes)\n }\n\n return false\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nimport { findParentNode } from './findParentNode.js'\n\nexport const isAtEndOfNode = (state: EditorState, nodeType?: string) => {\n const { $from, $to, $anchor } = state.selection\n\n if (nodeType) {\n const parentNode = findParentNode(node => node.type.name === nodeType)(state.selection)\n\n if (!parentNode) {\n return false\n }\n\n const $parentPos = state.doc.resolve(parentNode.pos + 1)\n\n if ($anchor.pos + 1 === $parentPos.end()) {\n return true\n }\n\n return false\n }\n\n if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {\n return false\n }\n\n return true\n}\n", "import type { EditorState } from '@tiptap/pm/state'\n\nexport const isAtStartOfNode = (state: EditorState) => {\n const { $from, $to } = state.selection\n\n if ($from.parentOffset > 0 || $from.pos !== $to.pos) {\n return false\n }\n\n return true\n}\n", "import type { AnyExtension, EnableRules } from '../types.js'\n\nexport function isExtensionRulesEnabled(extension: AnyExtension, enabled: EnableRules): boolean {\n if (Array.isArray(enabled)) {\n return enabled.some(enabledExtension => {\n const name = typeof enabledExtension === 'string' ? enabledExtension : enabledExtension.name\n\n return name === extension.name\n })\n }\n\n return enabled\n}\n", "import { getExtensionField } from '../helpers/getExtensionField.js'\nimport type { NodeConfig } from '../index.js'\nimport type { Extensions } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\nimport { splitExtensions } from './splitExtensions.js'\n\nexport function isList(name: string, extensions: Extensions): boolean {\n const { nodeExtensions } = splitExtensions(extensions)\n const extension = nodeExtensions.find(item => item.name === name)\n\n if (!extension) {\n return false\n }\n\n const context = {\n name: extension.name,\n options: extension.options,\n storage: extension.storage,\n }\n const group = callOrReturn(getExtensionField(extension, 'group', context))\n\n if (typeof group !== 'string') {\n return false\n }\n\n return group.split(' ').includes('list')\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\n\n/**\n * Returns true if the given prosemirror node is empty.\n */\nexport function isNodeEmpty(\n node: ProseMirrorNode,\n {\n checkChildren = true,\n ignoreWhitespace = false,\n }: {\n /**\n * When true (default), it will also check if all children are empty.\n */\n checkChildren?: boolean\n /**\n * When true, it will ignore whitespace when checking for emptiness.\n */\n ignoreWhitespace?: boolean\n } = {},\n): boolean {\n if (ignoreWhitespace) {\n if (node.type.name === 'hardBreak') {\n // Hard breaks are considered empty\n return true\n }\n if (node.isText) {\n return /^\\s*$/m.test(node.text ?? '')\n }\n }\n\n if (node.isText) {\n return !node.text\n }\n\n if (node.isAtom || node.isLeaf) {\n return false\n }\n\n if (node.content.childCount === 0) {\n return true\n }\n\n if (checkChildren) {\n let isContentEmpty = true\n\n node.content.forEach(childNode => {\n if (isContentEmpty === false) {\n // Exit early for perf\n return\n }\n\n if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {\n isContentEmpty = false\n }\n })\n\n return isContentEmpty\n }\n\n return false\n}\n", "import { NodeSelection } from '@tiptap/pm/state'\n\nexport function isNodeSelection(value: unknown): value is NodeSelection {\n return value instanceof NodeSelection\n}\n", "import type { Transaction } from '@tiptap/pm/state'\nimport type { MapResult } from '@tiptap/pm/transform'\n\n/**\n * A class that represents a mappable position in the editor. It can be extended\n * by other extensions to add additional position mapping capabilities.\n */\nexport class MappablePosition {\n /**\n * The absolute position in the editor.\n */\n public position: number\n\n constructor(position: number) {\n this.position = position\n }\n\n /**\n * Creates a MappablePosition from a JSON object.\n */\n static fromJSON(json: any): MappablePosition {\n return new MappablePosition(json.position)\n }\n\n /**\n * Converts the MappablePosition to a JSON object.\n */\n toJSON(): any {\n return {\n position: this.position,\n }\n }\n}\n\n/**\n * The result of the getUpdatedPosition function.\n */\nexport interface GetUpdatedPositionResult {\n position: MappablePosition\n mapResult: MapResult | null\n}\n\n/**\n * Calculates the new position after applying a transaction.\n *\n * @returns The new mappable position and the map result.\n */\nexport function getUpdatedPosition(position: MappablePosition, transaction: Transaction): GetUpdatedPositionResult {\n const mapResult = transaction.mapping.mapResult(position.position)\n return {\n position: new MappablePosition(mapResult.pos),\n mapResult,\n }\n}\n\n/**\n * Creates a MappablePosition from a position number. This is the default\n * implementation for Tiptap core. It can be overridden by other Tiptap\n * extensions.\n *\n * @param position The position (as a number) where the MappablePosition will be created.\n * @returns A new MappablePosition instance at the given position.\n */\nexport function createMappablePosition(position: number): MappablePosition {\n return new MappablePosition(position)\n}\n", "import type { EditorView } from '@tiptap/pm/view'\n\nimport { minMax } from '../utilities/minMax.js'\n\nexport function posToDOMRect(view: EditorView, from: number, to: number): DOMRect {\n const minPos = 0\n const maxPos = view.state.doc.content.size\n const resolvedFrom = minMax(from, minPos, maxPos)\n const resolvedEnd = minMax(to, minPos, maxPos)\n const start = view.coordsAtPos(resolvedFrom)\n const end = view.coordsAtPos(resolvedEnd, -1)\n const top = Math.min(start.top, end.top)\n const bottom = Math.max(start.bottom, end.bottom)\n const left = Math.min(start.left, end.left)\n const right = Math.max(start.right, end.right)\n const width = right - left\n const height = bottom - top\n const x = left\n const y = top\n const data = {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x,\n y,\n }\n\n return {\n ...data,\n toJSON: () => data,\n }\n}\n", "import type { Schema } from '@tiptap/pm/model'\n\nimport type { JSONContent } from '../types.js'\n\ntype RewriteUnknownContentOptions = {\n /**\n * If true, unknown nodes will be treated as paragraphs\n * @default true\n */\n fallbackToParagraph?: boolean\n}\n\ntype RewrittenContent = {\n /**\n * The original JSON content that was rewritten\n */\n original: JSONContent\n /**\n * The name of the node or mark that was unsupported\n */\n unsupported: string\n}[]\n\n/**\n * The actual implementation of the rewriteUnknownContent function\n */\nfunction rewriteUnknownContentInner({\n json,\n validMarks,\n validNodes,\n options,\n rewrittenContent = [],\n}: {\n json: JSONContent\n validMarks: Set\n validNodes: Set\n options?: RewriteUnknownContentOptions\n rewrittenContent?: RewrittenContent\n}): {\n /**\n * The cleaned JSON content\n */\n json: JSONContent | null\n /**\n * The array of nodes and marks that were rewritten\n */\n rewrittenContent: RewrittenContent\n} {\n if (json.marks && Array.isArray(json.marks)) {\n json.marks = json.marks.filter(mark => {\n const name = typeof mark === 'string' ? mark : mark.type\n\n if (validMarks.has(name)) {\n return true\n }\n\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(mark)),\n unsupported: name,\n })\n // Just ignore any unknown marks\n return false\n })\n }\n\n if (json.content && Array.isArray(json.content)) {\n json.content = json.content\n .map(\n value =>\n rewriteUnknownContentInner({\n json: value,\n validMarks,\n validNodes,\n options,\n rewrittenContent,\n }).json,\n )\n .filter(a => a !== null && a !== undefined)\n }\n\n if (json.type && !validNodes.has(json.type)) {\n rewrittenContent.push({\n original: JSON.parse(JSON.stringify(json)),\n unsupported: json.type,\n })\n\n if (json.content && Array.isArray(json.content) && options?.fallbackToParagraph !== false) {\n // Just treat it like a paragraph and hope for the best\n json.type = 'paragraph'\n\n return {\n json,\n rewrittenContent,\n }\n }\n\n // or just omit it entirely\n return {\n json: null,\n rewrittenContent,\n }\n }\n\n return { json, rewrittenContent }\n}\n\n/**\n * Rewrite unknown nodes and marks within JSON content\n * Allowing for user within the editor\n */\nexport function rewriteUnknownContent(\n /**\n * The JSON content to clean of unknown nodes and marks\n */\n json: JSONContent,\n /**\n * The schema to use for validation\n */\n schema: Schema,\n /**\n * Options for the cleaning process\n */\n options?: RewriteUnknownContentOptions,\n): {\n /**\n * The cleaned JSON content\n */\n json: JSONContent | null\n /**\n * The array of nodes and marks that were rewritten\n */\n rewrittenContent: {\n /**\n * The original JSON content that was rewritten\n */\n original: JSONContent\n /**\n * The name of the node or mark that was unsupported\n */\n unsupported: string\n }[]\n} {\n return rewriteUnknownContentInner({\n json,\n validNodes: new Set(Object.keys(schema.nodes)),\n validMarks: new Set(Object.keys(schema.marks)),\n options,\n })\n}\n", "import type { MarkType, ResolvedPos } from '@tiptap/pm/model'\nimport type { EditorState, Transaction } from '@tiptap/pm/state'\n\nimport { getMarkAttributes } from '../helpers/getMarkAttributes.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isTextSelection } from '../helpers/index.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n setMark: {\n /**\n * Add a mark with new attributes.\n * @param typeOrName The mark type or name.\n * @example editor.commands.setMark('bold', { level: 1 })\n */\n setMark: (typeOrName: string | MarkType, attributes?: Record) => ReturnType\n }\n }\n}\n\nfunction canSetMark(state: EditorState, tr: Transaction, newMarkType: MarkType) {\n const { selection } = tr\n let cursor: ResolvedPos | null = null\n\n if (isTextSelection(selection)) {\n cursor = selection.$cursor\n }\n\n if (cursor) {\n const currentMarks = state.storedMarks ?? cursor.marks()\n const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType)\n\n // There can be no current marks that exclude the new mark, and the parent must allow this mark type\n return (\n parentAllowsMarkType &&\n (!!newMarkType.isInSet(currentMarks) || !currentMarks.some(mark => mark.type.excludes(newMarkType)))\n )\n }\n\n const { ranges } = selection\n\n return ranges.some(({ $from, $to }) => {\n let someNodeSupportsMark =\n $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false\n\n state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {\n // If we already found a mark that we can enable, return false to bypass the remaining search\n if (someNodeSupportsMark) {\n return false\n }\n\n if (node.isInline) {\n const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType)\n const currentMarksAllowMarkType =\n !!newMarkType.isInSet(node.marks) || !node.marks.some(otherMark => otherMark.type.excludes(newMarkType))\n\n someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType\n }\n return !someNodeSupportsMark\n })\n\n return someNodeSupportsMark\n })\n}\nexport const setMark: RawCommands['setMark'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n const { selection } = tr\n const { empty, ranges } = selection\n const type = getMarkType(typeOrName, state.schema)\n\n if (dispatch) {\n if (empty) {\n const oldAttributes = getMarkAttributes(state, type)\n\n tr.addStoredMark(\n type.create({\n ...oldAttributes,\n ...attributes,\n }),\n )\n } else {\n ranges.forEach(range => {\n const from = range.$from.pos\n const to = range.$to.pos\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n const trimmedFrom = Math.max(pos, from)\n const trimmedTo = Math.min(pos + node.nodeSize, to)\n const someHasMark = node.marks.find(mark => mark.type === type)\n\n // if there is already a mark of this type\n // we know that we have to merge its attributes\n // otherwise we add a fresh new mark\n if (someHasMark) {\n node.marks.forEach(mark => {\n if (type === mark.type) {\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n type.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n } else {\n tr.addMark(trimmedFrom, trimmedTo, type.create(attributes))\n }\n })\n })\n }\n }\n\n return canSetMark(state, tr, type)\n }\n", "import type { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n setMeta: {\n /**\n * Store a metadata property in the current transaction.\n * @param key The key of the metadata property.\n * @param value The value to store.\n * @example editor.commands.setMeta('foo', 'bar')\n */\n setMeta: (key: string | Plugin | PluginKey, value: any) => ReturnType\n }\n }\n}\n\nexport const setMeta: RawCommands['setMeta'] =\n (key, value) =>\n ({ tr }) => {\n tr.setMeta(key, value)\n\n return true\n }\n", "import { setBlockType } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n setNode: {\n /**\n * Replace a given range with a node.\n * @param typeOrName The type or name of the node\n * @param attributes The attributes of the node\n * @example editor.commands.setNode('paragraph')\n */\n setNode: (typeOrName: string | NodeType, attributes?: Record) => ReturnType\n }\n }\n}\n\nexport const setNode: RawCommands['setNode'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch, chain }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n let attributesToCopy: Record | undefined\n\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs\n }\n\n // TODO: use a fallback like insertContent?\n if (!type.isTextblock) {\n console.warn('[tiptap warn]: Currently \"setNode()\" only supports text block nodes.')\n\n return false\n }\n\n return (\n chain()\n // try to convert node to default node if needed\n .command(({ commands }) => {\n const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state)\n\n if (canSetBlock) {\n return true\n }\n\n return commands.clearNodes()\n })\n .command(({ state: updatedState }) => {\n return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch)\n })\n .run()\n )\n }\n", "import { NodeSelection } from '@tiptap/pm/state'\n\nimport type { RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n setNodeSelection: {\n /**\n * Creates a NodeSelection.\n * @param position - Position of the node.\n * @example editor.commands.setNodeSelection(10)\n */\n setNodeSelection: (position: number) => ReturnType\n }\n }\n}\n\nexport const setNodeSelection: RawCommands['setNodeSelection'] =\n position =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr\n const from = minMax(position, 0, doc.content.size)\n const selection = NodeSelection.create(doc, from)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n", "import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n setTextDirection: {\n /**\n * Set the text direction for nodes.\n * If no position is provided, it will use the current selection.\n * @param direction The text direction to set ('ltr', 'rtl', or 'auto')\n * @param position Optional position or range to apply the direction to\n * @example editor.commands.setTextDirection('rtl')\n * @example editor.commands.setTextDirection('ltr', { from: 0, to: 10 })\n */\n setTextDirection: (direction: 'ltr' | 'rtl' | 'auto', position?: number | Range) => ReturnType\n }\n }\n}\n\nexport const setTextDirection: RawCommands['setTextDirection'] =\n (direction, position) =>\n ({ tr, state, dispatch }) => {\n const { selection } = state\n let from: number\n let to: number\n\n if (typeof position === 'number') {\n from = position\n to = position\n } else if (position && 'from' in position && 'to' in position) {\n from = position.from\n to = position.to\n } else {\n from = selection.from\n to = selection.to\n }\n\n if (dispatch) {\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isText) {\n return\n }\n\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n dir: direction,\n })\n })\n }\n\n return true\n }\n", "import { TextSelection } from '@tiptap/pm/state'\n\nimport type { Range, RawCommands } from '../types.js'\nimport { minMax } from '../utilities/minMax.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n setTextSelection: {\n /**\n * Creates a TextSelection.\n * @param position The position of the selection.\n * @example editor.commands.setTextSelection(10)\n */\n setTextSelection: (position: number | Range) => ReturnType\n }\n }\n}\n\nexport const setTextSelection: RawCommands['setTextSelection'] =\n position =>\n ({ tr, dispatch }) => {\n if (dispatch) {\n const { doc } = tr\n const { from, to } = typeof position === 'number' ? { from: position, to: position } : position\n const minPos = TextSelection.atStart(doc).from\n const maxPos = TextSelection.atEnd(doc).to\n const resolvedFrom = minMax(from, minPos, maxPos)\n const resolvedEnd = minMax(to, minPos, maxPos)\n const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd)\n\n tr.setSelection(selection)\n }\n\n return true\n }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { sinkListItem as originalSinkListItem } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n sinkListItem: {\n /**\n * Sink the list item down into an inner list.\n * @param typeOrName The type or name of the node.\n * @example editor.commands.sinkListItem('listItem')\n */\n sinkListItem: (typeOrName: string | NodeType) => ReturnType\n }\n }\n}\n\nexport const sinkListItem: RawCommands['sinkListItem'] =\n typeOrName =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalSinkListItem(type)(state, dispatch)\n }\n", "import type { EditorState } from '@tiptap/pm/state'\nimport { NodeSelection, TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { defaultBlockAt } from '../helpers/defaultBlockAt.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\nfunction ensureMarks(state: EditorState, splittableMarks?: string[]) {\n const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks())\n\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks?.includes(mark.type.name))\n\n state.tr.ensureMarks(filteredMarks)\n }\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n splitBlock: {\n /**\n * Forks a new node from an existing node.\n * @param options.keepMarks Keep marks from the previous node.\n * @example editor.commands.splitBlock()\n * @example editor.commands.splitBlock({ keepMarks: true })\n */\n splitBlock: (options?: { keepMarks?: boolean }) => ReturnType\n }\n }\n}\n\nexport const splitBlock: RawCommands['splitBlock'] =\n ({ keepMarks = true } = {}) =>\n ({ tr, state, dispatch, editor }) => {\n const { selection, doc } = tr\n const { $from, $to } = selection\n const extensionAttributes = editor.extensionManager.attributes\n const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs)\n\n if (selection instanceof NodeSelection && selection.node.isBlock) {\n if (!$from.parentOffset || !canSplit(doc, $from.pos)) {\n return false\n }\n\n if (dispatch) {\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks)\n }\n\n tr.split($from.pos).scrollIntoView()\n }\n\n return true\n }\n\n if (!$from.parent.isBlock) {\n return false\n }\n\n const atEnd = $to.parentOffset === $to.parent.content.size\n\n const deflt = $from.depth === 0 ? undefined : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)))\n\n let types =\n atEnd && deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined\n\n let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types)\n\n if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)) {\n can = true\n types = deflt\n ? [\n {\n type: deflt,\n attrs: newAttributes,\n },\n ]\n : undefined\n }\n\n if (dispatch) {\n if (can) {\n if (selection instanceof TextSelection) {\n tr.deleteSelection()\n }\n\n tr.split(tr.mapping.map($from.pos), 1, types)\n\n if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {\n const first = tr.mapping.map($from.before())\n const $first = tr.doc.resolve(first)\n\n if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {\n tr.setNodeMarkup(tr.mapping.map($from.before()), deflt)\n }\n }\n }\n\n if (keepMarks) {\n ensureMarks(state, editor.extensionManager.splittableMarks)\n }\n\n tr.scrollIntoView()\n }\n\n return can\n }\n", "import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { Fragment, Slice } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { canSplit } from '@tiptap/pm/transform'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSplittedAttributes } from '../helpers/getSplittedAttributes.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n splitListItem: {\n /**\n * Splits one list item into two list items.\n * @param typeOrName The type or name of the node.\n * @param overrideAttrs The attributes to ensure on the new node.\n * @example editor.commands.splitListItem('listItem')\n */\n splitListItem: (typeOrName: string | NodeType, overrideAttrs?: Record) => ReturnType\n }\n }\n}\n\nexport const splitListItem: RawCommands['splitListItem'] =\n (typeOrName, overrideAttrs = {}) =>\n ({ tr, state, dispatch, editor }) => {\n const type = getNodeType(typeOrName, state.schema)\n const { $from, $to } = state.selection\n\n // @ts-ignore\n // eslint-disable-next-line\n const node: ProseMirrorNode = state.selection.node\n\n if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {\n return false\n }\n\n const grandParent = $from.node(-1)\n\n if (grandParent.type !== type) {\n return false\n }\n\n const extensionAttributes = editor.extensionManager.attributes\n\n if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {\n // In an empty block. If this is a nested list, the wrapping\n // list item should be split. Otherwise, bail out and let next\n // command handle lifting.\n if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {\n return false\n }\n\n if (dispatch) {\n let wrap = Fragment.empty\n // eslint-disable-next-line\n const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3\n\n // Build a fragment containing empty versions of the structure\n // from the outer list item to the parent node of the cursor\n for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {\n wrap = Fragment.from($from.node(d).copy(wrap))\n }\n\n const depthAfter =\n // eslint-disable-next-line no-nested-ternary\n $from.indexAfter(-1) < $from.node(-2).childCount\n ? 1\n : $from.indexAfter(-2) < $from.node(-3).childCount\n ? 2\n : 3\n\n // Add a second list item with an empty default start node\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n }\n const nextType = type.contentMatch.defaultType?.createAndFill(newNextTypeAttributes) || undefined\n\n wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType) || undefined))\n\n const start = $from.before($from.depth - (depthBefore - 1))\n\n tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0))\n\n let sel = -1\n\n tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {\n if (sel > -1) {\n return false\n }\n\n if (n.isTextblock && n.content.size === 0) {\n sel = pos + 1\n }\n })\n\n if (sel > -1) {\n tr.setSelection(TextSelection.near(tr.doc.resolve(sel)))\n }\n\n tr.scrollIntoView()\n }\n\n return true\n }\n\n const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null\n\n const newTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),\n ...overrideAttrs,\n }\n const newNextTypeAttributes = {\n ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),\n ...overrideAttrs,\n }\n\n tr.delete($from.pos, $to.pos)\n\n const types = nextType\n ? [\n { type, attrs: newTypeAttributes },\n { type: nextType, attrs: newNextTypeAttributes },\n ]\n : [{ type, attrs: newTypeAttributes }]\n\n if (!canSplit(tr.doc, $from.pos, 2)) {\n return false\n }\n\n if (dispatch) {\n const { selection, storedMarks } = state\n const { splittableMarks } = editor.extensionManager\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n tr.split($from.pos, 2, types).scrollIntoView()\n\n if (!marks || !dispatch) {\n return true\n }\n\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n }\n\n return true\n }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport type { Transaction } from '@tiptap/pm/state'\nimport { canJoin } from '@tiptap/pm/transform'\n\nimport { findParentNode } from '../helpers/findParentNode.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isList } from '../helpers/isList.js'\nimport type { RawCommands } from '../types.js'\n\nconst joinListBackwards = (tr: Transaction, listType: NodeType): boolean => {\n const list = findParentNode(node => node.type === listType)(tr.selection)\n\n if (!list) {\n return true\n }\n\n const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth)\n\n if (before === undefined) {\n return true\n }\n\n const nodeBefore = tr.doc.nodeAt(before)\n const canJoinBackwards = list.node.type === nodeBefore?.type && canJoin(tr.doc, list.pos)\n\n if (!canJoinBackwards) {\n return true\n }\n\n tr.join(list.pos)\n\n return true\n}\n\nconst joinListForwards = (tr: Transaction, listType: NodeType): boolean => {\n const list = findParentNode(node => node.type === listType)(tr.selection)\n\n if (!list) {\n return true\n }\n\n const after = tr.doc.resolve(list.start).after(list.depth)\n\n if (after === undefined) {\n return true\n }\n\n const nodeAfter = tr.doc.nodeAt(after)\n const canJoinForwards = list.node.type === nodeAfter?.type && canJoin(tr.doc, after)\n\n if (!canJoinForwards) {\n return true\n }\n\n tr.join(after)\n\n return true\n}\n\ndeclare module '@tiptap/core' {\n interface Commands {\n toggleList: {\n /**\n * Toggle between different list types.\n * @param listTypeOrName The type or name of the list.\n * @param itemTypeOrName The type or name of the list item.\n * @param keepMarks Keep marks when toggling.\n * @param attributes Attributes for the new list.\n * @example editor.commands.toggleList('bulletList', 'listItem')\n */\n toggleList: (\n listTypeOrName: string | NodeType,\n itemTypeOrName: string | NodeType,\n keepMarks?: boolean,\n attributes?: Record,\n ) => ReturnType\n }\n }\n}\n\nexport const toggleList: RawCommands['toggleList'] =\n (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) =>\n ({ editor, tr, state, dispatch, chain, commands, can }) => {\n const { extensions, splittableMarks } = editor.extensionManager\n const listType = getNodeType(listTypeOrName, state.schema)\n const itemType = getNodeType(itemTypeOrName, state.schema)\n const { selection, storedMarks } = state\n const { $from, $to } = selection\n const range = $from.blockRange($to)\n\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n if (!range) {\n return false\n }\n\n const parentList = findParentNode(node => isList(node.type.name, extensions))(selection)\n\n if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {\n // remove list\n if (parentList.node.type === listType) {\n return commands.liftListItem(itemType)\n }\n\n // change list type\n if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) {\n return chain()\n .command(() => {\n tr.setNodeMarkup(parentList.pos, listType)\n\n return true\n })\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n }\n }\n if (!keepMarks || !marks || !dispatch) {\n return (\n chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes)\n\n if (canWrapInList) {\n return true\n }\n\n return commands.clearNodes()\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n )\n }\n\n return (\n chain()\n // try to convert node to default node if needed\n .command(() => {\n const canWrapInList = can().wrapInList(listType, attributes)\n\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n\n if (canWrapInList) {\n return true\n }\n\n return commands.clearNodes()\n })\n .wrapInList(listType, attributes)\n .command(() => joinListBackwards(tr, listType))\n .command(() => joinListForwards(tr, listType))\n .run()\n )\n }\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { isMarkActive } from '../helpers/isMarkActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n toggleMark: {\n /**\n * Toggle a mark on and off.\n * @param typeOrName The mark type or name.\n * @param attributes The attributes of the mark.\n * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n * @example editor.commands.toggleMark('bold')\n */\n toggleMark: (\n /**\n * The mark type or name.\n */\n typeOrName: string | MarkType,\n\n /**\n * The attributes of the mark.\n */\n attributes?: Record,\n\n options?: {\n /**\n * Removes the mark even across the current selection. Defaults to `false`.\n */\n extendEmptyMarkRange?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const toggleMark: RawCommands['toggleMark'] =\n (typeOrName, attributes = {}, options = {}) =>\n ({ state, commands }) => {\n const { extendEmptyMarkRange = false } = options\n const type = getMarkType(typeOrName, state.schema)\n const isActive = isMarkActive(state, type, attributes)\n\n if (isActive) {\n return commands.unsetMark(type, { extendEmptyMarkRange })\n }\n\n return commands.setMark(type, attributes)\n }\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n toggleNode: {\n /**\n * Toggle a node with another node.\n * @param typeOrName The type or name of the node.\n * @param toggleTypeOrName The type or name of the node to toggle.\n * @param attributes The attributes of the node.\n * @example editor.commands.toggleNode('heading', 'paragraph')\n */\n toggleNode: (\n typeOrName: string | NodeType,\n toggleTypeOrName: string | NodeType,\n attributes?: Record,\n ) => ReturnType\n }\n }\n}\n\nexport const toggleNode: RawCommands['toggleNode'] =\n (typeOrName, toggleTypeOrName, attributes = {}) =>\n ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema)\n const toggleType = getNodeType(toggleTypeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n let attributesToCopy: Record | undefined\n\n if (state.selection.$anchor.sameParent(state.selection.$head)) {\n // only copy attributes if the selection is pointing to a node of the same type\n attributesToCopy = state.selection.$anchor.parent.attrs\n }\n\n if (isActive) {\n return commands.setNode(toggleType, attributesToCopy)\n }\n\n // If the node is not active, we want to set the new node type with the given attributes\n // Copying over the attributes from the current node if the selection is pointing to a node of the same type\n return commands.setNode(type, { ...attributesToCopy, ...attributes })\n }\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { isNodeActive } from '../helpers/isNodeActive.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n toggleWrap: {\n /**\n * Wraps nodes in another node, or removes an existing wrap.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.toggleWrap('blockquote')\n */\n toggleWrap: (typeOrName: string | NodeType, attributes?: Record) => ReturnType\n }\n }\n}\n\nexport const toggleWrap: RawCommands['toggleWrap'] =\n (typeOrName, attributes = {}) =>\n ({ state, commands }) => {\n const type = getNodeType(typeOrName, state.schema)\n const isActive = isNodeActive(state, type, attributes)\n\n if (isActive) {\n return commands.lift(type)\n }\n\n return commands.wrapIn(type, attributes)\n }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n undoInputRule: {\n /**\n * Undo an input rule.\n * @example editor.commands.undoInputRule()\n */\n undoInputRule: () => ReturnType\n }\n }\n}\n\nexport const undoInputRule: RawCommands['undoInputRule'] =\n () =>\n ({ state, dispatch }) => {\n const plugins = state.plugins\n\n for (let i = 0; i < plugins.length; i += 1) {\n const plugin = plugins[i]\n let undoable\n\n // @ts-ignore\n // eslint-disable-next-line\n if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {\n if (dispatch) {\n const tr = state.tr\n const toUndo = undoable.transform\n\n for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {\n tr.step(toUndo.steps[j].invert(toUndo.docs[j]))\n }\n\n if (undoable.text) {\n const marks = tr.doc.resolve(undoable.from).marks()\n\n tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))\n } else {\n tr.delete(undoable.from, undoable.to)\n }\n }\n\n return true\n }\n }\n\n return false\n }\n", "import type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n unsetAllMarks: {\n /**\n * Remove all marks in the current selection.\n * @example editor.commands.unsetAllMarks()\n */\n unsetAllMarks: () => ReturnType\n }\n }\n}\n\nexport const unsetAllMarks: RawCommands['unsetAllMarks'] =\n () =>\n ({ tr, dispatch }) => {\n const { selection } = tr\n const { empty, ranges } = selection\n\n if (empty) {\n return true\n }\n\n if (dispatch) {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos)\n })\n }\n\n return true\n }\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarkRange } from '../helpers/getMarkRange.js'\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n unsetMark: {\n /**\n * Remove all marks in the current selection.\n * @param typeOrName The mark type or name.\n * @param options.extendEmptyMarkRange Removes the mark even across the current selection. Defaults to `false`.\n * @example editor.commands.unsetMark('bold')\n */\n unsetMark: (\n /**\n * The mark type or name.\n */\n typeOrName: string | MarkType,\n\n options?: {\n /**\n * Removes the mark even across the current selection. Defaults to `false`.\n */\n extendEmptyMarkRange?: boolean\n },\n ) => ReturnType\n }\n }\n}\n\nexport const unsetMark: RawCommands['unsetMark'] =\n (typeOrName, options = {}) =>\n ({ tr, state, dispatch }) => {\n const { extendEmptyMarkRange = false } = options\n const { selection } = tr\n const type = getMarkType(typeOrName, state.schema)\n const { $from, empty, ranges } = selection\n\n if (!dispatch) {\n return true\n }\n\n if (empty && extendEmptyMarkRange) {\n let { from, to } = selection\n const attrs = $from.marks().find(mark => mark.type === type)?.attrs\n const range = getMarkRange($from, type, attrs)\n\n if (range) {\n from = range.from\n to = range.to\n }\n\n tr.removeMark(from, to, type)\n } else {\n ranges.forEach(range => {\n tr.removeMark(range.$from.pos, range.$to.pos, type)\n })\n }\n\n tr.removeStoredMark(type)\n\n return true\n }\n", "import type { Range, RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n unsetTextDirection: {\n /**\n * Remove the text direction attribute from nodes.\n * If no position is provided, it will use the current selection.\n * @param position Optional position or range to remove the direction from\n * @example editor.commands.unsetTextDirection()\n * @example editor.commands.unsetTextDirection({ from: 0, to: 10 })\n */\n unsetTextDirection: (position?: number | Range) => ReturnType\n }\n }\n}\n\nexport const unsetTextDirection: RawCommands['unsetTextDirection'] =\n position =>\n ({ tr, state, dispatch }) => {\n const { selection } = state\n let from: number\n let to: number\n\n if (typeof position === 'number') {\n from = position\n to = position\n } else if (position && 'from' in position && 'to' in position) {\n from = position.from\n to = position.to\n } else {\n from = selection.from\n to = selection.to\n }\n\n if (dispatch) {\n tr.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isText) {\n return\n }\n\n const newAttrs = { ...node.attrs }\n\n delete newAttrs.dir\n\n tr.setNodeMarkup(pos, undefined, newAttrs)\n })\n }\n\n return true\n }\n", "import type { Mark, MarkType, Node, NodeType } from '@tiptap/pm/model'\nimport type { SelectionRange } from '@tiptap/pm/state'\n\nimport { getMarkType } from '../helpers/getMarkType.js'\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport { getSchemaTypeNameByName } from '../helpers/getSchemaTypeNameByName.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n updateAttributes: {\n /**\n * Update attributes of a node or mark.\n * @param typeOrName The type or name of the node or mark.\n * @param attributes The attributes of the node or mark.\n * @example editor.commands.updateAttributes('mention', { userId: \"2\" })\n */\n updateAttributes: (\n /**\n * The type or name of the node or mark.\n */\n typeOrName: string | NodeType | MarkType,\n\n /**\n * The attributes of the node or mark.\n */\n attributes: Record,\n ) => ReturnType\n }\n }\n}\n\nexport const updateAttributes: RawCommands['updateAttributes'] =\n (typeOrName, attributes = {}) =>\n ({ tr, state, dispatch }) => {\n let nodeType: NodeType | null = null\n let markType: MarkType | null = null\n\n const schemaType = getSchemaTypeNameByName(\n typeof typeOrName === 'string' ? typeOrName : typeOrName.name,\n state.schema,\n )\n\n if (!schemaType) {\n return false\n }\n\n if (schemaType === 'node') {\n nodeType = getNodeType(typeOrName as NodeType, state.schema)\n }\n\n if (schemaType === 'mark') {\n markType = getMarkType(typeOrName as MarkType, state.schema)\n }\n\n let canUpdate = false\n\n tr.selection.ranges.forEach((range: SelectionRange) => {\n const from = range.$from.pos\n const to = range.$to.pos\n\n let lastPos: number | undefined\n let lastNode: Node | undefined\n let trimmedFrom: number\n let trimmedTo: number\n\n if (tr.selection.empty) {\n state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n if (nodeType && nodeType === node.type) {\n canUpdate = true\n trimmedFrom = Math.max(pos, from)\n trimmedTo = Math.min(pos + node.nodeSize, to)\n lastPos = pos\n lastNode = node\n }\n })\n } else {\n state.doc.nodesBetween(from, to, (node: Node, pos: number) => {\n if (pos < from && nodeType && nodeType === node.type) {\n canUpdate = true\n trimmedFrom = Math.max(pos, from)\n trimmedTo = Math.min(pos + node.nodeSize, to)\n lastPos = pos\n lastNode = node\n }\n\n if (pos >= from && pos <= to) {\n if (nodeType && nodeType === node.type) {\n canUpdate = true\n\n if (dispatch) {\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n ...attributes,\n })\n }\n }\n\n if (markType && node.marks.length) {\n node.marks.forEach((mark: Mark) => {\n if (markType === mark.type) {\n canUpdate = true\n\n if (dispatch) {\n const trimmedFrom2 = Math.max(pos, from)\n const trimmedTo2 = Math.min(pos + node.nodeSize, to)\n\n tr.addMark(\n trimmedFrom2,\n trimmedTo2,\n markType.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n }\n })\n }\n }\n })\n }\n\n if (lastNode) {\n if (lastPos !== undefined && dispatch) {\n tr.setNodeMarkup(lastPos, undefined, {\n ...lastNode.attrs,\n ...attributes,\n })\n }\n\n if (markType && lastNode.marks.length) {\n lastNode.marks.forEach((mark: Mark) => {\n if (markType === mark.type && dispatch) {\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n markType.create({\n ...mark.attrs,\n ...attributes,\n }),\n )\n }\n })\n }\n }\n })\n\n return canUpdate\n }\n", "import { wrapIn as originalWrapIn } from '@tiptap/pm/commands'\nimport type { NodeType } from '@tiptap/pm/model'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n wrapIn: {\n /**\n * Wraps nodes in another node.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.wrapIn('blockquote')\n */\n wrapIn: (typeOrName: string | NodeType, attributes?: Record) => ReturnType\n }\n }\n}\n\nexport const wrapIn: RawCommands['wrapIn'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalWrapIn(type, attributes)(state, dispatch)\n }\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { wrapInList as originalWrapInList } from '@tiptap/pm/schema-list'\n\nimport { getNodeType } from '../helpers/getNodeType.js'\nimport type { RawCommands } from '../types.js'\n\ndeclare module '@tiptap/core' {\n interface Commands {\n wrapInList: {\n /**\n * Wrap a node in a list.\n * @param typeOrName The type or name of the node.\n * @param attributes The attributes of the node.\n * @example editor.commands.wrapInList('bulletList')\n */\n wrapInList: (typeOrName: string | NodeType, attributes?: Record) => ReturnType\n }\n }\n}\n\nexport const wrapInList: RawCommands['wrapInList'] =\n (typeOrName, attributes = {}) =>\n ({ state, dispatch }) => {\n const type = getNodeType(typeOrName, state.schema)\n\n return originalWrapInList(type, attributes)(state, dispatch)\n }\n", "/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport type { MarkType, Node as ProseMirrorNode, NodeType, Schema } from '@tiptap/pm/model'\nimport type { Plugin, PluginKey, Transaction } from '@tiptap/pm/state'\nimport { EditorState } from '@tiptap/pm/state'\nimport { EditorView } from '@tiptap/pm/view'\n\nimport { CommandManager } from './CommandManager.js'\nimport { EventEmitter } from './EventEmitter.js'\nimport { ExtensionManager } from './ExtensionManager.js'\nimport {\n ClipboardTextSerializer,\n Commands,\n Delete,\n Drop,\n Editable,\n FocusEvents,\n Keymap,\n Paste,\n Tabindex,\n TextDirection,\n} from './extensions/index.js'\nimport { createDocument } from './helpers/createDocument.js'\nimport { getAttributes } from './helpers/getAttributes.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getText } from './helpers/getText.js'\nimport { getTextSerializersFromSchema } from './helpers/getTextSerializersFromSchema.js'\nimport { isActive } from './helpers/isActive.js'\nimport { isNodeEmpty } from './helpers/isNodeEmpty.js'\nimport { createMappablePosition, getUpdatedPosition } from './helpers/MappablePosition.js'\nimport { resolveFocusPosition } from './helpers/resolveFocusPosition.js'\nimport type { Storage } from './index.js'\nimport { NodePos } from './NodePos.js'\nimport { style } from './style.js'\nimport type {\n CanCommands,\n ChainedCommands,\n DocumentType,\n EditorEvents,\n EditorOptions,\n NodeType as TNodeType,\n SingleCommands,\n TextSerializer,\n TextType as TTextType,\n Utils,\n} from './types.js'\nimport { createStyleTag } from './utilities/createStyleTag.js'\nimport { isFunction } from './utilities/isFunction.js'\n\nexport * as extensions from './extensions/index.js'\n\n// @ts-ignore\nexport interface TiptapEditorHTMLElement extends HTMLElement {\n editor?: Editor\n}\n\nexport class Editor extends EventEmitter {\n private commandManager!: CommandManager\n\n public extensionManager!: ExtensionManager\n\n private css: HTMLStyleElement | null = null\n\n private className = 'tiptap'\n\n public schema!: Schema\n\n private editorView: EditorView | null = null\n\n public isFocused = false\n\n private editorState!: EditorState\n\n /**\n * The editor is considered initialized after the `create` event has been emitted.\n */\n public isInitialized = false\n\n public extensionStorage: Storage = {} as Storage\n\n /**\n * A unique ID for this editor instance.\n */\n public instanceId = Math.random().toString(36).slice(2, 9)\n\n public options: EditorOptions = {\n element: typeof document !== 'undefined' ? document.createElement('div') : null,\n content: '',\n injectCSS: true,\n injectNonce: undefined,\n extensions: [],\n autofocus: false,\n editable: true,\n textDirection: undefined,\n editorProps: {},\n parseOptions: {},\n coreExtensionOptions: {},\n enableInputRules: true,\n enablePasteRules: true,\n enableCoreExtensions: true,\n enableContentCheck: false,\n emitContentError: false,\n onBeforeCreate: () => null,\n onCreate: () => null,\n onMount: () => null,\n onUnmount: () => null,\n onUpdate: () => null,\n onSelectionUpdate: () => null,\n onTransaction: () => null,\n onFocus: () => null,\n onBlur: () => null,\n onDestroy: () => null,\n onContentError: ({ error }) => {\n throw error\n },\n onPaste: () => null,\n onDrop: () => null,\n onDelete: () => null,\n enableExtensionDispatchTransaction: true,\n }\n\n constructor(options: Partial = {}) {\n super()\n this.setOptions(options)\n this.createExtensionManager()\n this.createCommandManager()\n this.createSchema()\n this.on('beforeCreate', this.options.onBeforeCreate)\n this.emit('beforeCreate', { editor: this })\n this.on('mount', this.options.onMount)\n this.on('unmount', this.options.onUnmount)\n this.on('contentError', this.options.onContentError)\n this.on('create', this.options.onCreate)\n this.on('update', this.options.onUpdate)\n this.on('selectionUpdate', this.options.onSelectionUpdate)\n this.on('transaction', this.options.onTransaction)\n this.on('focus', this.options.onFocus)\n this.on('blur', this.options.onBlur)\n this.on('destroy', this.options.onDestroy)\n this.on('drop', ({ event, slice, moved }) => this.options.onDrop(event, slice, moved))\n this.on('paste', ({ event, slice }) => this.options.onPaste(event, slice))\n this.on('delete', this.options.onDelete)\n\n const initialDoc = this.createDoc()\n const selection = resolveFocusPosition(initialDoc, this.options.autofocus)\n\n // Set editor state immediately, so that it's available independently from the view\n this.editorState = EditorState.create({\n doc: initialDoc,\n schema: this.schema,\n selection: selection || undefined,\n })\n\n if (this.options.element) {\n this.mount(this.options.element)\n }\n }\n\n /**\n * Attach the editor to the DOM, creating a new editor view.\n */\n public mount(el: NonNullable & {}) {\n if (typeof document === 'undefined') {\n throw new Error(\n `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`,\n )\n }\n this.createView(el)\n this.emit('mount', { editor: this })\n\n if (this.css && !document.head.contains(this.css)) {\n document.head.appendChild(this.css)\n }\n\n window.setTimeout(() => {\n if (this.isDestroyed) {\n return\n }\n\n if (this.options.autofocus !== false && this.options.autofocus !== null) {\n this.commands.focus(this.options.autofocus)\n }\n this.emit('create', { editor: this })\n this.isInitialized = true\n }, 0)\n }\n\n /**\n * Remove the editor from the DOM, but still allow remounting at a different point in time\n */\n public unmount() {\n if (this.editorView) {\n // Cleanup our reference to prevent circular references which caused memory leaks\n // @ts-ignore\n const dom = this.editorView.dom as TiptapEditorHTMLElement\n\n if (dom?.editor) {\n delete dom.editor\n }\n this.editorView.destroy()\n }\n this.editorView = null\n this.isInitialized = false\n\n // Safely remove CSS element with fallback for test environments\n // Only remove CSS if no other editors exist in the document after unmount\n if (this.css && !document.querySelectorAll(`.${this.className}`).length) {\n try {\n if (typeof this.css.remove === 'function') {\n this.css.remove()\n } else if (this.css.parentNode) {\n this.css.parentNode.removeChild(this.css)\n }\n } catch (error) {\n // Silently handle any unexpected DOM removal errors in test environments\n console.warn('Failed to remove CSS element:', error)\n }\n }\n this.css = null\n this.emit('unmount', { editor: this })\n }\n\n /**\n * Returns the editor storage.\n */\n public get storage(): Storage {\n return this.extensionStorage\n }\n\n /**\n * An object of all registered commands.\n */\n public get commands(): SingleCommands {\n return this.commandManager.commands\n }\n\n /**\n * Create a command chain to call multiple commands at once.\n */\n public chain(): ChainedCommands {\n return this.commandManager.chain()\n }\n\n /**\n * Check if a command or a command chain can be executed. Without executing it.\n */\n public can(): CanCommands {\n return this.commandManager.can()\n }\n\n /**\n * Inject CSS styles.\n */\n private injectCSS(): void {\n if (this.options.injectCSS && typeof document !== 'undefined') {\n this.css = createStyleTag(style, this.options.injectNonce)\n }\n }\n\n /**\n * Update editor options.\n *\n * @param options A list of options\n */\n public setOptions(options: Partial = {}): void {\n this.options = {\n ...this.options,\n ...options,\n }\n\n if (!this.editorView || !this.state || this.isDestroyed) {\n return\n }\n\n if (this.options.editorProps) {\n this.view.setProps(this.options.editorProps)\n }\n\n this.view.updateState(this.state)\n }\n\n /**\n * Update editable state of the editor.\n */\n public setEditable(editable: boolean, emitUpdate = true): void {\n this.setOptions({ editable })\n\n if (emitUpdate) {\n this.emit('update', { editor: this, transaction: this.state.tr, appendedTransactions: [] })\n }\n }\n\n /**\n * Returns whether the editor is editable.\n */\n public get isEditable(): boolean {\n // since plugins are applied after creating the view\n // `editable` is always `true` for one tick.\n // that’s why we also have to check for `options.editable`\n return this.options.editable && this.view && this.view.editable\n }\n\n /**\n * Returns the editor state.\n */\n public get view(): EditorView {\n if (this.editorView) {\n return this.editorView\n }\n\n return new Proxy(\n {\n state: this.editorState,\n updateState: (state: EditorState): ReturnType => {\n this.editorState = state\n },\n dispatch: (tr: Transaction): ReturnType => {\n this.dispatchTransaction(tr)\n },\n\n // Stub some commonly accessed properties to prevent errors\n composing: false,\n dragging: null,\n editable: true,\n isDestroyed: false,\n } as EditorView,\n {\n get: (obj, key) => {\n if (this.editorView) {\n // If the editor view is available, but the caller has a stale reference to the proxy,\n // Just return what the editor view has.\n return this.editorView[key as keyof EditorView]\n }\n // Specifically always return the most recent editorState\n if (key === 'state') {\n return this.editorState\n }\n if (key in obj) {\n return Reflect.get(obj, key)\n }\n\n // We throw an error here, because we know the view is not available\n throw new Error(\n `[tiptap error]: The editor view is not available. Cannot access view['${key as string}']. The editor may not be mounted yet.`,\n )\n },\n },\n ) as EditorView\n }\n\n /**\n * Returns the editor state.\n */\n public get state(): EditorState {\n if (this.editorView) {\n this.editorState = this.view.state\n }\n\n return this.editorState\n }\n\n /**\n * Register a ProseMirror plugin.\n *\n * @param plugin A ProseMirror plugin\n * @param handlePlugins Control how to merge the plugin into the existing plugins.\n * @returns The new editor state\n */\n public registerPlugin(\n plugin: Plugin,\n handlePlugins?: (newPlugin: Plugin, plugins: Plugin[]) => Plugin[],\n ): EditorState {\n const plugins = isFunction(handlePlugins)\n ? handlePlugins(plugin, [...this.state.plugins])\n : [...this.state.plugins, plugin]\n\n const state = this.state.reconfigure({ plugins })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Unregister a ProseMirror plugin.\n *\n * @param nameOrPluginKeyToRemove The plugins name\n * @returns The new editor state or undefined if the editor is destroyed\n */\n public unregisterPlugin(\n nameOrPluginKeyToRemove: string | PluginKey | (string | PluginKey)[],\n ): EditorState | undefined {\n if (this.isDestroyed) {\n return undefined\n }\n\n const prevPlugins = this.state.plugins\n let plugins = prevPlugins\n\n ;([] as (string | PluginKey)[]).concat(nameOrPluginKeyToRemove).forEach(nameOrPluginKey => {\n // @ts-ignore\n const name = typeof nameOrPluginKey === 'string' ? `${nameOrPluginKey}$` : nameOrPluginKey.key\n\n // @ts-ignore\n plugins = plugins.filter(plugin => !plugin.key.startsWith(name))\n })\n\n if (prevPlugins.length === plugins.length) {\n // No plugin was removed, so we don’t need to update the state\n return undefined\n }\n\n const state = this.state.reconfigure({\n plugins,\n })\n\n this.view.updateState(state)\n\n return state\n }\n\n /**\n * Creates an extension manager.\n */\n private createExtensionManager(): void {\n const coreExtensions = this.options.enableCoreExtensions\n ? [\n Editable,\n ClipboardTextSerializer.configure({\n blockSeparator: this.options.coreExtensionOptions?.clipboardTextSerializer?.blockSeparator,\n }),\n Commands,\n FocusEvents,\n Keymap,\n Tabindex,\n Drop,\n Paste,\n Delete,\n TextDirection.configure({\n direction: this.options.textDirection,\n }),\n ].filter(ext => {\n if (typeof this.options.enableCoreExtensions === 'object') {\n return (\n this.options.enableCoreExtensions[ext.name as keyof typeof this.options.enableCoreExtensions] !== false\n )\n }\n return true\n })\n : []\n const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {\n return ['extension', 'node', 'mark'].includes(extension?.type)\n })\n\n this.extensionManager = new ExtensionManager(allExtensions, this)\n }\n\n /**\n * Creates an command manager.\n */\n private createCommandManager(): void {\n this.commandManager = new CommandManager({\n editor: this,\n })\n }\n\n /**\n * Creates a ProseMirror schema.\n */\n private createSchema(): void {\n this.schema = this.extensionManager.schema\n }\n\n /**\n * Creates the initial document.\n */\n private createDoc(): ProseMirrorNode {\n let doc: ProseMirrorNode\n\n try {\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: this.options.enableContentCheck,\n })\n } catch (e) {\n if (\n !(e instanceof Error) ||\n !['[tiptap error]: Invalid JSON content', '[tiptap error]: Invalid HTML content'].includes(e.message)\n ) {\n // Not the content error we were expecting\n throw e\n }\n this.emit('contentError', {\n editor: this,\n error: e as Error,\n disableCollaboration: () => {\n if (\n 'collaboration' in this.storage &&\n typeof this.storage.collaboration === 'object' &&\n this.storage.collaboration\n ) {\n ;(this.storage.collaboration as any).isDisabled = true\n }\n // To avoid syncing back invalid content, reinitialize the extensions without the collaboration extension\n this.options.extensions = this.options.extensions.filter(extension => extension.name !== 'collaboration')\n\n // Restart the initialization process by recreating the extension manager with the new set of extensions\n this.createExtensionManager()\n },\n })\n\n // Content is invalid, but attempt to create it anyway, stripping out the invalid parts\n doc = createDocument(this.options.content, this.schema, this.options.parseOptions, {\n errorOnInvalidContent: false,\n })\n }\n return doc\n }\n\n /**\n * Creates a ProseMirror view.\n */\n private createView(element: NonNullable): void {\n const { editorProps, enableExtensionDispatchTransaction } = this.options\n // If a user provided a custom `dispatchTransaction` through `editorProps`,\n // we use that as the base dispatch function.\n // Otherwise, we use Tiptap's internal `dispatchTransaction` method.\n const baseDispatch = (editorProps as any).dispatchTransaction || this.dispatchTransaction.bind(this)\n const dispatch = enableExtensionDispatchTransaction\n ? this.extensionManager.dispatchTransaction(baseDispatch)\n : baseDispatch\n\n this.editorView = new EditorView(element, {\n ...editorProps,\n attributes: {\n // add `role=\"textbox\"` to the editor element\n role: 'textbox',\n ...editorProps?.attributes,\n },\n dispatchTransaction: dispatch,\n state: this.editorState,\n markViews: this.extensionManager.markViews,\n nodeViews: this.extensionManager.nodeViews,\n })\n\n // `editor.view` is not yet available at this time.\n // Therefore we will add all plugins and node views directly afterwards.\n const newState = this.state.reconfigure({\n plugins: this.extensionManager.plugins,\n })\n\n this.view.updateState(newState)\n\n this.prependClass()\n this.injectCSS()\n\n // Let’s store the editor instance in the DOM element.\n // So we’ll have access to it for tests.\n // @ts-ignore\n const dom = this.view.dom as TiptapEditorHTMLElement\n\n dom.editor = this\n }\n\n /**\n * Creates all node and mark views.\n */\n public createNodeViews(): void {\n if (this.view.isDestroyed) {\n return\n }\n\n this.view.setProps({\n markViews: this.extensionManager.markViews,\n nodeViews: this.extensionManager.nodeViews,\n })\n }\n\n /**\n * Prepend class name to element.\n */\n public prependClass(): void {\n this.view.dom.className = `${this.className} ${this.view.dom.className}`\n }\n\n public isCapturingTransaction = false\n\n private capturedTransaction: Transaction | null = null\n\n public captureTransaction(fn: () => void) {\n this.isCapturingTransaction = true\n fn()\n this.isCapturingTransaction = false\n\n const tr = this.capturedTransaction\n\n this.capturedTransaction = null\n\n return tr\n }\n\n /**\n * The callback over which to send transactions (state updates) produced by the view.\n *\n * @param transaction An editor state transaction\n */\n private dispatchTransaction(transaction: Transaction): void {\n // if the editor / the view of the editor was destroyed\n // the transaction should not be dispatched as there is no view anymore.\n if (this.view.isDestroyed) {\n return\n }\n\n if (this.isCapturingTransaction) {\n if (!this.capturedTransaction) {\n this.capturedTransaction = transaction\n\n return\n }\n\n transaction.steps.forEach(step => this.capturedTransaction?.step(step))\n\n return\n }\n\n // Apply transaction and get resulting state and transactions\n const { state, transactions } = this.state.applyTransaction(transaction)\n const selectionHasChanged = !this.state.selection.eq(state.selection)\n const rootTrWasApplied = transactions.includes(transaction)\n const prevState = this.state\n\n this.emit('beforeTransaction', {\n editor: this,\n transaction,\n nextState: state,\n })\n\n // If transaction was filtered out, we can return early\n if (!rootTrWasApplied) {\n return\n }\n\n this.view.updateState(state)\n\n // Emit transaction event with appended transactions info\n this.emit('transaction', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n\n if (selectionHasChanged) {\n this.emit('selectionUpdate', {\n editor: this,\n transaction,\n })\n }\n\n // Only emit the latest between focus and blur events\n const mostRecentFocusTr = transactions.findLast(tr => tr.getMeta('focus') || tr.getMeta('blur'))\n const focus = mostRecentFocusTr?.getMeta('focus')\n const blur = mostRecentFocusTr?.getMeta('blur')\n\n if (focus) {\n this.emit('focus', {\n editor: this,\n event: focus.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n if (blur) {\n this.emit('blur', {\n editor: this,\n event: blur.event,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n transaction: mostRecentFocusTr!,\n })\n }\n\n // Compare states for update event\n if (\n transaction.getMeta('preventUpdate') ||\n !transactions.some(tr => tr.docChanged) ||\n prevState.doc.eq(state.doc)\n ) {\n return\n }\n\n this.emit('update', {\n editor: this,\n transaction,\n appendedTransactions: transactions.slice(1),\n })\n }\n\n /**\n * Get attributes of the currently selected node or mark.\n */\n public getAttributes(nameOrType: string | NodeType | MarkType): Record {\n return getAttributes(this.state, nameOrType)\n }\n\n /**\n * Returns if the currently selected node or mark is active.\n *\n * @param name Name of the node or mark\n * @param attributes Attributes of the node or mark\n */\n public isActive(name: string, attributes?: {}): boolean\n public isActive(attributes: {}): boolean\n public isActive(nameOrAttributes: string, attributesOrUndefined?: {}): boolean {\n const name = typeof nameOrAttributes === 'string' ? nameOrAttributes : null\n\n const attributes = typeof nameOrAttributes === 'string' ? attributesOrUndefined : nameOrAttributes\n\n return isActive(this.state, name, attributes)\n }\n\n /**\n * Get the document as JSON.\n */\n public getJSON(): DocumentType<\n Record | undefined,\n TNodeType, any, (TNodeType | TTextType)[]>[]\n > {\n return this.state.doc.toJSON()\n }\n\n /**\n * Get the document as HTML.\n */\n public getHTML(): string {\n return getHTMLFromFragment(this.state.doc.content, this.schema)\n }\n\n /**\n * Get the document as text.\n */\n public getText(options?: { blockSeparator?: string; textSerializers?: Record }): string {\n const { blockSeparator = '\\n\\n', textSerializers = {} } = options || {}\n\n return getText(this.state.doc, {\n blockSeparator,\n textSerializers: {\n ...getTextSerializersFromSchema(this.schema),\n ...textSerializers,\n },\n })\n }\n\n /**\n * Check if there is no content.\n */\n public get isEmpty(): boolean {\n return isNodeEmpty(this.state.doc)\n }\n\n /**\n * Destroy the editor.\n */\n public destroy(): void {\n this.emit('destroy')\n\n this.unmount()\n\n this.removeAllListeners()\n }\n\n /**\n * Check if the editor is already destroyed.\n */\n public get isDestroyed(): boolean {\n return this.editorView?.isDestroyed ?? true\n }\n\n public $node(selector: string, attributes?: { [key: string]: any }): NodePos | null {\n return this.$doc?.querySelector(selector, attributes) || null\n }\n\n public $nodes(selector: string, attributes?: { [key: string]: any }): NodePos[] | null {\n return this.$doc?.querySelectorAll(selector, attributes) || null\n }\n\n public $pos(pos: number) {\n const $pos = this.state.doc.resolve(pos)\n\n return new NodePos($pos, this)\n }\n\n get $doc() {\n return this.$pos(0)\n }\n\n /**\n * Returns a set of utilities for working with positions and ranges.\n */\n public utils: Utils = {\n getUpdatedPosition,\n createMappablePosition,\n }\n}\n", "type StringKeyOf = Extract\ntype CallbackType, EventName extends StringKeyOf> = T[EventName] extends any[]\n ? T[EventName]\n : [T[EventName]]\ntype CallbackFunction, EventName extends StringKeyOf> = (\n ...props: CallbackType\n) => any\n\nexport class EventEmitter> {\n private callbacks: { [key: string]: Array<(...args: any[]) => void> } = {}\n\n public on>(event: EventName, fn: CallbackFunction): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = []\n }\n\n this.callbacks[event].push(fn)\n\n return this\n }\n\n public emit>(event: EventName, ...args: CallbackType): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n callbacks.forEach(callback => callback.apply(this, args))\n }\n\n return this\n }\n\n public off>(event: EventName, fn?: CallbackFunction): this {\n const callbacks = this.callbacks[event]\n\n if (callbacks) {\n if (fn) {\n this.callbacks[event] = callbacks.filter(callback => callback !== fn)\n } else {\n delete this.callbacks[event]\n }\n }\n\n return this\n }\n\n public once>(event: EventName, fn: CallbackFunction): this {\n const onceFn = (...args: CallbackType) => {\n this.off(event, onceFn)\n fn.apply(this, args)\n }\n\n return this.on(event, onceFn)\n }\n\n public removeAllListeners(): void {\n this.callbacks = {}\n }\n}\n", "import { keymap } from '@tiptap/pm/keymap'\nimport type { Schema } from '@tiptap/pm/model'\nimport type { Plugin, Transaction } from '@tiptap/pm/state'\nimport type { MarkViewConstructor, NodeViewConstructor } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport {\n flattenExtensions,\n getAttributesFromExtensions,\n getExtensionField,\n getNodeType,\n getRenderedAttributes,\n getSchemaByResolvedExtensions,\n getSchemaTypeByName,\n isExtensionRulesEnabled,\n resolveExtensions,\n sortExtensions,\n splitExtensions,\n} from './helpers/index.js'\nimport { type MarkConfig, type NodeConfig, type Storage, getMarkType, updateMarkViewAttributes } from './index.js'\nimport { inputRulesPlugin } from './InputRule.js'\nimport { Mark } from './Mark.js'\nimport { pasteRulesPlugin } from './PasteRule.js'\nimport type { AnyConfig, Extensions, RawCommands } from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\n\nexport class ExtensionManager {\n editor: Editor\n\n schema: Schema\n\n /**\n * A flattened and sorted array of all extensions\n */\n extensions: Extensions\n\n /**\n * A non-flattened array of base extensions (no sub-extensions)\n */\n baseExtensions: Extensions\n\n splittableMarks: string[] = []\n\n constructor(extensions: Extensions, editor: Editor) {\n this.editor = editor\n this.baseExtensions = extensions\n this.extensions = resolveExtensions(extensions)\n this.schema = getSchemaByResolvedExtensions(this.extensions, editor)\n this.setupExtensions()\n }\n\n static resolve = resolveExtensions\n\n static sort = sortExtensions\n\n static flatten = flattenExtensions\n\n /**\n * Get all commands from the extensions.\n * @returns An object with all commands where the key is the command name and the value is the command function\n */\n get commands(): RawCommands {\n return this.extensions.reduce((commands, extension) => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const addCommands = getExtensionField(extension, 'addCommands', context)\n\n if (!addCommands) {\n return commands\n }\n\n return {\n ...commands,\n ...addCommands(),\n }\n }, {} as RawCommands)\n }\n\n /**\n * Get all registered Prosemirror plugins from the extensions.\n * @returns An array of Prosemirror plugins\n */\n get plugins(): Plugin[] {\n const { editor } = this\n\n // With ProseMirror, first plugins within an array are executed first.\n // In Tiptap, we provide the ability to override plugins,\n // so it feels more natural to run plugins at the end of an array first.\n // That’s why we have to reverse the `extensions` array and sort again\n // based on the `priority` option.\n const extensions = sortExtensions([...this.extensions].reverse())\n\n const allPlugins = extensions.flatMap(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const plugins: Plugin[] = []\n\n const addKeyboardShortcuts = getExtensionField(\n extension,\n 'addKeyboardShortcuts',\n context,\n )\n\n let defaultBindings: Record boolean> = {}\n\n // bind exit handling\n if (extension.type === 'mark' && getExtensionField(extension, 'exitable', context)) {\n defaultBindings.ArrowRight = () => Mark.handleExit({ editor, mark: extension as Mark })\n }\n\n if (addKeyboardShortcuts) {\n const bindings = Object.fromEntries(\n Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {\n return [shortcut, () => method({ editor })]\n }),\n )\n\n defaultBindings = { ...defaultBindings, ...bindings }\n }\n\n const keyMapPlugin = keymap(defaultBindings)\n\n plugins.push(keyMapPlugin)\n\n const addInputRules = getExtensionField(extension, 'addInputRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {\n const rules = addInputRules()\n\n if (rules && rules.length) {\n const inputResult = inputRulesPlugin({\n editor,\n rules,\n })\n\n const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult]\n\n plugins.push(...inputPlugins)\n }\n }\n\n const addPasteRules = getExtensionField(extension, 'addPasteRules', context)\n\n if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {\n const rules = addPasteRules()\n\n if (rules && rules.length) {\n const pasteRules = pasteRulesPlugin({ editor, rules })\n\n plugins.push(...pasteRules)\n }\n }\n\n const addProseMirrorPlugins = getExtensionField(\n extension,\n 'addProseMirrorPlugins',\n context,\n )\n\n if (addProseMirrorPlugins) {\n const proseMirrorPlugins = addProseMirrorPlugins()\n\n plugins.push(...proseMirrorPlugins)\n }\n\n return plugins\n })\n\n return allPlugins\n }\n\n /**\n * Get all attributes from the extensions.\n * @returns An array of attributes\n */\n get attributes() {\n return getAttributesFromExtensions(this.extensions)\n }\n\n /**\n * Get all node views from the extensions.\n * @returns An object with all node views where the key is the node name and the value is the node view function\n */\n get nodeViews(): Record {\n const { editor } = this\n const { nodeExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n nodeExtensions\n .filter(extension => !!getExtensionField(extension, 'addNodeView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getNodeType(extension.name, this.schema),\n }\n const addNodeView = getExtensionField(extension, 'addNodeView', context)\n\n if (!addNodeView) {\n return []\n }\n\n const nodeViewResult = addNodeView()\n\n if (!nodeViewResult) {\n return []\n }\n\n const nodeview: NodeViewConstructor = (node, view, getPos, decorations, innerDecorations) => {\n const HTMLAttributes = getRenderedAttributes(node, extensionAttributes)\n\n return nodeViewResult({\n // pass-through\n node,\n view,\n getPos: getPos as () => number,\n decorations,\n innerDecorations,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n })\n }\n\n return [extension.name, nodeview]\n }),\n )\n }\n\n /**\n * Get the composed dispatchTransaction function from all extensions.\n * @param baseDispatch The base dispatch function (e.g. from the editor or user props)\n * @returns A composed dispatch function\n */\n dispatchTransaction(baseDispatch: (tr: Transaction) => void): (tr: Transaction) => void {\n const { editor } = this\n const extensions = sortExtensions([...this.extensions].reverse())\n\n return extensions.reduceRight((next, extension) => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n const dispatchTransaction = getExtensionField(\n extension,\n 'dispatchTransaction',\n context,\n )\n\n if (!dispatchTransaction) {\n return next\n }\n\n return (transaction: Transaction) => {\n dispatchTransaction.call(context, { transaction, next })\n }\n }, baseDispatch)\n }\n\n get markViews(): Record {\n const { editor } = this\n const { markExtensions } = splitExtensions(this.extensions)\n\n return Object.fromEntries(\n markExtensions\n .filter(extension => !!getExtensionField(extension, 'addMarkView'))\n .map(extension => {\n const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name)\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor,\n type: getMarkType(extension.name, this.schema),\n }\n const addMarkView = getExtensionField(extension, 'addMarkView', context)\n\n if (!addMarkView) {\n return []\n }\n\n const markView: MarkViewConstructor = (mark, view, inline) => {\n const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes)\n\n return addMarkView()({\n // pass-through\n mark,\n view,\n inline,\n // tiptap-specific\n editor,\n extension,\n HTMLAttributes,\n updateAttributes: (attrs: Record) => {\n updateMarkViewAttributes(mark, editor, attrs)\n },\n })\n }\n\n return [extension.name, markView]\n }),\n )\n }\n\n /**\n * Go through all extensions, create extension storages & setup marks\n * & bind editor event listener.\n */\n private setupExtensions() {\n const extensions = this.extensions\n // re-initialize the extension storage object instance\n this.editor.extensionStorage = Object.fromEntries(\n extensions.map(extension => [extension.name, extension.storage]),\n ) as unknown as Storage\n\n extensions.forEach(extension => {\n const context = {\n name: extension.name,\n options: extension.options,\n storage: this.editor.extensionStorage[extension.name as keyof Storage],\n editor: this.editor,\n type: getSchemaTypeByName(extension.name, this.schema),\n }\n\n if (extension.type === 'mark') {\n const keepOnSplit = callOrReturn(getExtensionField(extension, 'keepOnSplit', context)) ?? true\n\n if (keepOnSplit) {\n this.splittableMarks.push(extension.name)\n }\n }\n\n const onBeforeCreate = getExtensionField(extension, 'onBeforeCreate', context)\n const onCreate = getExtensionField(extension, 'onCreate', context)\n const onUpdate = getExtensionField(extension, 'onUpdate', context)\n const onSelectionUpdate = getExtensionField(\n extension,\n 'onSelectionUpdate',\n context,\n )\n const onTransaction = getExtensionField(extension, 'onTransaction', context)\n const onFocus = getExtensionField(extension, 'onFocus', context)\n const onBlur = getExtensionField(extension, 'onBlur', context)\n const onDestroy = getExtensionField(extension, 'onDestroy', context)\n\n if (onBeforeCreate) {\n this.editor.on('beforeCreate', onBeforeCreate)\n }\n\n if (onCreate) {\n this.editor.on('create', onCreate)\n }\n\n if (onUpdate) {\n this.editor.on('update', onUpdate)\n }\n\n if (onSelectionUpdate) {\n this.editor.on('selectionUpdate', onSelectionUpdate)\n }\n\n if (onTransaction) {\n this.editor.on('transaction', onTransaction)\n }\n\n if (onFocus) {\n this.editor.on('focus', onFocus)\n }\n\n if (onBlur) {\n this.editor.on('blur', onBlur)\n }\n\n if (onDestroy) {\n this.editor.on('destroy', onDestroy)\n }\n })\n }\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport type { EditorState, TextSelection } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport { getTextContentFromNodes } from './helpers/getTextContentFromNodes.js'\nimport type { CanCommands, ChainedCommands, ExtendedRegExpMatchArray, Range, SingleCommands } from './types.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type InputRuleMatch = {\n index: number\n text: string\n replaceWith?: string\n match?: RegExpMatchArray\n data?: Record\n}\n\nexport type InputRuleFinder = RegExp | ((text: string) => InputRuleMatch | null)\n\nexport class InputRule {\n find: InputRuleFinder\n\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n }) => void | null\n\n undoable: boolean\n\n constructor(config: {\n find: InputRuleFinder\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n }) => void | null\n undoable?: boolean\n }) {\n this.find = config.find\n this.handler = config.handler\n this.undoable = config.undoable ?? true\n }\n}\n\nconst inputRuleMatcherHandler = (text: string, find: InputRuleFinder): ExtendedRegExpMatchArray | null => {\n if (isRegExp(find)) {\n return find.exec(text)\n }\n\n const inputRuleMatch = find(text)\n\n if (!inputRuleMatch) {\n return null\n }\n\n const result: ExtendedRegExpMatchArray = [inputRuleMatch.text]\n\n result.index = inputRuleMatch.index\n result.input = text\n result.data = inputRuleMatch.data\n\n if (inputRuleMatch.replaceWith) {\n if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"inputRuleMatch.replaceWith\" must be part of \"inputRuleMatch.text\".')\n }\n\n result.push(inputRuleMatch.replaceWith)\n }\n\n return result\n}\n\nfunction run(config: {\n editor: Editor\n from: number\n to: number\n text: string\n rules: InputRule[]\n plugin: Plugin\n}): boolean {\n const { editor, from, to, text, rules, plugin } = config\n const { view } = editor\n\n if (view.composing) {\n return false\n }\n\n const $from = view.state.doc.resolve(from)\n\n if (\n // check for code node\n $from.parent.type.spec.code ||\n // check for code mark\n !!($from.nodeBefore || $from.nodeAfter)?.marks.find(mark => mark.type.spec.code)\n ) {\n return false\n }\n\n let matched = false\n\n const textBefore = getTextContentFromNodes($from) + text\n\n rules.forEach(rule => {\n if (matched) {\n return\n }\n\n const match = inputRuleMatcherHandler(textBefore, rule.find)\n\n if (!match) {\n return\n }\n\n const tr = view.state.tr\n const state = createChainableState({\n state: view.state,\n transaction: tr,\n })\n const range = {\n from: from - (match[0].length - text.length),\n to,\n }\n\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n })\n\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n })\n\n // stop if there are no changes\n if (handler === null || !tr.steps.length) {\n return\n }\n\n // store transform as meta data\n // so we can undo input rules within the `undoInputRules` command\n if (rule.undoable) {\n tr.setMeta(plugin, {\n transform: tr,\n from,\n to,\n text,\n })\n }\n\n view.dispatch(tr)\n matched = true\n })\n\n return matched\n}\n\n/**\n * Create an input rules plugin. When enabled, it will cause text\n * input that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function inputRulesPlugin(props: { editor: Editor; rules: InputRule[] }): Plugin {\n const { editor, rules } = props\n const plugin = new Plugin({\n state: {\n init() {\n return null\n },\n apply(tr, prev, state) {\n const stored = tr.getMeta(plugin)\n\n if (stored) {\n return stored\n }\n\n // if InputRule is triggered by insertContent()\n const simulatedInputMeta = tr.getMeta('applyInputRules') as\n | undefined\n | {\n from: number\n text: string | ProseMirrorNode | Fragment\n }\n const isSimulatedInput = !!simulatedInputMeta\n\n if (isSimulatedInput) {\n setTimeout(() => {\n let { text } = simulatedInputMeta\n\n if (typeof text === 'string') {\n text = text as string\n } else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema)\n }\n\n const { from } = simulatedInputMeta\n const to = from + text.length\n\n run({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n })\n })\n }\n\n return tr.selectionSet || tr.docChanged ? null : prev\n },\n },\n\n props: {\n handleTextInput(view, from, to, text) {\n return run({\n editor,\n from,\n to,\n text,\n rules,\n plugin,\n })\n },\n\n handleDOMEvents: {\n compositionend: view => {\n setTimeout(() => {\n const { $cursor } = view.state.selection as TextSelection\n\n if ($cursor) {\n run({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '',\n rules,\n plugin,\n })\n }\n })\n\n return false\n },\n },\n\n // add support for input rules to trigger on enter\n // this is useful for example for code blocks\n handleKeyDown(view, event) {\n if (event.key !== 'Enter') {\n return false\n }\n\n const { $cursor } = view.state.selection as TextSelection\n\n if ($cursor) {\n return run({\n editor,\n from: $cursor.pos,\n to: $cursor.pos,\n text: '\\n',\n rules,\n plugin,\n })\n }\n\n return false\n },\n },\n\n // @ts-ignore\n isInputRules: true,\n }) as Plugin\n\n return plugin\n}\n", "// see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts\n\nfunction getType(value: any): string {\n return Object.prototype.toString.call(value).slice(8, -1)\n}\n\nexport function isPlainObject(value: any): value is Record {\n if (getType(value) !== 'Object') {\n return false\n }\n\n return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype\n}\n", "import { isPlainObject } from './isPlainObject.js'\n\nexport function mergeDeep(target: Record, source: Record): Record {\n const output = { ...target }\n\n if (isPlainObject(target) && isPlainObject(source)) {\n Object.keys(source).forEach(key => {\n if (isPlainObject(source[key]) && isPlainObject(target[key])) {\n output[key] = mergeDeep(target[key], source[key])\n } else {\n output[key] = source[key]\n }\n })\n }\n\n return output\n}\n", "import type { Plugin } from '@tiptap/pm/state'\n\nimport type { Editor } from './Editor.js'\nimport { getExtensionField } from './helpers/getExtensionField.js'\nimport type { ExtensionConfig, MarkConfig, NodeConfig } from './index.js'\nimport type { InputRule } from './InputRule.js'\nimport type { Mark } from './Mark.js'\nimport type { Node } from './Node.js'\nimport type { PasteRule } from './PasteRule.js'\nimport type {\n AnyConfig,\n DispatchTransactionProps,\n EditorEvents,\n Extensions,\n GlobalAttributes,\n JSONContent,\n KeyboardShortcutCommand,\n MarkdownParseHelpers,\n MarkdownParseResult,\n MarkdownRendererHelpers,\n MarkdownToken,\n MarkdownTokenizer,\n ParentConfig,\n RawCommands,\n RenderContext,\n} from './types.js'\nimport { callOrReturn } from './utilities/callOrReturn.js'\nimport { mergeDeep } from './utilities/mergeDeep.js'\n\nexport interface ExtendableConfig<\n Options = any,\n Storage = any,\n Config extends\n | ExtensionConfig\n | NodeConfig\n | MarkConfig\n | ExtendableConfig = ExtendableConfig,\n PMType = any,\n> {\n /**\n * The extension name - this must be unique.\n * It will be used to identify the extension.\n *\n * @example 'myExtension'\n */\n name: string\n\n /**\n * The priority of your extension. The higher, the earlier it will be called\n * and will take precedence over other extensions with a lower priority.\n * @default 100\n * @example 101\n */\n priority?: number\n\n /**\n * This method will add options to this extension\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#settings\n * @example\n * addOptions() {\n * return {\n * myOption: 'foo',\n * myOtherOption: 10,\n * }\n */\n addOptions?: (this: { name: string; parent: ParentConfig['addOptions'] }) => Options\n\n /**\n * The default storage this extension can save data to.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#storage\n * @example\n * defaultStorage: {\n * prefetchedUsers: [],\n * loading: false,\n * }\n */\n addStorage?: (this: { name: string; options: Options; parent: ParentConfig['addStorage'] }) => Storage\n\n /**\n * This function adds globalAttributes to specific nodes.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#global-attributes\n * @example\n * addGlobalAttributes() {\n * return [\n * {\n // Extend the following extensions\n * types: [\n * 'heading',\n * 'paragraph',\n * ],\n * // … with those attributes\n * attributes: {\n * textAlign: {\n * default: 'left',\n * renderHTML: attributes => ({\n * style: `text-align: ${attributes.textAlign}`,\n * }),\n * parseHTML: element => element.style.textAlign || 'left',\n * },\n * },\n * },\n * ]\n * }\n */\n addGlobalAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n extensions: (Node | Mark)[]\n parent: ParentConfig['addGlobalAttributes']\n }) => GlobalAttributes\n\n /**\n * This function adds commands to the editor\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#commands\n * @example\n * addCommands() {\n * return {\n * myCommand: () => ({ chain }) => chain().setMark('type', 'foo').run(),\n * }\n * }\n */\n addCommands?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['addCommands']\n }) => Partial\n\n /**\n * This function registers keyboard shortcuts.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#keyboard-shortcuts\n * @example\n * addKeyboardShortcuts() {\n * return {\n * 'Mod-l': () => this.editor.commands.toggleBulletList(),\n * }\n * },\n */\n addKeyboardShortcuts?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['addKeyboardShortcuts']\n }) => {\n [key: string]: KeyboardShortcutCommand\n }\n\n /**\n * This function adds input rules to the editor.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#input-rules\n * @example\n * addInputRules() {\n * return [\n * markInputRule({\n * find: inputRegex,\n * type: this.type,\n * }),\n * ]\n * },\n */\n addInputRules?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['addInputRules']\n }) => InputRule[]\n\n /**\n * This function adds paste rules to the editor.\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#paste-rules\n * @example\n * addPasteRules() {\n * return [\n * markPasteRule({\n * find: pasteRegex,\n * type: this.type,\n * }),\n * ]\n * },\n */\n addPasteRules?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['addPasteRules']\n }) => PasteRule[]\n\n /**\n * This function adds Prosemirror plugins to the editor\n * @see https://tiptap.dev/docs/editor/guide/custom-extensions#prosemirror-plugins\n * @example\n * addProseMirrorPlugins() {\n * return [\n * customPlugin(),\n * ]\n * }\n */\n addProseMirrorPlugins?: (this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['addProseMirrorPlugins']\n }) => Plugin[]\n\n /**\n * This function adds additional extensions to the editor. This is useful for\n * building extension kits.\n * @example\n * addExtensions() {\n * return [\n * BulletList,\n * OrderedList,\n * ListItem\n * ]\n * }\n */\n addExtensions?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig['addExtensions']\n }) => Extensions\n\n /**\n * The markdown token name\n *\n * This is the name of the token that this extension uses to parse and render markdown and comes from the Marked Lexer.\n *\n * @see https://github.com/markedjs/marked/blob/master/src/Tokens.ts\n *\n */\n markdownTokenName?: string\n\n /**\n * The parse function used by the markdown parser to convert markdown tokens to ProseMirror nodes.\n */\n parseMarkdown?: (token: MarkdownToken, helpers: MarkdownParseHelpers) => MarkdownParseResult\n\n /**\n * The serializer function used by the markdown serializer to convert ProseMirror nodes to markdown tokens.\n */\n renderMarkdown?: (node: JSONContent, helpers: MarkdownRendererHelpers, ctx: RenderContext) => string\n\n /**\n * The markdown tokenizer responsible for turning a markdown string into tokens\n *\n * Custom tokenizers are only needed when you want to parse non-standard markdown token.\n */\n markdownTokenizer?: MarkdownTokenizer\n\n /**\n * Optional markdown options for indentation\n */\n markdownOptions?: {\n /**\n * Defines if this markdown element should indent it's child elements\n */\n indentsContent?: boolean\n }\n\n /**\n * This function extends the schema of the node.\n * @example\n * extendNodeSchema() {\n * return {\n * group: 'inline',\n * selectable: false,\n * }\n * }\n */\n extendNodeSchema?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig['extendNodeSchema']\n },\n extension: Node,\n ) => Record)\n | null\n\n /**\n * This function extends the schema of the mark.\n * @example\n * extendMarkSchema() {\n * return {\n * group: 'inline',\n * selectable: false,\n * }\n * }\n */\n extendMarkSchema?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig['extendMarkSchema']\n },\n extension: Mark,\n ) => Record)\n | null\n\n /**\n * The editor is not ready yet.\n */\n onBeforeCreate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onBeforeCreate']\n },\n event: EditorEvents['beforeCreate'],\n ) => void)\n | null\n\n /**\n * The editor is ready.\n */\n onCreate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onCreate']\n },\n event: EditorEvents['create'],\n ) => void)\n | null\n\n /**\n * The content has changed.\n */\n onUpdate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onUpdate']\n },\n event: EditorEvents['update'],\n ) => void)\n | null\n\n /**\n * The selection has changed.\n */\n onSelectionUpdate?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onSelectionUpdate']\n },\n event: EditorEvents['selectionUpdate'],\n ) => void)\n | null\n\n /**\n * The editor state has changed.\n */\n onTransaction?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onTransaction']\n },\n event: EditorEvents['transaction'],\n ) => void)\n | null\n\n /**\n * The editor is focused.\n */\n onFocus?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onFocus']\n },\n event: EditorEvents['focus'],\n ) => void)\n | null\n\n /**\n * The editor isn’t focused anymore.\n */\n onBlur?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onBlur']\n },\n event: EditorEvents['blur'],\n ) => void)\n | null\n\n /**\n * The editor is destroyed.\n */\n onDestroy?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['onDestroy']\n },\n event: EditorEvents['destroy'],\n ) => void)\n | null\n\n /**\n * This hook allows you to intercept and modify transactions before they are dispatched.\n *\n * Example\n * ```ts\n * dispatchTransaction({ transaction, next }) {\n * console.log('Dispatching transaction:', transaction)\n * next(transaction)\n * }\n * ```\n *\n * @param props - The dispatch transaction props\n */\n dispatchTransaction?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: PMType\n parent: ParentConfig['dispatchTransaction']\n },\n props: DispatchTransactionProps,\n ) => void)\n | null\n}\n\nexport class Extendable<\n Options = any,\n Storage = any,\n Config = ExtensionConfig | NodeConfig | MarkConfig,\n> {\n type = 'extendable'\n parent: Extendable | null = null\n\n child: Extendable | null = null\n\n name = ''\n\n config: Config = {\n name: this.name,\n } as Config\n\n constructor(config: Partial = {}) {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.name = (this.config as any).name\n }\n\n get options(): Options {\n return {\n ...(callOrReturn(\n getExtensionField(this as any, 'addOptions', {\n name: this.name,\n }),\n ) || {}),\n }\n }\n\n get storage(): Readonly {\n return {\n ...(callOrReturn(\n getExtensionField(this as any, 'addStorage', {\n name: this.name,\n options: this.options,\n }),\n ) || {}),\n }\n }\n\n configure(options: Partial = {}) {\n const extension = this.extend({\n ...this.config,\n addOptions: () => {\n return mergeDeep(this.options as Record, options) as Options\n },\n })\n\n extension.name = this.name\n extension.parent = this.parent\n\n return extension\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig =\n | ExtensionConfig\n | NodeConfig\n | MarkConfig,\n >(extendedConfig: Partial = {}): Extendable {\n const extension = new (this.constructor as any)({ ...this.config, ...extendedConfig })\n\n extension.parent = this\n this.child = extension\n extension.name = 'name' in extendedConfig ? extendedConfig.name : extension.parent.name\n\n return extension\n }\n}\n", "import type { DOMOutputSpec, Mark as ProseMirrorMark, MarkSpec, MarkType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, MarkViewRenderer, ParentConfig } from './types.js'\n\nexport interface MarkConfig\n extends ExtendableConfig, MarkType> {\n /**\n * Mark View\n */\n addMarkView?:\n | ((this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: MarkType\n parent: ParentConfig>['addMarkView']\n }) => MarkViewRenderer)\n | null\n\n /**\n * Keep mark after split node\n */\n keepOnSplit?: boolean | (() => boolean)\n\n /**\n * Inclusive\n */\n inclusive?:\n | MarkSpec['inclusive']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['inclusive']\n editor?: Editor\n }) => MarkSpec['inclusive'])\n\n /**\n * Excludes\n */\n excludes?:\n | MarkSpec['excludes']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['excludes']\n editor?: Editor\n }) => MarkSpec['excludes'])\n\n /**\n * Marks this Mark as exitable\n */\n exitable?: boolean | (() => boolean)\n\n /**\n * Group\n */\n group?:\n | MarkSpec['group']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['group']\n editor?: Editor\n }) => MarkSpec['group'])\n\n /**\n * Spanning\n */\n spanning?:\n | MarkSpec['spanning']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['spanning']\n editor?: Editor\n }) => MarkSpec['spanning'])\n\n /**\n * Code\n */\n code?:\n | boolean\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['code']\n editor?: Editor\n }) => boolean)\n\n /**\n * Parse HTML\n */\n parseHTML?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['parseHTML']\n editor?: Editor\n }) => MarkSpec['parseDOM']\n\n /**\n * Render HTML\n */\n renderHTML?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['renderHTML']\n editor?: Editor\n },\n props: {\n mark: ProseMirrorMark\n HTMLAttributes: Record\n },\n ) => DOMOutputSpec)\n | null\n\n /**\n * Attributes\n */\n addAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['addAttributes']\n editor?: Editor\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n }) => Attributes | {}\n}\n\n/**\n * The Mark class is used to create custom mark extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Mark extends Extendable> {\n type = 'mark'\n\n /**\n * Create a new Mark instance\n * @param config - Mark configuration object or a function that returns a configuration object\n */\n static create(config: Partial> | (() => Partial>) = {}) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Mark(resolvedConfig)\n }\n\n static handleExit({ editor, mark }: { editor: Editor; mark: Mark }) {\n const { tr } = editor.state\n const currentPos = editor.state.selection.$from\n const isAtEnd = currentPos.pos === currentPos.end()\n\n if (isAtEnd) {\n const currentMarks = currentPos.marks()\n const isInMark = !!currentMarks.find(m => m?.type.name === mark.name)\n\n if (!isInMark) {\n return false\n }\n\n const removeMark = currentMarks.find(m => m?.type.name === mark.name)\n\n if (removeMark) {\n tr.removeStoredMark(removeMark)\n }\n tr.insertText(' ', currentPos.pos)\n\n editor.view.dispatch(tr)\n\n return true\n }\n\n return false\n }\n\n configure(options?: Partial) {\n return super.configure(options) as Mark\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig extends MarkConfig = MarkConfig,\n >(\n extendedConfig?:\n | (() => Partial)\n | (Partial &\n ThisType<{\n name: string\n options: ExtendedOptions\n storage: ExtendedStorage\n editor: Editor\n type: MarkType\n }>),\n ): Mark {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Mark\n }\n}\n", "import type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Fragment } from '@tiptap/pm/model'\nimport type { EditorState } from '@tiptap/pm/state'\nimport { Plugin } from '@tiptap/pm/state'\n\nimport { CommandManager } from './CommandManager.js'\nimport type { Editor } from './Editor.js'\nimport { createChainableState } from './helpers/createChainableState.js'\nimport { getHTMLFromFragment } from './helpers/getHTMLFromFragment.js'\nimport type { CanCommands, ChainedCommands, ExtendedRegExpMatchArray, Range, SingleCommands } from './types.js'\nimport { isNumber } from './utilities/isNumber.js'\nimport { isRegExp } from './utilities/isRegExp.js'\n\nexport type PasteRuleMatch = {\n index: number\n text: string\n replaceWith?: string\n match?: RegExpMatchArray\n data?: Record\n}\n\nexport type PasteRuleFinder =\n | RegExp\n | ((text: string, event?: ClipboardEvent | null) => PasteRuleMatch[] | null | undefined)\n\n/**\n * Paste rules are used to react to pasted content.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport class PasteRule {\n find: PasteRuleFinder\n\n handler: (props: {\n state: EditorState\n range: Range\n match: ExtendedRegExpMatchArray\n commands: SingleCommands\n chain: () => ChainedCommands\n can: () => CanCommands\n pasteEvent: ClipboardEvent | null\n dropEvent: DragEvent | null\n }) => void | null\n\n constructor(config: {\n find: PasteRuleFinder\n handler: (props: {\n can: () => CanCommands\n chain: () => ChainedCommands\n commands: SingleCommands\n dropEvent: DragEvent | null\n match: ExtendedRegExpMatchArray\n pasteEvent: ClipboardEvent | null\n range: Range\n state: EditorState\n }) => void | null\n }) {\n this.find = config.find\n this.handler = config.handler\n }\n}\n\nconst pasteRuleMatcherHandler = (\n text: string,\n find: PasteRuleFinder,\n event?: ClipboardEvent | null,\n): ExtendedRegExpMatchArray[] => {\n if (isRegExp(find)) {\n return [...text.matchAll(find)]\n }\n\n const matches = find(text, event)\n\n if (!matches) {\n return []\n }\n\n return matches.map(pasteRuleMatch => {\n const result: ExtendedRegExpMatchArray = [pasteRuleMatch.text]\n\n result.index = pasteRuleMatch.index\n result.input = text\n result.data = pasteRuleMatch.data\n\n if (pasteRuleMatch.replaceWith) {\n if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {\n console.warn('[tiptap warn]: \"pasteRuleMatch.replaceWith\" must be part of \"pasteRuleMatch.text\".')\n }\n\n result.push(pasteRuleMatch.replaceWith)\n }\n\n return result\n })\n}\n\nfunction run(config: {\n editor: Editor\n state: EditorState\n from: number\n to: number\n rule: PasteRule\n pasteEvent: ClipboardEvent | null\n dropEvent: DragEvent | null\n}): boolean {\n const { editor, state, from, to, rule, pasteEvent, dropEvent } = config\n\n const { commands, chain, can } = new CommandManager({\n editor,\n state,\n })\n\n const handlers: (void | null)[] = []\n\n state.doc.nodesBetween(from, to, (node, pos) => {\n // Skip code blocks and non-textual nodes.\n // Be defensive: `node` may be a Fragment without a `type`. Only text,\n // inline, or textblock nodes are processed by paste rules.\n if (node.type?.spec?.code || !(node.isText || node.isTextblock || node.isInline)) {\n return\n }\n\n // For textblock and inline/text nodes, compute the range relative to the node.\n // Prefer `node.nodeSize` when available (some Node shapes expose this),\n // otherwise fall back to `node.content?.size`. Default to 0 if neither exists.\n const contentSize = node.content?.size ?? node.nodeSize ?? 0\n const resolvedFrom = Math.max(from, pos)\n const resolvedTo = Math.min(to, pos + contentSize)\n\n // If the resolved range is empty or invalid for this node, skip it. This\n // avoids calling `textBetween` with start > end which can cause internal\n // Fragment/Node traversal to access undefined `nodeSize` values.\n if (resolvedFrom >= resolvedTo) {\n return\n }\n\n const textToMatch = node.isText\n ? node.text || ''\n : node.textBetween(resolvedFrom - pos, resolvedTo - pos, undefined, '\\ufffc')\n\n const matches = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent)\n\n matches.forEach(match => {\n if (match.index === undefined) {\n return\n }\n\n const start = resolvedFrom + match.index + 1\n const end = start + match[0].length\n const range = {\n from: state.tr.mapping.map(start),\n to: state.tr.mapping.map(end),\n }\n\n const handler = rule.handler({\n state,\n range,\n match,\n commands,\n chain,\n can,\n pasteEvent,\n dropEvent,\n })\n\n handlers.push(handler)\n })\n })\n\n const success = handlers.every(handler => handler !== null)\n\n return success\n}\n\n// When dragging across editors, must get another editor instance to delete selection content.\nlet tiptapDragFromOtherEditor: Editor | null = null\n\nconst createClipboardPasteEvent = (text: string) => {\n const event = new ClipboardEvent('paste', {\n clipboardData: new DataTransfer(),\n })\n\n event.clipboardData?.setData('text/html', text)\n\n return event\n}\n\n/**\n * Create an paste rules plugin. When enabled, it will cause pasted\n * text that matches any of the given rules to trigger the rule’s\n * action.\n */\nexport function pasteRulesPlugin(props: { editor: Editor; rules: PasteRule[] }): Plugin[] {\n const { editor, rules } = props\n let dragSourceElement: Element | null = null\n let isPastedFromProseMirror = false\n let isDroppedFromProseMirror = false\n let pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n let dropEvent: DragEvent | null\n\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n } catch {\n dropEvent = null\n }\n\n const processEvent = ({\n state,\n from,\n to,\n rule,\n pasteEvt,\n }: {\n state: EditorState\n from: number\n to: { b: number }\n rule: PasteRule\n pasteEvt: ClipboardEvent | null\n }) => {\n const tr = state.tr\n const chainableState = createChainableState({\n state,\n transaction: tr,\n })\n\n const handler = run({\n editor,\n state: chainableState,\n from: Math.max(from - 1, 0),\n to: to.b - 1,\n rule,\n pasteEvent: pasteEvt,\n dropEvent,\n })\n\n if (!handler || !tr.steps.length) {\n return\n }\n\n try {\n dropEvent = typeof DragEvent !== 'undefined' ? new DragEvent('drop') : null\n } catch {\n dropEvent = null\n }\n pasteEvent = typeof ClipboardEvent !== 'undefined' ? new ClipboardEvent('paste') : null\n\n return tr\n }\n\n const plugins = rules.map(rule => {\n return new Plugin({\n // we register a global drag handler to track the current drag source element\n view(view) {\n const handleDragstart = (event: DragEvent) => {\n dragSourceElement = view.dom.parentElement?.contains(event.target as Element) ? view.dom.parentElement : null\n\n if (dragSourceElement) {\n tiptapDragFromOtherEditor = editor\n }\n }\n\n const handleDragend = () => {\n if (tiptapDragFromOtherEditor) {\n tiptapDragFromOtherEditor = null\n }\n }\n\n window.addEventListener('dragstart', handleDragstart)\n window.addEventListener('dragend', handleDragend)\n\n return {\n destroy() {\n window.removeEventListener('dragstart', handleDragstart)\n window.removeEventListener('dragend', handleDragend)\n },\n }\n },\n\n props: {\n handleDOMEvents: {\n drop: (view, event: Event) => {\n isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement\n dropEvent = event as DragEvent\n\n if (!isDroppedFromProseMirror) {\n const dragFromOtherEditor = tiptapDragFromOtherEditor\n\n if (dragFromOtherEditor?.isEditable) {\n // setTimeout to avoid the wrong content after drop, timeout arg can't be empty or 0\n setTimeout(() => {\n const selection = dragFromOtherEditor.state.selection\n\n if (selection) {\n dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to })\n }\n }, 10)\n }\n }\n return false\n },\n\n paste: (_view, event: Event) => {\n const html = (event as ClipboardEvent).clipboardData?.getData('text/html')\n\n pasteEvent = event as ClipboardEvent\n\n isPastedFromProseMirror = !!html?.includes('data-pm-slice')\n\n return false\n },\n },\n },\n\n appendTransaction: (transactions, oldState, state) => {\n const transaction = transactions[0]\n const isPaste = transaction.getMeta('uiEvent') === 'paste' && !isPastedFromProseMirror\n const isDrop = transaction.getMeta('uiEvent') === 'drop' && !isDroppedFromProseMirror\n\n // if PasteRule is triggered by insertContent()\n const simulatedPasteMeta = transaction.getMeta('applyPasteRules') as\n | undefined\n | { from: number; text: string | ProseMirrorNode | Fragment }\n const isSimulatedPaste = !!simulatedPasteMeta\n\n if (!isPaste && !isDrop && !isSimulatedPaste) {\n return\n }\n\n // Handle simulated paste\n if (isSimulatedPaste) {\n let { text } = simulatedPasteMeta\n\n if (typeof text === 'string') {\n text = text as string\n } else {\n text = getHTMLFromFragment(Fragment.from(text), state.schema)\n }\n\n const { from } = simulatedPasteMeta\n const to = from + text.length\n\n const pasteEvt = createClipboardPasteEvent(text)\n\n return processEvent({\n rule,\n state,\n from,\n to: { b: to },\n pasteEvt,\n })\n }\n\n // handle actual paste/drop\n const from = oldState.doc.content.findDiffStart(state.doc.content)\n const to = oldState.doc.content.findDiffEnd(state.doc.content)\n\n // stop if there is no changed range\n if (!isNumber(from) || !to || from === to.b) {\n return\n }\n\n return processEvent({\n rule,\n state,\n from,\n to,\n pasteEvt: pasteEvent,\n })\n },\n })\n })\n\n return plugins\n}\n", "export function isNumber(value: any): value is number {\n return typeof value === 'number'\n}\n", "export { ClipboardTextSerializer } from './clipboardTextSerializer.js'\nexport { Commands } from './commands.js'\nexport { Delete } from './delete.js'\nexport { Drop } from './drop.js'\nexport { Editable } from './editable.js'\nexport { FocusEvents, focusEventsPluginKey } from './focusEvents.js'\nexport { Keymap } from './keymap.js'\nexport { Paste } from './paste.js'\nexport { Tabindex } from './tabindex.js'\nexport { TextDirection } from './textDirection.js'\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\nimport { getTextBetween } from '../helpers/getTextBetween.js'\nimport { getTextSerializersFromSchema } from '../helpers/getTextSerializersFromSchema.js'\n\nexport type ClipboardTextSerializerOptions = {\n blockSeparator?: string\n}\n\nexport const ClipboardTextSerializer = Extension.create({\n name: 'clipboardTextSerializer',\n\n addOptions() {\n return {\n blockSeparator: undefined,\n }\n },\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('clipboardTextSerializer'),\n props: {\n clipboardTextSerializer: () => {\n const { editor } = this\n const { state, schema } = editor\n const { doc, selection } = state\n const { ranges } = selection\n const from = Math.min(...ranges.map(range => range.$from.pos))\n const to = Math.max(...ranges.map(range => range.$to.pos))\n const textSerializers = getTextSerializersFromSchema(schema)\n const range = { from, to }\n\n return getTextBetween(doc, range, {\n ...(this.options.blockSeparator !== undefined ? { blockSeparator: this.options.blockSeparator } : {}),\n textSerializers,\n })\n },\n },\n }),\n ]\n },\n})\n", "import type { Editor } from './Editor.js'\nimport { type ExtendableConfig, Extendable } from './Extendable.js'\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ExtensionConfig\n extends ExtendableConfig, null> {}\n\n/**\n * The Extension class is the base class for all extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Extension extends Extendable<\n Options,\n Storage,\n ExtensionConfig\n> {\n type = 'extension'\n\n /**\n * Create a new Extension instance\n * @param config - Extension configuration object or a function that returns a configuration object\n */\n static create(\n config: Partial> | (() => Partial>) = {},\n ) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Extension(resolvedConfig)\n }\n\n configure(options?: Partial) {\n return super.configure(options) as Extension\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig = ExtensionConfig,\n >(\n extendedConfig?:\n | (() => Partial)\n | (Partial &\n ThisType<{\n name: string\n options: ExtendedOptions\n storage: ExtendedStorage\n editor: Editor\n type: null\n }>),\n ): Extension {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Extension\n }\n}\n", "import * as commands from '../commands/index.js'\nimport { Extension } from '../Extension.js'\n\nexport * from '../commands/index.js'\n\nexport const Commands = Extension.create({\n name: 'commands',\n\n addCommands() {\n return {\n ...commands,\n }\n },\n})\n", "import { RemoveMarkStep } from '@tiptap/pm/transform'\n\nimport { Extension } from '../Extension.js'\nimport { combineTransactionSteps, getChangedRanges } from '../helpers/index.js'\n\n/**\n * This extension allows you to be notified when the user deletes content you are interested in.\n */\nexport const Delete = Extension.create({\n name: 'delete',\n\n onUpdate({ transaction, appendedTransactions }) {\n const callback = () => {\n if (\n this.editor.options.coreExtensionOptions?.delete?.filterTransaction?.(transaction) ??\n transaction.getMeta('y-sync$')\n ) {\n return\n }\n const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions])\n const changes = getChangedRanges(nextTransaction)\n\n changes.forEach(change => {\n if (\n nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter &&\n nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore\n ) {\n nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from) => {\n const to = from + node.nodeSize - 2\n const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to\n\n this.editor.emit('delete', {\n type: 'node',\n node,\n from,\n to,\n newFrom: nextTransaction.mapping.map(from),\n newTo: nextTransaction.mapping.map(to),\n deletedRange: change.oldRange,\n newRange: change.newRange,\n partial: !isFullyWithinRange,\n editor: this.editor,\n transaction,\n combinedTransform: nextTransaction,\n })\n })\n }\n })\n\n const mapping = nextTransaction.mapping\n nextTransaction.steps.forEach((step, index) => {\n if (step instanceof RemoveMarkStep) {\n const newStart = mapping.slice(index).map(step.from, -1)\n const newEnd = mapping.slice(index).map(step.to)\n const oldStart = mapping.invert().map(newStart, -1)\n const oldEnd = mapping.invert().map(newEnd)\n\n const foundBeforeMark = nextTransaction.doc.nodeAt(newStart - 1)?.marks.some(mark => mark.eq(step.mark))\n const foundAfterMark = nextTransaction.doc.nodeAt(newEnd)?.marks.some(mark => mark.eq(step.mark))\n\n this.editor.emit('delete', {\n type: 'mark',\n mark: step.mark,\n from: step.from,\n to: step.to,\n deletedRange: {\n from: oldStart,\n to: oldEnd,\n },\n newRange: {\n from: newStart,\n to: newEnd,\n },\n partial: Boolean(foundAfterMark || foundBeforeMark),\n editor: this.editor,\n transaction,\n combinedTransform: nextTransaction,\n })\n }\n })\n }\n\n if (this.editor.options.coreExtensionOptions?.delete?.async ?? true) {\n setTimeout(callback, 0)\n } else {\n callback()\n }\n },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Drop = Extension.create({\n name: 'drop',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapDrop'),\n\n props: {\n handleDrop: (_, e, slice, moved) => {\n this.editor.emit('drop', {\n editor: this.editor,\n event: e,\n slice,\n moved,\n })\n },\n },\n }),\n ]\n },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Editable = Extension.create({\n name: 'editable',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('editable'),\n props: {\n editable: () => this.editor.options.editable,\n },\n }),\n ]\n },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const focusEventsPluginKey = new PluginKey('focusEvents')\n\nexport const FocusEvents = Extension.create({\n name: 'focusEvents',\n\n addProseMirrorPlugins() {\n const { editor } = this\n\n return [\n new Plugin({\n key: focusEventsPluginKey,\n props: {\n handleDOMEvents: {\n focus: (view, event: Event) => {\n editor.isFocused = true\n\n const transaction = editor.state.tr.setMeta('focus', { event }).setMeta('addToHistory', false)\n\n view.dispatch(transaction)\n\n return false\n },\n blur: (view, event: Event) => {\n editor.isFocused = false\n\n const transaction = editor.state.tr.setMeta('blur', { event }).setMeta('addToHistory', false)\n\n view.dispatch(transaction)\n\n return false\n },\n },\n },\n }),\n ]\n },\n})\n", "import { Plugin, PluginKey, Selection } from '@tiptap/pm/state'\n\nimport { CommandManager } from '../CommandManager.js'\nimport { Extension } from '../Extension.js'\nimport { createChainableState } from '../helpers/createChainableState.js'\nimport { isNodeEmpty } from '../helpers/isNodeEmpty.js'\nimport { isiOS } from '../utilities/isiOS.js'\nimport { isMacOS } from '../utilities/isMacOS.js'\n\nexport const Keymap = Extension.create({\n name: 'keymap',\n\n addKeyboardShortcuts() {\n const handleBackspace = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.undoInputRule(),\n\n // maybe convert first text block node to default node\n () =>\n commands.command(({ tr }) => {\n const { selection, doc } = tr\n const { empty, $anchor } = selection\n const { pos, parent } = $anchor\n const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor\n const parentIsIsolating = $parentPos.parent.type.spec.isolating\n\n const parentPos = $anchor.pos - $anchor.parentOffset\n\n const isAtStart =\n parentIsIsolating && $parentPos.parent.childCount === 1\n ? parentPos === $anchor.pos\n : Selection.atStart(doc).from === pos\n\n if (\n !empty ||\n !parent.type.isTextblock ||\n parent.textContent.length ||\n !isAtStart ||\n (isAtStart && $anchor.parent.type.name === 'paragraph') // prevent clearNodes when no nodes to clear, otherwise history stack is appended\n ) {\n return false\n }\n\n return commands.clearNodes()\n }),\n\n () => commands.deleteSelection(),\n () => commands.joinBackward(),\n () => commands.selectNodeBackward(),\n ])\n\n const handleDelete = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.deleteSelection(),\n () => commands.deleteCurrentNode(),\n () => commands.joinForward(),\n () => commands.selectNodeForward(),\n ])\n\n const handleEnter = () =>\n this.editor.commands.first(({ commands }) => [\n () => commands.newlineInCode(),\n () => commands.createParagraphNear(),\n () => commands.liftEmptyBlock(),\n () => commands.splitBlock(),\n ])\n\n const baseKeymap = {\n Enter: handleEnter,\n 'Mod-Enter': () => this.editor.commands.exitCode(),\n Backspace: handleBackspace,\n 'Mod-Backspace': handleBackspace,\n 'Shift-Backspace': handleBackspace,\n Delete: handleDelete,\n 'Mod-Delete': handleDelete,\n 'Mod-a': () => this.editor.commands.selectAll(),\n }\n\n const pcKeymap = {\n ...baseKeymap,\n }\n\n const macKeymap = {\n ...baseKeymap,\n 'Ctrl-h': handleBackspace,\n 'Alt-Backspace': handleBackspace,\n 'Ctrl-d': handleDelete,\n 'Ctrl-Alt-Backspace': handleDelete,\n 'Alt-Delete': handleDelete,\n 'Alt-d': handleDelete,\n 'Ctrl-a': () => this.editor.commands.selectTextblockStart(),\n 'Ctrl-e': () => this.editor.commands.selectTextblockEnd(),\n }\n\n if (isiOS() || isMacOS()) {\n return macKeymap\n }\n\n return pcKeymap\n },\n\n addProseMirrorPlugins() {\n return [\n // With this plugin we check if the whole document was selected and deleted.\n // In this case we will additionally call `clearNodes()` to convert e.g. a heading\n // to a paragraph if necessary.\n // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well\n // with many other commands.\n new Plugin({\n key: new PluginKey('clearDocument'),\n appendTransaction: (transactions, oldState, newState) => {\n if (transactions.some(tr => tr.getMeta('composition'))) {\n return\n }\n\n const docChanges = transactions.some(transaction => transaction.docChanged) && !oldState.doc.eq(newState.doc)\n\n const ignoreTr = transactions.some(transaction => transaction.getMeta('preventClearDocument'))\n\n if (!docChanges || ignoreTr) {\n return\n }\n\n const { empty, from, to } = oldState.selection\n const allFrom = Selection.atStart(oldState.doc).from\n const allEnd = Selection.atEnd(oldState.doc).to\n const allWasSelected = from === allFrom && to === allEnd\n\n if (empty || !allWasSelected) {\n return\n }\n\n const isEmpty = isNodeEmpty(newState.doc)\n\n if (!isEmpty) {\n return\n }\n\n const tr = newState.tr\n const state = createChainableState({\n state: newState,\n transaction: tr,\n })\n const { commands } = new CommandManager({\n editor: this.editor,\n state,\n })\n\n commands.clearNodes()\n\n if (!tr.steps.length) {\n return\n }\n\n return tr\n },\n }),\n ]\n },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Paste = Extension.create({\n name: 'paste',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tiptapPaste'),\n\n props: {\n handlePaste: (_view, e, slice) => {\n this.editor.emit('paste', {\n editor: this.editor,\n event: e,\n slice,\n })\n },\n },\n }),\n ]\n },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\n\nexport const Tabindex = Extension.create({\n name: 'tabindex',\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('tabindex'),\n props: {\n attributes: (): { [name: string]: string } => (this.editor.isEditable ? { tabindex: '0' } : {}),\n },\n }),\n ]\n },\n})\n", "import { Plugin, PluginKey } from '@tiptap/pm/state'\n\nimport { Extension } from '../Extension.js'\nimport { splitExtensions } from '../helpers/splitExtensions.js'\n\nexport interface TextDirectionOptions {\n direction: 'ltr' | 'rtl' | 'auto' | undefined\n}\n\n/**\n * The TextDirection extension adds support for setting text direction (LTR/RTL/auto)\n * on all nodes in the editor.\n *\n * This extension adds a global `dir` attribute to all node types, which can be used\n * to control bidirectional text rendering. The direction can be set globally via\n * editor options or per-node using commands.\n */\nexport const TextDirection = Extension.create({\n name: 'textDirection',\n\n addOptions() {\n return {\n direction: undefined,\n }\n },\n\n addGlobalAttributes() {\n // Only add the dir attribute to nodes if text direction is configured\n // This prevents null/undefined values from appearing in JSON exports\n if (!this.options.direction) {\n return []\n }\n\n const { nodeExtensions } = splitExtensions(this.extensions)\n\n return [\n {\n types: nodeExtensions.filter(extension => extension.name !== 'text').map(extension => extension.name),\n attributes: {\n dir: {\n default: this.options.direction,\n parseHTML: element => {\n const dir = element.getAttribute('dir')\n\n if (dir && (dir === 'ltr' || dir === 'rtl' || dir === 'auto')) {\n return dir\n }\n\n return this.options.direction\n },\n renderHTML: attributes => {\n if (!attributes.dir) {\n return {}\n }\n\n return {\n dir: attributes.dir,\n }\n },\n },\n },\n },\n ]\n },\n\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('textDirection'),\n props: {\n attributes: (): { [name: string]: string } => {\n const direction = this.options.direction\n\n if (!direction) {\n return {}\n }\n\n return {\n dir: direction,\n }\n },\n },\n }),\n ]\n },\n})\n", "import type { Fragment, Node, ResolvedPos } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { Content, Range } from './types.js'\n\nexport class NodePos {\n private resolvedPos: ResolvedPos\n\n private isBlock: boolean\n\n private editor: Editor\n\n private get name(): string {\n return this.node.type.name\n }\n\n constructor(pos: ResolvedPos, editor: Editor, isBlock = false, node: Node | null = null) {\n this.isBlock = isBlock\n this.resolvedPos = pos\n this.editor = editor\n this.currentNode = node\n }\n\n private currentNode: Node | null = null\n\n get node(): Node {\n return this.currentNode || this.resolvedPos.node()\n }\n\n get element(): HTMLElement {\n return this.editor.view.domAtPos(this.pos).node as HTMLElement\n }\n\n public actualDepth: number | null = null\n\n get depth(): number {\n return this.actualDepth ?? this.resolvedPos.depth\n }\n\n get pos(): number {\n return this.resolvedPos.pos\n }\n\n get content(): Fragment {\n return this.node.content\n }\n\n set content(content: Content) {\n let from = this.from\n let to = this.to\n\n if (this.isBlock) {\n if (this.content.size === 0) {\n console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`)\n return\n }\n\n from = this.from + 1\n to = this.to - 1\n }\n\n this.editor.commands.insertContentAt({ from, to }, content)\n }\n\n get attributes(): { [key: string]: any } {\n return this.node.attrs\n }\n\n get textContent(): string {\n return this.node.textContent\n }\n\n get size(): number {\n return this.node.nodeSize\n }\n\n get from(): number {\n if (this.isBlock) {\n return this.pos\n }\n\n return this.resolvedPos.start(this.resolvedPos.depth)\n }\n\n get range(): Range {\n return {\n from: this.from,\n to: this.to,\n }\n }\n\n get to(): number {\n if (this.isBlock) {\n return this.pos + this.size\n }\n\n return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1)\n }\n\n get parent(): NodePos | null {\n if (this.depth === 0) {\n return null\n }\n\n const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1)\n const $pos = this.resolvedPos.doc.resolve(parentPos)\n\n return new NodePos($pos, this.editor)\n }\n\n get before(): NodePos | null {\n let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2))\n\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.from - 3)\n }\n\n return new NodePos($pos, this.editor)\n }\n\n get after(): NodePos | null {\n let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1))\n\n if ($pos.depth !== this.depth) {\n $pos = this.resolvedPos.doc.resolve(this.to + 3)\n }\n\n return new NodePos($pos, this.editor)\n }\n\n get children(): NodePos[] {\n const children: NodePos[] = []\n\n this.node.content.forEach((node, offset) => {\n const isBlock = node.isBlock && !node.isTextblock\n const isNonTextAtom = node.isAtom && !node.isText\n const isInline = node.isInline\n\n const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1)\n\n // Check if targetPos is within valid document range\n if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) {\n return\n }\n\n const $pos = this.resolvedPos.doc.resolve(targetPos)\n\n // Only apply depth check for non-block, non-inline nodes (i.e., textblocks)\n // Inline nodes should always be included as children since we're iterating\n // over direct children via this.node.content\n if (!isBlock && !isInline && $pos.depth <= this.depth) {\n return\n }\n\n // Pass the node for both block and inline nodes to ensure correct node reference\n const childNodePos = new NodePos($pos, this.editor, isBlock, isBlock || isInline ? node : null)\n\n if (isBlock) {\n childNodePos.actualDepth = this.depth + 1\n }\n\n children.push(childNodePos)\n })\n\n return children\n }\n\n get firstChild(): NodePos | null {\n return this.children[0] || null\n }\n\n get lastChild(): NodePos | null {\n const children = this.children\n\n return children[children.length - 1] || null\n }\n\n closest(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n let node: NodePos | null = null\n let currentNode = this.parent\n\n while (currentNode && !node) {\n if (currentNode.node.type.name === selector) {\n if (Object.keys(attributes).length > 0) {\n const nodeAttributes = currentNode.node.attrs\n const attrKeys = Object.keys(attributes)\n\n for (let index = 0; index < attrKeys.length; index += 1) {\n const key = attrKeys[index]\n\n if (nodeAttributes[key] !== attributes[key]) {\n break\n }\n }\n } else {\n node = currentNode\n }\n }\n\n currentNode = currentNode.parent\n }\n\n return node\n }\n\n querySelector(selector: string, attributes: { [key: string]: any } = {}): NodePos | null {\n return this.querySelectorAll(selector, attributes, true)[0] || null\n }\n\n querySelectorAll(selector: string, attributes: { [key: string]: any } = {}, firstItemOnly = false): NodePos[] {\n let nodes: NodePos[] = []\n\n if (!this.children || this.children.length === 0) {\n return nodes\n }\n const attrKeys = Object.keys(attributes)\n\n /**\n * Finds all children recursively that match the selector and attributes\n * If firstItemOnly is true, it will return the first item found\n */\n this.children.forEach(childPos => {\n // If we already found a node and we only want the first item, we dont need to keep going\n if (firstItemOnly && nodes.length > 0) {\n return\n }\n\n if (childPos.node.type.name === selector) {\n const doesAllAttributesMatch = attrKeys.every(key => attributes[key] === childPos.node.attrs[key])\n\n if (doesAllAttributesMatch) {\n nodes.push(childPos)\n }\n }\n\n // If we already found a node and we only want the first item, we can stop here and skip the recursion\n if (firstItemOnly && nodes.length > 0) {\n return\n }\n\n nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly))\n })\n\n return nodes\n }\n\n setAttribute(attributes: { [key: string]: any }) {\n const { tr } = this.editor.state\n\n tr.setNodeMarkup(this.from, undefined, {\n ...this.node.attrs,\n ...attributes,\n })\n\n this.editor.view.dispatch(tr)\n }\n}\n", "export const style = `.ProseMirror {\n position: relative;\n}\n\n.ProseMirror {\n word-wrap: break-word;\n white-space: pre-wrap;\n white-space: break-spaces;\n -webkit-font-variant-ligatures: none;\n font-variant-ligatures: none;\n font-feature-settings: \"liga\" 0; /* the above doesn't seem to work in Edge */\n}\n\n.ProseMirror [contenteditable=\"false\"] {\n white-space: normal;\n}\n\n.ProseMirror [contenteditable=\"false\"] [contenteditable=\"true\"] {\n white-space: pre-wrap;\n}\n\n.ProseMirror pre {\n white-space: pre-wrap;\n}\n\nimg.ProseMirror-separator {\n display: inline !important;\n border: none !important;\n margin: 0 !important;\n width: 0 !important;\n height: 0 !important;\n}\n\n.ProseMirror-gapcursor {\n display: none;\n pointer-events: none;\n position: absolute;\n margin: 0;\n}\n\n.ProseMirror-gapcursor:after {\n content: \"\";\n display: block;\n position: absolute;\n top: -2px;\n width: 20px;\n border-top: 1px solid black;\n animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n}\n\n@keyframes ProseMirror-cursor-blink {\n to {\n visibility: hidden;\n }\n}\n\n.ProseMirror-hideselection *::selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection *::-moz-selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection * {\n caret-color: transparent;\n}\n\n.ProseMirror-focused .ProseMirror-gapcursor {\n display: block;\n}`\n", "export function createStyleTag(style: string, nonce?: string, suffix?: string): HTMLStyleElement {\n const tiptapStyleTag = (\n document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ''}]`)\n )\n\n if (tiptapStyleTag !== null) {\n return tiptapStyleTag\n }\n\n const styleNode = document.createElement('style')\n\n if (nonce) {\n styleNode.setAttribute('nonce', nonce)\n }\n\n styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ''}`, '')\n styleNode.innerHTML = style\n document.getElementsByTagName('head')[0].appendChild(styleNode)\n\n return styleNode\n}\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a mark when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function markInputRule(config: {\n find: InputRuleFinder\n type: MarkType\n undoable?: boolean\n getAttributes?: Record | ((match: ExtendedRegExpMatchArray) => Record) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const { tr } = state\n const captureGroup = match[match.length - 1]\n const fullMatch = match[0]\n\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/)\n const textStart = range.from + fullMatch.indexOf(captureGroup)\n const textEnd = textStart + captureGroup.length\n\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded as MarkType[]\n\n return excluded.find(type => type === config.type && type !== item.mark.type)\n })\n .filter(item => item.to > textStart)\n\n if (excludedMarks.length) {\n return null\n }\n\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to)\n }\n\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart)\n }\n\n const markEnd = range.from + startSpaces + captureGroup.length\n\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n tr.removeStoredMark(config.type)\n }\n },\n undoable: config.undoable,\n })\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that adds a node when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function nodeInputRule(config: {\n /**\n * The regex to match.\n */\n find: InputRuleFinder\n\n /**\n * The node type to add.\n */\n type: NodeType\n\n /**\n * Whether the input rule should be undoable\n * when the user presses backspace.\n */\n undoable?: boolean\n\n /**\n * A function that returns the attributes for the node\n * can also be an object of attributes\n */\n getAttributes?: Record | ((match: ExtendedRegExpMatchArray) => Record) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n const { tr } = state\n const start = range.from\n let end = range.to\n\n const newNode = config.type.create(attributes)\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n let matchStart = start + offset\n\n if (matchStart > end) {\n matchStart = end\n } else {\n end = matchStart + match[1].length\n }\n\n // insert last typed character\n const lastChar = match[0][match[0].length - 1]\n\n tr.insertText(lastChar, start + match[0].length - 1)\n\n // insert node from input rule\n tr.replaceWith(matchStart, end, newNode)\n } else if (match[0]) {\n const insertionStart = config.type.isInline ? start : start - 1\n\n tr.insert(insertionStart, config.type.create(attributes)).delete(tr.mapping.map(start), tr.mapping.map(end))\n }\n\n tr.scrollIntoView()\n },\n undoable: config.undoable,\n })\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule that changes the type of a textblock when the\n * matched text is typed into it. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textblockTypeInputRule(config: {\n find: InputRuleFinder\n type: NodeType\n undoable?: boolean\n getAttributes?: Record | ((match: ExtendedRegExpMatchArray) => Record) | false | null\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n const $start = state.doc.resolve(range.from)\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n\n if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {\n return null\n }\n\n state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes)\n },\n undoable: config.undoable,\n })\n}\n", "import type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\n\n/**\n * Build an input rule that replaces text when the\n * matched text is typed into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function textInputRule(config: { find: InputRuleFinder; replace: string; undoable?: boolean }) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace\n let start = range.from\n const end = range.to\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n\n insert += match[0].slice(offset + match[1].length)\n start += offset\n\n const cutOff = start - end\n\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert\n start = end\n }\n }\n\n state.tr.insertText(insert, start, end)\n },\n undoable: config.undoable,\n })\n}\n", "import type { Node as ProseMirrorNode, NodeType } from '@tiptap/pm/model'\nimport { canJoin, findWrapping } from '@tiptap/pm/transform'\n\nimport type { Editor } from '../Editor.js'\nimport type { InputRuleFinder } from '../InputRule.js'\nimport { InputRule } from '../InputRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an input rule for automatically wrapping a textblock when a\n * given string is typed. When using a regular expresion you’ll\n * probably want the regexp to start with `^`, so that the pattern can\n * only occur at the start of a textblock.\n *\n * `type` is the type of node to wrap in.\n *\n * By default, if there’s a node with the same type above the newly\n * wrapped node, the rule will try to join those\n * two nodes. You can pass a join predicate, which takes a regular\n * expression match and the node before the wrapped node, and can\n * return a boolean to indicate whether a join should happen.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#input-rules\n */\nexport function wrappingInputRule(config: {\n find: InputRuleFinder\n type: NodeType\n keepMarks?: boolean\n keepAttributes?: boolean\n editor?: Editor\n undoable?: boolean\n getAttributes?: Record | ((match: ExtendedRegExpMatchArray) => Record) | false | null\n joinPredicate?: (match: ExtendedRegExpMatchArray, node: ProseMirrorNode) => boolean\n}) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match, chain }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match) || {}\n const tr = state.tr.delete(range.from, range.to)\n const $start = tr.doc.resolve(range.from)\n const blockRange = $start.blockRange()\n const wrapping = blockRange && findWrapping(blockRange, config.type, attributes)\n\n if (!wrapping) {\n return null\n }\n\n tr.wrap(blockRange, wrapping)\n\n if (config.keepMarks && config.editor) {\n const { selection, storedMarks } = state\n const { splittableMarks } = config.editor.extensionManager\n const marks = storedMarks || (selection.$to.parentOffset && selection.$from.marks())\n\n if (marks) {\n const filteredMarks = marks.filter(mark => splittableMarks.includes(mark.type.name))\n\n tr.ensureMarks(filteredMarks)\n }\n }\n if (config.keepAttributes) {\n /** If the nodeType is `bulletList` or `orderedList` set the `nodeType` as `listItem` */\n const nodeType =\n config.type.name === 'bulletList' || config.type.name === 'orderedList' ? 'listItem' : 'taskList'\n\n chain().updateAttributes(nodeType, attributes).run()\n }\n\n const before = tr.doc.resolve(range.from - 1).nodeBefore\n\n if (\n before &&\n before.type === config.type &&\n canJoin(tr.doc, range.from - 1) &&\n (!config.joinPredicate || config.joinPredicate(match, before))\n ) {\n tr.join(range.from - 1)\n }\n },\n undoable: config.undoable,\n })\n}\n", "export type Attributes = Record\n\nexport type DOMOutputSpecElement = 0 | Attributes | DOMOutputSpecArray\n/**\n * Better describes the output of a `renderHTML` function in prosemirror\n * @see https://prosemirror.net/docs/ref/#model.DOMOutputSpec\n */\nexport type DOMOutputSpecArray =\n | [string]\n | [string, Attributes]\n | [string, 0]\n | [string, Attributes, 0]\n | [string, Attributes, DOMOutputSpecArray | 0]\n | [string, DOMOutputSpecArray]\n\n// JSX types for Tiptap's JSX runtime\n// These types only apply when using @jsxImportSource @tiptap/core\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace JSX {\n export type Element = DOMOutputSpecArray\n export interface IntrinsicElements {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n }\n export interface ElementChildrenAttribute {\n children: unknown\n }\n}\n\nexport type JSXRenderer = (\n tag: 'slot' | string | ((props?: Attributes) => DOMOutputSpecArray | DOMOutputSpecElement),\n props?: Attributes,\n ...children: JSXRenderer[]\n) => DOMOutputSpecArray | DOMOutputSpecElement\n\nexport function Fragment(props: { children: JSXRenderer[] }) {\n return props.children\n}\n\nexport const h: JSXRenderer = (tag, attributes) => {\n // Treat the slot tag as the Prosemirror hole to render content into\n if (tag === 'slot') {\n return 0\n }\n\n // If the tag is a function, call it with the props\n if (tag instanceof Function) {\n return tag(attributes)\n }\n\n const { children, ...rest } = attributes ?? {}\n\n if (tag === 'svg') {\n throw new Error('SVG elements are not supported in the JSX syntax, use the array syntax instead')\n }\n\n // Otherwise, return the tag, attributes, and children\n return [tag, rest, children]\n}\n\n// See\n// https://esbuild.github.io/api/#jsx-import-source\n// https://www.typescriptlang.org/tsconfig/#jsxImportSource\n\nexport { h as createElement, h as jsx, h as jsxDEV, h as jsxs }\n", "import type { Node as PMNode } from '@tiptap/pm/model'\nimport type { Decoration, DecorationSource, NodeView } from '@tiptap/pm/view'\n\nimport type { Editor } from '../Editor.js'\n\nconst isTouchEvent = (e: MouseEvent | TouchEvent): e is TouchEvent => {\n return 'touches' in e\n}\n\n/**\n * Directions where resize handles can be placed\n *\n * @example\n * - `'top'` - Top edge handle\n * - `'bottom-right'` - Bottom-right corner handle\n */\nexport type ResizableNodeViewDirection =\n | 'top'\n | 'right'\n | 'bottom'\n | 'left'\n | 'top-right'\n | 'top-left'\n | 'bottom-right'\n | 'bottom-left'\n\n/**\n * Dimensions for the resizable node in pixels\n */\nexport type ResizableNodeDimensions = {\n /** Width in pixels */\n width: number\n /** Height in pixels */\n height: number\n}\n\n/**\n * Configuration options for creating a ResizableNodeView\n *\n * @example\n * ```ts\n * new ResizableNodeView({\n * element: imgElement,\n * node,\n * getPos,\n * onResize: (width, height) => {\n * imgElement.style.width = `${width}px`\n * imgElement.style.height = `${height}px`\n * },\n * onCommit: (width, height) => {\n * editor.commands.updateAttributes('image', { width, height })\n * },\n * onUpdate: (node) => true,\n * options: {\n * directions: ['bottom-right', 'bottom-left'],\n * min: { width: 100, height: 100 },\n * preserveAspectRatio: true\n * }\n * })\n * ```\n */\nexport type ResizableNodeViewOptions = {\n /**\n * The DOM element to make resizable (e.g., an img, video, or iframe element)\n */\n element: HTMLElement\n\n /**\n * The DOM element that will hold the editable content element\n */\n contentElement?: HTMLElement\n\n /**\n * The ProseMirror node instance\n */\n node: PMNode\n\n /**\n * The Tiptap editor instance\n */\n editor: Editor\n\n /**\n * Function that returns the current position of the node in the document\n */\n getPos: () => number | undefined\n\n /**\n * Callback fired continuously during resize with current dimensions.\n * Use this to update the element's visual size in real-time.\n *\n * @param width - Current width in pixels\n * @param height - Current height in pixels\n *\n * @example\n * ```ts\n * onResize: (width, height) => {\n * element.style.width = `${width}px`\n * element.style.height = `${height}px`\n * }\n * ```\n */\n onResize?: (width: number, height: number) => void\n\n /**\n * Callback fired once when resize completes with final dimensions.\n * Use this to persist the new size to the node's attributes.\n *\n * @param width - Final width in pixels\n * @param height - Final height in pixels\n *\n * @example\n * ```ts\n * onCommit: (width, height) => {\n * const pos = getPos()\n * if (pos !== undefined) {\n * editor.commands.updateAttributes('image', { width, height })\n * }\n * }\n * ```\n */\n onCommit: (width: number, height: number) => void\n\n /**\n * Callback for handling node updates.\n * Return `true` to accept the update, `false` to reject it.\n *\n * @example\n * ```ts\n * onUpdate: (node, decorations, innerDecorations) => {\n * if (node.type !== this.node.type) return false\n * return true\n * }\n * ```\n */\n onUpdate: NodeView['update']\n\n /**\n * Optional configuration for resize behavior and styling\n */\n options?: {\n /**\n * Which resize handles to display.\n * @default ['bottom-left', 'bottom-right', 'top-left', 'top-right']\n *\n * @example\n * ```ts\n * // Only show corner handles\n * directions: ['top-left', 'top-right', 'bottom-left', 'bottom-right']\n *\n * // Only show right edge handle\n * directions: ['right']\n * ```\n */\n directions?: ResizableNodeViewDirection[]\n\n /**\n * Minimum dimensions in pixels\n * @default { width: 8, height: 8 }\n *\n * @example\n * ```ts\n * min: { width: 100, height: 50 }\n * ```\n */\n min?: Partial\n\n /**\n * Maximum dimensions in pixels\n * @default undefined (no maximum)\n *\n * @example\n * ```ts\n * max: { width: 1000, height: 800 }\n * ```\n */\n max?: Partial\n\n /**\n * Always preserve aspect ratio when resizing.\n * When `false`, aspect ratio is preserved only when Shift key is pressed.\n * @default false\n *\n * @example\n * ```ts\n * preserveAspectRatio: true // Always lock aspect ratio\n * ```\n */\n preserveAspectRatio?: boolean\n\n /**\n * Custom CSS class names for styling\n *\n * @example\n * ```ts\n * className: {\n * container: 'resize-container',\n * wrapper: 'resize-wrapper',\n * handle: 'resize-handle',\n * resizing: 'is-resizing'\n * }\n * ```\n */\n className?: {\n /** Class for the outer container element */\n container?: string\n /** Class for the wrapper element that contains the resizable element */\n wrapper?: string\n /** Class applied to all resize handles */\n handle?: string\n /** Class added to container while actively resizing */\n resizing?: string\n }\n\n /**\n * Optional callback for creating custom resize handle elements.\n *\n * This function allows developers to define their own handle element\n * (e.g., custom icons, classes, or styles) for a given resize direction.\n * It is called internally for each handle direction.\n *\n * @param direction - The direction of the handle being created (e.g., 'top', 'bottom-right').\n * @returns The custom handle HTMLElement.\n *\n * @example\n * ```ts\n * createCustomHandle: (direction) => {\n * const handle = document.createElement('div')\n * handle.dataset.resizeHandle = direction\n * handle.style.position = 'absolute'\n * handle.className = 'tiptap-custom-handle'\n *\n * const isTop = direction.includes('top')\n * const isBottom = direction.includes('bottom')\n * const isLeft = direction.includes('left')\n * const isRight = direction.includes('right')\n *\n * if (isTop) handle.style.top = '0'\n * if (isBottom) handle.style.bottom = '0'\n * if (isLeft) handle.style.left = '0'\n * if (isRight) handle.style.right = '0'\n *\n * // Edge handles span the full width or height\n * if (direction === 'top' || direction === 'bottom') {\n * handle.style.left = '0'\n * handle.style.right = '0'\n * }\n *\n * if (direction === 'left' || direction === 'right') {\n * handle.style.top = '0'\n * handle.style.bottom = '0'\n * }\n *\n * return handle\n * }\n * ```\n */\n createCustomHandle?: (direction: ResizableNodeViewDirection) => HTMLElement\n }\n}\n\n/**\n * A NodeView implementation that adds resize handles to any DOM element.\n *\n * This class creates a resizable node view for Tiptap/ProseMirror editors.\n * It wraps your element with resize handles and manages the resize interaction,\n * including aspect ratio preservation, min/max constraints, and keyboard modifiers.\n *\n * @example\n * ```ts\n * // Basic usage in a Tiptap extension\n * addNodeView() {\n * return ({ node, getPos }) => {\n * const img = document.createElement('img')\n * img.src = node.attrs.src\n *\n * return new ResizableNodeView({\n * element: img,\n * node,\n * getPos,\n * onResize: (width, height) => {\n * img.style.width = `${width}px`\n * img.style.height = `${height}px`\n * },\n * onCommit: (width, height) => {\n * this.editor.commands.updateAttributes('image', { width, height })\n * },\n * onUpdate: () => true,\n * options: {\n * min: { width: 100, height: 100 },\n * preserveAspectRatio: true\n * }\n * })\n * }\n * }\n * ```\n */\nexport class ResizableNodeView {\n /** The ProseMirror node instance */\n node: PMNode\n\n /** The Tiptap editor instance */\n editor: Editor\n\n /** The DOM element being made resizable */\n element: HTMLElement\n\n /** The editable DOM element inside the DOM */\n contentElement?: HTMLElement\n\n /** The outer container element (returned as NodeView.dom) */\n container: HTMLElement\n\n /** The wrapper element that contains the element and handles */\n wrapper: HTMLElement\n\n /** Function to get the current node position */\n getPos: () => number | undefined\n\n /** Callback fired during resize */\n onResize?: (width: number, height: number) => void\n\n /** Callback fired when resize completes */\n onCommit: (width: number, height: number) => void\n\n /** Callback for node updates */\n onUpdate?: NodeView['update']\n\n /** Active resize handle directions */\n directions: ResizableNodeViewDirection[] = ['bottom-left', 'bottom-right', 'top-left', 'top-right']\n\n /** Minimum allowed dimensions */\n minSize: ResizableNodeDimensions = {\n height: 8,\n width: 8,\n }\n\n /** Maximum allowed dimensions (optional) */\n maxSize?: Partial\n\n /** Whether to always preserve aspect ratio */\n preserveAspectRatio: boolean = false\n\n /** CSS class names for elements */\n classNames = {\n container: '',\n wrapper: '',\n handle: '',\n resizing: '',\n }\n\n /** Optional callback for creating custom resize handles */\n createCustomHandle?: (direction: ResizableNodeViewDirection) => HTMLElement\n\n /** Initial width of the element (for aspect ratio calculation) */\n private initialWidth: number = 0\n\n /** Initial height of the element (for aspect ratio calculation) */\n private initialHeight: number = 0\n\n /** Calculated aspect ratio (width / height) */\n private aspectRatio: number = 1\n\n /** Whether a resize operation is currently active */\n private isResizing: boolean = false\n\n /** The handle currently being dragged */\n private activeHandle: ResizableNodeViewDirection | null = null\n\n /** Starting mouse X position when resize began */\n private startX: number = 0\n\n /** Starting mouse Y position when resize began */\n private startY: number = 0\n\n /** Element width when resize began */\n private startWidth: number = 0\n\n /** Element height when resize began */\n private startHeight: number = 0\n\n /** Whether Shift key is currently pressed (for temporary aspect ratio lock) */\n private isShiftKeyPressed: boolean = false\n\n /** Last known editable state of the editor */\n private lastEditableState: boolean | undefined = undefined\n\n /** Map of handle elements by direction */\n private handleMap = new Map()\n\n /**\n * Creates a new ResizableNodeView instance.\n *\n * The constructor sets up the resize handles, applies initial sizing from\n * node attributes, and configures all resize behavior options.\n *\n * @param options - Configuration options for the resizable node view\n */\n constructor(options: ResizableNodeViewOptions) {\n this.node = options.node\n this.editor = options.editor\n this.element = options.element\n this.contentElement = options.contentElement\n\n this.getPos = options.getPos\n\n this.onResize = options.onResize\n this.onCommit = options.onCommit\n this.onUpdate = options.onUpdate\n\n if (options.options?.min) {\n this.minSize = {\n ...this.minSize,\n ...options.options.min,\n }\n }\n\n if (options.options?.max) {\n this.maxSize = options.options.max\n }\n\n if (options?.options?.directions) {\n this.directions = options.options.directions\n }\n\n if (options.options?.preserveAspectRatio) {\n this.preserveAspectRatio = options.options.preserveAspectRatio\n }\n\n if (options.options?.className) {\n this.classNames = {\n container: options.options.className.container || '',\n wrapper: options.options.className.wrapper || '',\n handle: options.options.className.handle || '',\n resizing: options.options.className.resizing || '',\n }\n }\n\n if (options.options?.createCustomHandle) {\n this.createCustomHandle = options.options.createCustomHandle\n }\n\n this.wrapper = this.createWrapper()\n this.container = this.createContainer()\n\n this.applyInitialSize()\n this.attachHandles()\n\n this.editor.on('update', this.handleEditorUpdate.bind(this))\n }\n\n /**\n * Returns the top-level DOM node that should be placed in the editor.\n *\n * This is required by the ProseMirror NodeView interface. The container\n * includes the wrapper, handles, and the actual content element.\n *\n * @returns The container element to be inserted into the editor\n */\n get dom() {\n return this.container\n }\n\n get contentDOM(): HTMLElement | null {\n return this.contentElement ?? null\n }\n\n private handleEditorUpdate() {\n const isEditable = this.editor.isEditable\n\n // Only if state actually changed\n if (isEditable === this.lastEditableState) {\n return\n }\n\n this.lastEditableState = isEditable\n\n if (!isEditable) {\n this.removeHandles()\n } else if (isEditable && this.handleMap.size === 0) {\n this.attachHandles()\n }\n }\n\n /**\n * Called when the node's content or attributes change.\n *\n * Updates the internal node reference. If a custom `onUpdate` callback\n * was provided, it will be called to handle additional update logic.\n *\n * @param node - The new/updated node\n * @param decorations - Node decorations\n * @param innerDecorations - Inner decorations\n * @returns `false` if the node type has changed (requires full rebuild), otherwise the result of `onUpdate` or `true`\n */\n update(node: PMNode, decorations: readonly Decoration[], innerDecorations: DecorationSource): boolean {\n if (node.type !== this.node.type) {\n return false\n }\n\n this.node = node\n\n if (this.onUpdate) {\n return this.onUpdate(node, decorations, innerDecorations)\n }\n\n return true\n }\n\n /**\n * Cleanup method called when the node view is being removed.\n *\n * Removes all event listeners to prevent memory leaks. This is required\n * by the ProseMirror NodeView interface. If a resize is active when\n * destroy is called, it will be properly cancelled.\n */\n destroy() {\n if (this.isResizing) {\n this.container.dataset.resizeState = 'false'\n\n if (this.classNames.resizing) {\n this.container.classList.remove(this.classNames.resizing)\n }\n\n document.removeEventListener('mousemove', this.handleMouseMove)\n document.removeEventListener('mouseup', this.handleMouseUp)\n document.removeEventListener('keydown', this.handleKeyDown)\n document.removeEventListener('keyup', this.handleKeyUp)\n this.isResizing = false\n this.activeHandle = null\n }\n\n this.editor.off('update', this.handleEditorUpdate.bind(this))\n\n this.container.remove()\n }\n\n /**\n * Creates the outer container element.\n *\n * The container is the top-level element returned by the NodeView and\n * wraps the entire resizable node. It's set up with flexbox to handle\n * alignment and includes data attributes for styling and identification.\n *\n * @returns The container element\n */\n createContainer() {\n const element = document.createElement('div')\n element.dataset.resizeContainer = ''\n element.dataset.node = this.node.type.name\n element.style.display = 'flex'\n\n if (this.classNames.container) {\n element.className = this.classNames.container\n }\n\n element.appendChild(this.wrapper)\n\n return element\n }\n\n /**\n * Creates the wrapper element that contains the content and handles.\n *\n * The wrapper uses relative positioning so that resize handles can be\n * positioned absolutely within it. This is the direct parent of the\n * content element being made resizable.\n *\n * @returns The wrapper element\n */\n createWrapper() {\n const element = document.createElement('div')\n element.style.position = 'relative'\n element.style.display = 'block'\n element.dataset.resizeWrapper = ''\n\n if (this.classNames.wrapper) {\n element.className = this.classNames.wrapper\n }\n\n element.appendChild(this.element)\n\n return element\n }\n\n /**\n * Creates a resize handle element for a specific direction.\n *\n * Each handle is absolutely positioned and includes a data attribute\n * identifying its direction for styling purposes.\n *\n * @param direction - The resize direction for this handle\n * @returns The handle element\n */\n private createHandle(direction: ResizableNodeViewDirection): HTMLElement {\n const handle = document.createElement('div')\n handle.dataset.resizeHandle = direction\n handle.style.position = 'absolute'\n\n if (this.classNames.handle) {\n handle.className = this.classNames.handle\n }\n\n return handle\n }\n\n /**\n * Positions a handle element according to its direction.\n *\n * Corner handles (e.g., 'top-left') are positioned at the intersection\n * of two edges. Edge handles (e.g., 'top') span the full width or height.\n *\n * @param handle - The handle element to position\n * @param direction - The direction determining the position\n */\n private positionHandle(handle: HTMLElement, direction: ResizableNodeViewDirection): void {\n const isTop = direction.includes('top')\n const isBottom = direction.includes('bottom')\n const isLeft = direction.includes('left')\n const isRight = direction.includes('right')\n\n if (isTop) {\n handle.style.top = '0'\n }\n\n if (isBottom) {\n handle.style.bottom = '0'\n }\n\n if (isLeft) {\n handle.style.left = '0'\n }\n\n if (isRight) {\n handle.style.right = '0'\n }\n\n // Edge handles span the full width or height\n if (direction === 'top' || direction === 'bottom') {\n handle.style.left = '0'\n handle.style.right = '0'\n }\n\n if (direction === 'left' || direction === 'right') {\n handle.style.top = '0'\n handle.style.bottom = '0'\n }\n }\n\n /**\n * Creates and attaches all resize handles to the wrapper.\n *\n * Iterates through the configured directions, creates a handle for each,\n * positions it, attaches the mousedown listener, and appends it to the DOM.\n */\n private attachHandles(): void {\n this.directions.forEach(direction => {\n let handle: HTMLElement\n\n if (this.createCustomHandle) {\n handle = this.createCustomHandle(direction)\n } else {\n handle = this.createHandle(direction)\n }\n\n if (!(handle instanceof HTMLElement)) {\n console.warn(\n `[ResizableNodeView] createCustomHandle(\"${direction}\") did not return an HTMLElement. Falling back to default handle.`,\n )\n handle = this.createHandle(direction)\n }\n\n if (!this.createCustomHandle) {\n this.positionHandle(handle, direction)\n }\n\n handle.addEventListener('mousedown', event => this.handleResizeStart(event, direction))\n handle.addEventListener('touchstart', event => this.handleResizeStart(event as unknown as MouseEvent, direction))\n\n this.handleMap.set(direction, handle)\n\n this.wrapper.appendChild(handle)\n })\n }\n\n /**\n * Removes all resize handles from the wrapper.\n *\n * Cleans up the handle map and removes each handle element from the DOM.\n */\n private removeHandles(): void {\n this.handleMap.forEach(el => el.remove())\n this.handleMap.clear()\n }\n\n /**\n * Applies initial sizing from node attributes to the element.\n *\n * If width/height attributes exist on the node, they're applied to the element.\n * Otherwise, the element's natural/current dimensions are measured. The aspect\n * ratio is calculated for later use in aspect-ratio-preserving resizes.\n */\n private applyInitialSize(): void {\n const width = this.node.attrs.width as number | undefined\n const height = this.node.attrs.height as number | undefined\n\n if (width) {\n this.element.style.width = `${width}px`\n this.initialWidth = width\n } else {\n this.initialWidth = this.element.offsetWidth\n }\n\n if (height) {\n this.element.style.height = `${height}px`\n this.initialHeight = height\n } else {\n this.initialHeight = this.element.offsetHeight\n }\n\n // Calculate aspect ratio for use during resizing\n if (this.initialWidth > 0 && this.initialHeight > 0) {\n this.aspectRatio = this.initialWidth / this.initialHeight\n }\n }\n\n /**\n * Initiates a resize operation when a handle is clicked.\n *\n * Captures the starting mouse position and element dimensions, sets up\n * the resize state, adds the resizing class and state attribute, and\n * attaches document-level listeners for mouse movement and keyboard input.\n *\n * @param event - The mouse down event\n * @param direction - The direction of the handle being dragged\n */\n private handleResizeStart(event: MouseEvent | TouchEvent, direction: ResizableNodeViewDirection): void {\n event.preventDefault()\n event.stopPropagation()\n\n // Capture initial state\n this.isResizing = true\n this.activeHandle = direction\n\n if (isTouchEvent(event)) {\n this.startX = event.touches[0].clientX\n this.startY = event.touches[0].clientY\n } else {\n this.startX = event.clientX\n this.startY = event.clientY\n }\n\n this.startWidth = this.element.offsetWidth\n this.startHeight = this.element.offsetHeight\n\n // Recalculate aspect ratio at resize start for accuracy\n if (this.startWidth > 0 && this.startHeight > 0) {\n this.aspectRatio = this.startWidth / this.startHeight\n }\n\n const pos = this.getPos()\n if (pos !== undefined) {\n // TODO: Select the node in the editor\n }\n\n // Update UI state\n this.container.dataset.resizeState = 'true'\n\n if (this.classNames.resizing) {\n this.container.classList.add(this.classNames.resizing)\n }\n\n // Attach document-level listeners for resize\n document.addEventListener('mousemove', this.handleMouseMove)\n document.addEventListener('touchmove', this.handleTouchMove)\n document.addEventListener('mouseup', this.handleMouseUp)\n document.addEventListener('keydown', this.handleKeyDown)\n document.addEventListener('keyup', this.handleKeyUp)\n }\n\n /**\n * Handles mouse movement during an active resize.\n *\n * Calculates the delta from the starting position, computes new dimensions\n * based on the active handle direction, applies constraints and aspect ratio,\n * then updates the element's style and calls the onResize callback.\n *\n * @param event - The mouse move event\n */\n private handleMouseMove = (event: MouseEvent): void => {\n if (!this.isResizing || !this.activeHandle) {\n return\n }\n\n const deltaX = event.clientX - this.startX\n const deltaY = event.clientY - this.startY\n\n this.handleResize(deltaX, deltaY)\n }\n\n private handleTouchMove = (event: TouchEvent): void => {\n if (!this.isResizing || !this.activeHandle) {\n return\n }\n\n const touch = event.touches[0]\n if (!touch) {\n return\n }\n\n const deltaX = touch.clientX - this.startX\n const deltaY = touch.clientY - this.startY\n\n this.handleResize(deltaX, deltaY)\n }\n\n private handleResize(deltaX: number, deltaY: number) {\n if (!this.activeHandle) {\n return\n }\n\n const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed\n const { width, height } = this.calculateNewDimensions(this.activeHandle, deltaX, deltaY)\n const constrained = this.applyConstraints(width, height, shouldPreserveAspectRatio)\n\n this.element.style.width = `${constrained.width}px`\n this.element.style.height = `${constrained.height}px`\n\n if (this.onResize) {\n this.onResize(constrained.width, constrained.height)\n }\n }\n\n /**\n * Completes the resize operation when the mouse button is released.\n *\n * Captures final dimensions, calls the onCommit callback to persist changes,\n * removes the resizing state and class, and cleans up document-level listeners.\n */\n private handleMouseUp = (): void => {\n if (!this.isResizing) {\n return\n }\n\n const finalWidth = this.element.offsetWidth\n const finalHeight = this.element.offsetHeight\n\n this.onCommit(finalWidth, finalHeight)\n\n this.isResizing = false\n this.activeHandle = null\n\n // Remove UI state\n this.container.dataset.resizeState = 'false'\n\n if (this.classNames.resizing) {\n this.container.classList.remove(this.classNames.resizing)\n }\n\n // Clean up document-level listeners\n document.removeEventListener('mousemove', this.handleMouseMove)\n document.removeEventListener('mouseup', this.handleMouseUp)\n document.removeEventListener('keydown', this.handleKeyDown)\n document.removeEventListener('keyup', this.handleKeyUp)\n }\n\n /**\n * Tracks Shift key state to enable temporary aspect ratio locking.\n *\n * When Shift is pressed during resize, aspect ratio is preserved even if\n * preserveAspectRatio is false.\n *\n * @param event - The keyboard event\n */\n private handleKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Shift') {\n this.isShiftKeyPressed = true\n }\n }\n\n /**\n * Tracks Shift key release to disable temporary aspect ratio locking.\n *\n * @param event - The keyboard event\n */\n private handleKeyUp = (event: KeyboardEvent): void => {\n if (event.key === 'Shift') {\n this.isShiftKeyPressed = false\n }\n }\n\n /**\n * Calculates new dimensions based on mouse delta and resize direction.\n *\n * Takes the starting dimensions and applies the mouse movement delta\n * according to the handle direction. For corner handles, both dimensions\n * are affected. For edge handles, only one dimension changes. If aspect\n * ratio should be preserved, delegates to applyAspectRatio.\n *\n * @param direction - The active resize handle direction\n * @param deltaX - Horizontal mouse movement since resize start\n * @param deltaY - Vertical mouse movement since resize start\n * @returns The calculated width and height\n */\n private calculateNewDimensions(\n direction: ResizableNodeViewDirection,\n deltaX: number,\n deltaY: number,\n ): ResizableNodeDimensions {\n let newWidth = this.startWidth\n let newHeight = this.startHeight\n\n const isRight = direction.includes('right')\n const isLeft = direction.includes('left')\n const isBottom = direction.includes('bottom')\n const isTop = direction.includes('top')\n\n // Apply horizontal delta\n if (isRight) {\n newWidth = this.startWidth + deltaX\n } else if (isLeft) {\n newWidth = this.startWidth - deltaX\n }\n\n // Apply vertical delta\n if (isBottom) {\n newHeight = this.startHeight + deltaY\n } else if (isTop) {\n newHeight = this.startHeight - deltaY\n }\n\n // For pure horizontal/vertical handles, only one dimension changes\n if (direction === 'right' || direction === 'left') {\n newWidth = this.startWidth + (isRight ? deltaX : -deltaX)\n }\n\n if (direction === 'top' || direction === 'bottom') {\n newHeight = this.startHeight + (isBottom ? deltaY : -deltaY)\n }\n\n const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed\n\n if (shouldPreserveAspectRatio) {\n return this.applyAspectRatio(newWidth, newHeight, direction)\n }\n\n return { width: newWidth, height: newHeight }\n }\n\n /**\n * Applies min/max constraints to dimensions.\n *\n * When aspect ratio is NOT preserved, constraints are applied independently\n * to width and height. When aspect ratio IS preserved, constraints are\n * applied while maintaining the aspect ratio—if one dimension hits a limit,\n * the other is recalculated proportionally.\n *\n * This ensures that aspect ratio is never broken when constrained.\n *\n * @param width - The unconstrained width\n * @param height - The unconstrained height\n * @param preserveAspectRatio - Whether to maintain aspect ratio while constraining\n * @returns The constrained dimensions\n */\n private applyConstraints(width: number, height: number, preserveAspectRatio: boolean): ResizableNodeDimensions {\n if (!preserveAspectRatio) {\n // Independent constraints for each dimension\n let constrainedWidth = Math.max(this.minSize.width, width)\n let constrainedHeight = Math.max(this.minSize.height, height)\n\n if (this.maxSize?.width) {\n constrainedWidth = Math.min(this.maxSize.width, constrainedWidth)\n }\n\n if (this.maxSize?.height) {\n constrainedHeight = Math.min(this.maxSize.height, constrainedHeight)\n }\n\n return { width: constrainedWidth, height: constrainedHeight }\n }\n\n // Aspect-ratio-aware constraints: adjust both dimensions proportionally\n let constrainedWidth = width\n let constrainedHeight = height\n\n // Check minimum constraints\n if (constrainedWidth < this.minSize.width) {\n constrainedWidth = this.minSize.width\n constrainedHeight = constrainedWidth / this.aspectRatio\n }\n\n if (constrainedHeight < this.minSize.height) {\n constrainedHeight = this.minSize.height\n constrainedWidth = constrainedHeight * this.aspectRatio\n }\n\n // Check maximum constraints\n if (this.maxSize?.width && constrainedWidth > this.maxSize.width) {\n constrainedWidth = this.maxSize.width\n constrainedHeight = constrainedWidth / this.aspectRatio\n }\n\n if (this.maxSize?.height && constrainedHeight > this.maxSize.height) {\n constrainedHeight = this.maxSize.height\n constrainedWidth = constrainedHeight * this.aspectRatio\n }\n\n return { width: constrainedWidth, height: constrainedHeight }\n }\n\n /**\n * Adjusts dimensions to maintain the original aspect ratio.\n *\n * For horizontal handles (left/right), uses width as the primary dimension\n * and calculates height from it. For vertical handles (top/bottom), uses\n * height as primary and calculates width. For corner handles, uses width\n * as the primary dimension.\n *\n * @param width - The new width\n * @param height - The new height\n * @param direction - The active resize direction\n * @returns Dimensions adjusted to preserve aspect ratio\n */\n private applyAspectRatio(\n width: number,\n height: number,\n direction: ResizableNodeViewDirection,\n ): ResizableNodeDimensions {\n const isHorizontal = direction === 'left' || direction === 'right'\n const isVertical = direction === 'top' || direction === 'bottom'\n\n if (isHorizontal) {\n // For horizontal resize, width is primary\n return {\n width,\n height: width / this.aspectRatio,\n }\n }\n\n if (isVertical) {\n // For vertical resize, height is primary\n return {\n width: height * this.aspectRatio,\n height,\n }\n }\n\n // For corner resize, width is primary\n return {\n width,\n height: width / this.aspectRatio,\n }\n }\n}\n\n/**\n * Alias for ResizableNodeView to maintain consistent naming.\n * @deprecated Use ResizableNodeView instead - will be removed in future versions.\n */\nexport const ResizableNodeview = ResizableNodeView\n", "import type { NodeType } from '@tiptap/pm/model'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\n\nexport function canInsertNode(state: EditorState, nodeType: NodeType): boolean {\n const { selection } = state\n const { $from } = selection\n\n // Special handling for NodeSelection\n if (selection instanceof NodeSelection) {\n const index = $from.index()\n const parent = $from.parent\n\n // Can we replace the selected node with the horizontal rule?\n return parent.canReplaceWith(index, index + 1, nodeType)\n }\n\n // Default: check if we can insert at the current position\n let depth = $from.depth\n\n while (depth >= 0) {\n const index = $from.index(depth)\n const parent = $from.node(depth)\n const match = parent.contentMatchAt(index)\n if (match.matchType(nodeType)) {\n return true\n }\n depth -= 1\n }\n return false\n}\n", "// source: https://stackoverflow.com/a/6969486\nexport function escapeForRegEx(string: string): string {\n return string.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n}\n", "/**\n * Detects if the current browser is Firefox.\n * @returns `true` if the browser is Firefox, `false` otherwise.\n * @example\n * if (isFirefox()) {\n * // Firefox-specific handling\n * }\n */\nexport function isFirefox(): boolean {\n return typeof navigator !== 'undefined' ? /Firefox/.test(navigator.userAgent) : false\n}\n", "export function isString(value: any): value is string {\n return typeof value === 'string'\n}\n", "/**\n * @fileoverview Markdown utilities for creating standardized markdown specs.\n *\n * This module provides utilities for creating complete markdown specifications\n * for different types of nodes using unified syntax patterns.\n */\n\nexport * from './attributeUtils.js'\nexport * from './createAtomBlockMarkdownSpec.js'\nexport * from './createBlockMarkdownSpec.js'\nexport * from './createInlineMarkdownSpec.js'\nexport * from './parseIndentedBlocks.js'\nexport * from './renderNestedMarkdownContent.js'\n", "/**\n * @fileoverview Utility functions for parsing and serializing markdown attributes.\n *\n * These utilities handle the common patterns for parsing attribute strings\n * in various markdown syntaxes like Pandoc attributes.\n */\n\n/**\n * Parses a Pandoc-style attribute string into an object.\n *\n * Supports the following patterns:\n * - Classes: `.className` → `{ class: 'className' }`\n * - IDs: `#myId` → `{ id: 'myId' }`\n * - Key-value pairs: `key=\"value\"` → `{ key: 'value' }`\n * - Boolean attributes: `disabled` → `{ disabled: true }`\n *\n * @param attrString - The attribute string to parse\n * @returns Parsed attributes object\n *\n * @example\n * ```ts\n * parseAttributes('.btn #submit disabled type=\"button\"')\n * // → { class: 'btn', id: 'submit', disabled: true, type: 'button' }\n * ```\n */\nexport function parseAttributes(attrString: string): Record {\n if (!attrString?.trim()) {\n return {}\n }\n\n const attributes: Record = {}\n\n // First, extract and remove quoted strings to avoid parsing content inside them\n const quotedStrings: string[] = []\n const tempString = attrString.replace(/[\"']([^\"']*)[\"']/g, match => {\n quotedStrings.push(match)\n return `__QUOTED_${quotedStrings.length - 1}__`\n })\n\n // Parse classes (.className) - only outside of quoted strings\n const classMatches = tempString.match(/(?:^|\\s)\\.([a-zA-Z][\\w-]*)/g)\n if (classMatches) {\n const classes = classMatches.map(match => match.trim().slice(1)) // Remove the dot\n attributes.class = classes.join(' ')\n }\n\n // Parse IDs (#myId) - only outside of quoted strings\n const idMatch = tempString.match(/(?:^|\\s)#([a-zA-Z][\\w-]*)/)\n if (idMatch) {\n attributes.id = idMatch[1]\n }\n\n // Parse key-value pairs (key=\"value\" or key='value') - restore quoted strings\n const kvRegex = /([a-zA-Z][\\w-]*)\\s*=\\s*(__QUOTED_\\d+__)/g\n const kvMatches = Array.from(tempString.matchAll(kvRegex))\n kvMatches.forEach(([, key, quotedRef]) => {\n const quotedIndex = parseInt(quotedRef.match(/__QUOTED_(\\d+)__/)?.[1] || '0', 10)\n const quotedValue = quotedStrings[quotedIndex]\n if (quotedValue) {\n // Remove the outer quotes\n attributes[key] = quotedValue.slice(1, -1)\n }\n })\n\n // Parse boolean attributes (standalone words that aren't classes/IDs)\n const cleanString = tempString\n .replace(/(?:^|\\s)\\.([a-zA-Z][\\w-]*)/g, '') // Remove classes\n .replace(/(?:^|\\s)#([a-zA-Z][\\w-]*)/g, '') // Remove IDs\n .replace(/([a-zA-Z][\\w-]*)\\s*=\\s*__QUOTED_\\d+__/g, '') // Remove key-value pairs\n .trim()\n\n if (cleanString) {\n const booleanAttrs = cleanString.split(/\\s+/).filter(Boolean)\n booleanAttrs.forEach(attr => {\n if (attr.match(/^[a-zA-Z][\\w-]*$/)) {\n attributes[attr] = true\n }\n })\n }\n\n return attributes\n}\n\n/**\n * Serializes an attributes object back to a Pandoc-style attribute string.\n *\n * @param attributes - The attributes object to serialize\n * @returns Serialized attribute string\n *\n * @example\n * ```ts\n * serializeAttributes({ class: 'btn primary', id: 'submit', disabled: true, type: 'button' })\n * // → '.btn.primary #submit disabled type=\"button\"'\n * ```\n */\nexport function serializeAttributes(attributes: Record): string {\n if (!attributes || Object.keys(attributes).length === 0) {\n return ''\n }\n\n const parts: string[] = []\n\n // Handle classes\n if (attributes.class) {\n const classes = String(attributes.class).split(/\\s+/).filter(Boolean)\n classes.forEach(cls => parts.push(`.${cls}`))\n }\n\n // Handle ID\n if (attributes.id) {\n parts.push(`#${attributes.id}`)\n }\n\n // Handle other attributes\n Object.entries(attributes).forEach(([key, value]) => {\n if (key === 'class' || key === 'id') {\n return // Already handled\n }\n\n if (value === true) {\n // Boolean attribute\n parts.push(key)\n } else if (value !== false && value != null) {\n // Key-value attribute\n parts.push(`${key}=\"${String(value)}\"`)\n }\n })\n\n return parts.join(' ')\n}\n", "import type {\n JSONContent,\n MarkdownParseHelpers,\n MarkdownParseResult,\n MarkdownToken,\n MarkdownTokenizer,\n} from '../../types.js'\nimport {\n parseAttributes as defaultParseAttributes,\n serializeAttributes as defaultSerializeAttributes,\n} from './attributeUtils.js'\n\nexport interface AtomBlockMarkdownSpecOptions {\n /** The Tiptap node name this spec is for */\n nodeName: string\n /** The markdown syntax name (defaults to nodeName if not provided) */\n name?: string\n /** Function to parse attributes from token attribute string */\n parseAttributes?: (attrString: string) => Record\n /** Function to serialize attributes back to string for rendering */\n serializeAttributes?: (attrs: Record) => string\n /** Default attributes to apply when parsing */\n defaultAttributes?: Record\n /** Required attributes that must be present for successful parsing */\n requiredAttributes?: string[]\n /** Attributes that are allowed to be rendered back to markdown (whitelist) */\n allowedAttributes?: string[]\n}\n\n/**\n * Creates a complete markdown spec for atomic block nodes using Pandoc syntax.\n *\n * The generated spec handles:\n * - Parsing self-closing blocks with `:::blockName {attributes}`\n * - Extracting and parsing attributes\n * - Validating required attributes\n * - Rendering blocks back to markdown\n *\n * @param options - Configuration for the atomic block markdown spec\n * @returns Complete markdown specification object\n *\n * @example\n * ```ts\n * const youtubeSpec = createAtomBlockMarkdownSpec({\n * nodeName: 'youtube',\n * requiredAttributes: ['src'],\n * defaultAttributes: { start: 0 },\n * allowedAttributes: ['src', 'start', 'width', 'height'] // Only these get rendered to markdown\n * })\n *\n * // Usage in extension:\n * export const Youtube = Node.create({\n * // ... other config\n * markdown: youtubeSpec\n * })\n * ```\n */\nexport function createAtomBlockMarkdownSpec(options: AtomBlockMarkdownSpecOptions): {\n parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => MarkdownParseResult\n markdownTokenizer: MarkdownTokenizer\n renderMarkdown: (node: JSONContent) => string\n} {\n const {\n nodeName,\n name: markdownName,\n parseAttributes = defaultParseAttributes,\n serializeAttributes = defaultSerializeAttributes,\n defaultAttributes = {},\n requiredAttributes = [],\n allowedAttributes,\n } = options\n\n // Use markdownName for syntax, fallback to nodeName\n const blockName = markdownName || nodeName\n\n // Helper function to filter attributes based on allowlist\n const filterAttributes = (attrs: Record) => {\n if (!allowedAttributes) {\n return attrs\n }\n\n const filtered: Record = {}\n allowedAttributes.forEach(key => {\n if (key in attrs) {\n filtered[key] = attrs[key]\n }\n })\n return filtered\n }\n\n return {\n parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => {\n const attrs = { ...defaultAttributes, ...token.attributes }\n return h.createNode(nodeName, attrs, [])\n },\n\n markdownTokenizer: {\n name: nodeName,\n level: 'block' as const,\n start(src: string) {\n const regex = new RegExp(`^:::${blockName}(?:\\\\s|$)`, 'm')\n const index = src.match(regex)?.index\n return index !== undefined ? index : -1\n },\n tokenize(src, _tokens, _lexer) {\n // Use non-global regex to match from the start of the string\n // Include optional newline to ensure we consume the entire line\n const regex = new RegExp(`^:::${blockName}(?:\\\\s+\\\\{([^}]*)\\\\})?\\\\s*:::(?:\\\\n|$)`)\n const match = src.match(regex)\n\n if (!match) {\n return undefined\n }\n\n // Parse attributes if present\n const attrString = match[1] || ''\n const attributes = parseAttributes(attrString)\n\n // Validate required attributes\n const missingRequired = requiredAttributes.find(required => !(required in attributes))\n if (missingRequired) {\n return undefined\n }\n\n return {\n type: nodeName,\n raw: match[0],\n attributes,\n }\n },\n },\n\n renderMarkdown: node => {\n const filteredAttrs = filterAttributes(node.attrs || {})\n const attrs = serializeAttributes(filteredAttrs)\n const attrString = attrs ? ` {${attrs}}` : ''\n\n return `:::${blockName}${attrString} :::`\n },\n }\n}\n", "import type {\n JSONContent,\n MarkdownParseHelpers,\n MarkdownParseResult,\n MarkdownRendererHelpers,\n MarkdownToken,\n MarkdownTokenizer,\n} from '../../types.js'\nimport {\n parseAttributes as defaultParseAttributes,\n serializeAttributes as defaultSerializeAttributes,\n} from './attributeUtils.js'\n\nexport interface BlockMarkdownSpecOptions {\n /** The Tiptap node name this spec is for */\n nodeName: string\n /** The markdown syntax name (defaults to nodeName if not provided) */\n name?: string\n /** Function to extract content from the node for serialization */\n getContent?: (token: MarkdownToken) => string\n /** Function to parse attributes from the attribute string */\n parseAttributes?: (attrString: string) => Record\n /** Function to serialize attributes to string */\n serializeAttributes?: (attrs: Record) => string\n /** Default attributes to apply when parsing */\n defaultAttributes?: Record\n /** Content type: 'block' allows paragraphs/lists/etc, 'inline' only allows bold/italic/links/etc */\n content?: 'block' | 'inline'\n /** Allowlist of attributes to include in markdown (if not provided, all attributes are included) */\n allowedAttributes?: string[]\n}\n\n/**\n * Creates a complete markdown spec for block-level nodes using Pandoc syntax.\n *\n * The generated spec handles:\n * - Parsing blocks with `:::blockName {attributes}` syntax\n * - Extracting and parsing attributes\n * - Rendering blocks back to markdown with proper formatting\n * - Nested content support\n *\n * @param options - Configuration for the block markdown spec\n * @returns Complete markdown specification object\n *\n * @example\n * ```ts\n * const calloutSpec = createBlockMarkdownSpec({\n * nodeName: 'callout',\n * defaultAttributes: { type: 'info' },\n * allowedAttributes: ['type', 'title'] // Only these get rendered to markdown\n * })\n *\n * // Usage in extension:\n * export const Callout = Node.create({\n * // ... other config\n * markdown: calloutSpec\n * })\n * ```\n */\nexport function createBlockMarkdownSpec(options: BlockMarkdownSpecOptions): {\n parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => MarkdownParseResult\n markdownTokenizer: MarkdownTokenizer\n renderMarkdown: (node: JSONContent, h: MarkdownRendererHelpers) => string\n} {\n const {\n nodeName,\n name: markdownName,\n getContent,\n parseAttributes = defaultParseAttributes,\n serializeAttributes = defaultSerializeAttributes,\n defaultAttributes = {},\n content = 'block',\n allowedAttributes,\n } = options\n\n // Use markdownName for syntax, fallback to nodeName\n const blockName = markdownName || nodeName\n\n // Helper function to filter attributes based on allowlist\n const filterAttributes = (attrs: Record) => {\n if (!allowedAttributes) {\n return attrs\n }\n\n const filtered: Record = {}\n allowedAttributes.forEach(key => {\n if (key in attrs) {\n filtered[key] = attrs[key]\n }\n })\n return filtered\n }\n\n return {\n parseMarkdown: (token, h) => {\n let nodeContent: JSONContent[]\n\n if (getContent) {\n const contentResult = getContent(token)\n // If getContent returns a string, wrap it in a text node\n nodeContent = typeof contentResult === 'string' ? [{ type: 'text', text: contentResult }] : contentResult\n } else if (content === 'block') {\n nodeContent = h.parseChildren(token.tokens || [])\n } else {\n nodeContent = h.parseInline(token.tokens || [])\n }\n\n const attrs = { ...defaultAttributes, ...token.attributes }\n\n return h.createNode(nodeName, attrs, nodeContent)\n },\n\n markdownTokenizer: {\n name: nodeName,\n level: 'block' as const,\n start(src) {\n const regex = new RegExp(`^:::${blockName}`, 'm')\n const index = src.match(regex)?.index\n return index !== undefined ? index : -1\n },\n tokenize(src, _tokens, lexer) {\n // Match the opening tag with optional attributes\n const openingRegex = new RegExp(`^:::${blockName}(?:\\\\s+\\\\{([^}]*)\\\\})?\\\\s*\\\\n`)\n const openingMatch = src.match(openingRegex)\n\n if (!openingMatch) {\n return undefined\n }\n\n const [openingTag, attrString = ''] = openingMatch\n const attributes = parseAttributes(attrString)\n\n // Find the matching closing tag by tracking nesting level\n let level = 1\n const position = openingTag.length\n let matchedContent = ''\n\n // Pattern to match any block opening (:::word) or closing (:::)\n const blockPattern = /^:::([\\w-]*)(\\s.*)?/gm\n const remaining = src.slice(position)\n\n blockPattern.lastIndex = 0\n\n // run until no more matches are found\n for (;;) {\n const match = blockPattern.exec(remaining)\n if (match === null) {\n break\n }\n const matchPos = match.index\n const blockType = match[1] // Empty string for closing tag, block name for opening\n\n if (match[2]?.endsWith(':::')) {\n // this is an atom ::: node, we skip it\n continue\n }\n\n if (blockType) {\n // Opening tag found - increase level\n level += 1\n } else {\n // Closing tag found - decrease level\n level -= 1\n\n if (level === 0) {\n // Found our matching closing tag\n // Don't trim yet - keep newlines for tokenizer regex matching\n const rawContent = remaining.slice(0, matchPos)\n matchedContent = rawContent.trim()\n const fullMatch = src.slice(0, position + matchPos + match[0].length)\n\n // Tokenize the content\n let contentTokens: MarkdownToken[] = []\n if (matchedContent) {\n if (content === 'block') {\n // Use rawContent for tokenization to preserve line boundaries for regex matching\n contentTokens = lexer.blockTokens(rawContent)\n\n // Parse inline tokens for any token that has text content but no tokens\n contentTokens.forEach(token => {\n if (token.text && (!token.tokens || token.tokens.length === 0)) {\n token.tokens = lexer.inlineTokens(token.text)\n }\n })\n\n // Clean up empty trailing paragraphs\n while (contentTokens.length > 0) {\n const lastToken = contentTokens[contentTokens.length - 1]\n if (lastToken.type === 'paragraph' && (!lastToken.text || lastToken.text.trim() === '')) {\n contentTokens.pop()\n } else {\n break\n }\n }\n } else {\n contentTokens = lexer.inlineTokens(matchedContent)\n }\n }\n\n return {\n type: nodeName,\n raw: fullMatch,\n attributes,\n content: matchedContent,\n tokens: contentTokens,\n }\n }\n }\n }\n\n // No matching closing tag found\n return undefined\n },\n },\n\n renderMarkdown: (node, h) => {\n const filteredAttrs = filterAttributes(node.attrs || {})\n const attrs = serializeAttributes(filteredAttrs)\n const attrString = attrs ? ` {${attrs}}` : ''\n const renderedContent = h.renderChildren(node.content || [], '\\n\\n')\n\n return `:::${blockName}${attrString}\\n\\n${renderedContent}\\n\\n:::`\n },\n }\n}\n", "import type {\n JSONContent,\n MarkdownParseHelpers,\n MarkdownParseResult,\n MarkdownToken,\n MarkdownTokenizer,\n} from '../../types.js'\n\n/**\n * Parse shortcode attributes like 'id=\"madonna\" handle=\"john\" name=\"John Doe\"'\n * Requires all values to be quoted with either single or double quotes\n */\nfunction parseShortcodeAttributes(attrString: string): Record {\n if (!attrString.trim()) {\n return {}\n }\n\n const attributes: Record = {}\n // Match key=value pairs, only accepting quoted values\n const regex = /(\\w+)=(?:\"([^\"]*)\"|'([^']*)')/g\n let match = regex.exec(attrString)\n\n while (match !== null) {\n const [, key, doubleQuoted, singleQuoted] = match\n attributes[key] = doubleQuoted || singleQuoted\n match = regex.exec(attrString)\n }\n\n return attributes\n}\n\n/**\n * Serialize attributes back to shortcode format\n * Always quotes all values with double quotes\n */\nfunction serializeShortcodeAttributes(attrs: Record): string {\n return Object.entries(attrs)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(' ')\n}\n\n/**\n * Configuration for an allowed attribute in markdown serialization.\n * Can be a simple string (attribute name) or an object with additional options.\n */\nexport type AllowedAttribute =\n | string\n | {\n /** The attribute name */\n name: string\n /**\n * If provided, the attribute will be skipped during serialization when its value\n * equals this default value. This keeps markdown output clean by omitting\n * attributes that have their default values.\n */\n skipIfDefault?: any\n }\n\nexport interface InlineMarkdownSpecOptions {\n /** The Tiptap node name this spec is for */\n nodeName: string\n /** The shortcode name (defaults to nodeName if not provided) */\n name?: string\n /** Function to extract content from the node for serialization */\n getContent?: (node: any) => string\n /** Function to parse attributes from the attribute string */\n parseAttributes?: (attrString: string) => Record\n /** Function to serialize attributes to string */\n serializeAttributes?: (attrs: Record) => string\n /** Default attributes to apply when parsing */\n defaultAttributes?: Record\n /** Whether this is a self-closing shortcode (no content, like [emoji name=party]) */\n selfClosing?: boolean\n /**\n * Allowlist of attributes to include in markdown serialization.\n * If not provided, all attributes are included.\n *\n * Each item can be either:\n * - A string: the attribute name (always included if present)\n * - An object: `{ name: string, skipIfDefault?: any }` for conditional inclusion\n *\n * @example\n * // Simple string attributes (backward compatible)\n * allowedAttributes: ['id', 'label']\n *\n * // Mixed with conditional attributes\n * allowedAttributes: [\n * 'id',\n * 'label',\n * { name: 'mentionSuggestionChar', skipIfDefault: '@' }\n * ]\n */\n allowedAttributes?: AllowedAttribute[]\n}\n\n/**\n * Creates a complete markdown spec for inline nodes using attribute syntax.\n *\n * The generated spec handles:\n * - Parsing shortcode syntax with `[nodeName attributes]content[/nodeName]` format\n * - Self-closing shortcodes like `[emoji name=party_popper]`\n * - Extracting and parsing attributes from the opening tag\n * - Rendering inline elements back to shortcode markdown\n * - Supporting both content-based and self-closing inline elements\n *\n * @param options - Configuration for the inline markdown spec\n * @returns Complete markdown specification object\n *\n * @example\n * ```ts\n * // Self-closing mention: [mention id=\"madonna\" label=\"Madonna\"]\n * const mentionSpec = createInlineMarkdownSpec({\n * nodeName: 'mention',\n * selfClosing: true,\n * defaultAttributes: { type: 'user' },\n * allowedAttributes: ['id', 'label'] // Only these get rendered to markdown\n * })\n *\n * // Self-closing emoji: [emoji name=\"party_popper\"]\n * const emojiSpec = createInlineMarkdownSpec({\n * nodeName: 'emoji',\n * selfClosing: true,\n * allowedAttributes: ['name']\n * })\n *\n * // With content: [highlight color=\"yellow\"]text[/highlight]\n * const highlightSpec = createInlineMarkdownSpec({\n * nodeName: 'highlight',\n * selfClosing: false,\n * allowedAttributes: ['color', 'style']\n * })\n *\n * // Usage in extension:\n * export const Mention = Node.create({\n * name: 'mention', // Must match nodeName\n * // ... other config\n * markdown: mentionSpec\n * })\n * ```\n */\nexport function createInlineMarkdownSpec(options: InlineMarkdownSpecOptions): {\n parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => MarkdownParseResult\n markdownTokenizer: MarkdownTokenizer\n renderMarkdown: (node: JSONContent) => string\n} {\n const {\n nodeName,\n name: shortcodeName,\n getContent,\n parseAttributes = parseShortcodeAttributes,\n serializeAttributes = serializeShortcodeAttributes,\n defaultAttributes = {},\n selfClosing = false,\n allowedAttributes,\n } = options\n\n // Use shortcodeName for markdown syntax, fallback to nodeName\n const shortcode = shortcodeName || nodeName\n\n // Helper function to filter attributes based on allowlist\n const filterAttributes = (attrs: Record) => {\n if (!allowedAttributes) {\n return attrs\n }\n\n const filtered: Record = {}\n allowedAttributes.forEach(attr => {\n // Handle both string and object formats for backward compatibility\n const attrName = typeof attr === 'string' ? attr : attr.name\n const skipIfDefault = typeof attr === 'string' ? undefined : attr.skipIfDefault\n\n if (attrName in attrs) {\n const value = attrs[attrName]\n\n // Skip if value equals the default (when skipIfDefault is specified)\n if (skipIfDefault !== undefined && value === skipIfDefault) {\n return\n }\n\n filtered[attrName] = value\n }\n })\n return filtered\n }\n\n // Escape special regex characters in shortcode name\n const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n return {\n parseMarkdown: (token: MarkdownToken, h: MarkdownParseHelpers) => {\n const attrs = { ...defaultAttributes, ...token.attributes }\n\n if (selfClosing) {\n // Self-closing nodes like mentions are atomic - no content\n return h.createNode(nodeName, attrs)\n }\n\n // Nodes with content\n const content = getContent ? getContent(token) : token.content || ''\n if (content) {\n // For inline content, create text nodes using the proper helper\n return h.createNode(nodeName, attrs, [h.createTextNode(content)])\n }\n return h.createNode(nodeName, attrs, [])\n },\n\n markdownTokenizer: {\n name: nodeName,\n level: 'inline' as const,\n start(src: string) {\n // Create a non-global version for finding the start position\n const startPattern = selfClosing\n ? new RegExp(`\\\\[${escapedShortcode}\\\\s*[^\\\\]]*\\\\]`)\n : new RegExp(`\\\\[${escapedShortcode}\\\\s*[^\\\\]]*\\\\][\\\\s\\\\S]*?\\\\[\\\\/${escapedShortcode}\\\\]`)\n\n const match = src.match(startPattern)\n const index = match?.index\n return index !== undefined ? index : -1\n },\n tokenize(src, _tokens, _lexer) {\n // Use non-global regex to match from the start of the string\n const tokenPattern = selfClosing\n ? new RegExp(`^\\\\[${escapedShortcode}\\\\s*([^\\\\]]*)\\\\]`)\n : new RegExp(`^\\\\[${escapedShortcode}\\\\s*([^\\\\]]*)\\\\]([\\\\s\\\\S]*?)\\\\[\\\\/${escapedShortcode}\\\\]`)\n\n const match = src.match(tokenPattern)\n\n if (!match) {\n return undefined\n }\n\n let content = ''\n let attrString = ''\n\n if (selfClosing) {\n // Self-closing: [shortcode attr=\"value\"]\n const [, attrs] = match\n attrString = attrs\n } else {\n // With content: [shortcode attr=\"value\"]content[/shortcode]\n const [, attrs, contentMatch] = match\n attrString = attrs\n content = contentMatch || ''\n }\n\n // Parse attributes from the attribute string\n const attributes = parseAttributes(attrString.trim())\n\n return {\n type: nodeName,\n raw: match[0],\n content: content.trim(),\n attributes,\n }\n },\n },\n\n renderMarkdown: (node: JSONContent) => {\n let content = ''\n if (getContent) {\n content = getContent(node)\n } else if (node.content && node.content.length > 0) {\n // Extract text from content array for inline nodes\n content = node.content\n .filter((child: any) => child.type === 'text')\n .map((child: any) => child.text)\n .join('')\n }\n\n const filteredAttrs = filterAttributes(node.attrs || {})\n const attrs = serializeAttributes(filteredAttrs)\n const attrString = attrs ? ` ${attrs}` : ''\n\n if (selfClosing) {\n return `[${shortcode}${attrString}]`\n }\n\n return `[${shortcode}${attrString}]${content}[/${shortcode}]`\n },\n }\n}\n", "/**\n * @fileoverview Utility for parsing indented markdown blocks with hierarchical nesting.\n *\n * This utility handles the complex logic of parsing markdown blocks that can contain\n * nested content based on indentation levels, maintaining proper hierarchical structure\n * for lists, task lists, and other indented block types.\n */\n\nexport interface ParsedBlock {\n type: string\n raw: string\n mainContent: string\n indentLevel: number\n nestedContent?: string\n nestedTokens?: any[]\n [key: string]: any\n}\n\nexport interface BlockParserConfig {\n /** Regex pattern to match block items */\n itemPattern: RegExp\n /** Function to extract data from regex match */\n extractItemData: (match: RegExpMatchArray) => {\n mainContent: string\n indentLevel: number\n [key: string]: any\n }\n /** Function to create the final token */\n createToken: (data: any, nestedTokens?: any[]) => ParsedBlock\n /** Base indentation to remove from nested content (default: 2 spaces) */\n baseIndentSize?: number\n /**\n * Custom parser for nested content. If provided, this will be called instead\n * of the default lexer.blockTokens() for parsing nested content.\n * This allows recursive parsing of the same block type.\n */\n customNestedParser?: (dedentedContent: string) => any[] | undefined\n}\n\n/**\n * Parses markdown text into hierarchical indented blocks with proper nesting.\n *\n * This utility handles:\n * - Line-by-line parsing with pattern matching\n * - Hierarchical nesting based on indentation levels\n * - Nested content collection and parsing\n * - Empty line handling\n * - Content dedenting for nested blocks\n *\n * The key difference from flat parsing is that this maintains the hierarchical\n * structure where nested items become `nestedTokens` of their parent items,\n * rather than being flattened into a single array.\n *\n * @param src - The markdown source text to parse\n * @param config - Configuration object defining how to parse and create tokens\n * @param lexer - Markdown lexer for parsing nested content\n * @returns Parsed result with hierarchical items, or undefined if no matches\n *\n * @example\n * ```ts\n * const result = parseIndentedBlocks(src, {\n * itemPattern: /^(\\s*)([-+*])\\s+\\[([ xX])\\]\\s+(.*)$/,\n * extractItemData: (match) => ({\n * indentLevel: match[1].length,\n * mainContent: match[4],\n * checked: match[3].toLowerCase() === 'x'\n * }),\n * createToken: (data, nestedTokens) => ({\n * type: 'taskItem',\n * checked: data.checked,\n * text: data.mainContent,\n * nestedTokens\n * })\n * }, lexer)\n * ```\n */\nexport function parseIndentedBlocks(\n src: string,\n config: BlockParserConfig,\n lexer: {\n inlineTokens: (src: string) => any[]\n blockTokens: (src: string) => any[]\n },\n):\n | {\n items: ParsedBlock[]\n raw: string\n }\n | undefined {\n const lines = src.split('\\n')\n const items: ParsedBlock[] = []\n let totalRaw = ''\n let i = 0\n const baseIndentSize = config.baseIndentSize || 2\n\n while (i < lines.length) {\n const currentLine = lines[i]\n const itemMatch = currentLine.match(config.itemPattern)\n\n if (!itemMatch) {\n // Not a matching item - stop if we have items, otherwise this isn't our block type\n if (items.length > 0) {\n break\n } else if (currentLine.trim() === '') {\n i += 1\n totalRaw = `${totalRaw}${currentLine}\\n`\n continue\n } else {\n return undefined\n }\n }\n\n const itemData = config.extractItemData(itemMatch)\n const { indentLevel, mainContent } = itemData\n totalRaw = `${totalRaw}${currentLine}\\n`\n\n // Collect content for this item (including nested items)\n const itemContent = [mainContent] // Start with the main text\n i += 1\n\n // Look ahead for nested content (indented more than current item)\n while (i < lines.length) {\n const nextLine = lines[i]\n\n if (nextLine.trim() === '') {\n // Empty line - might be end of nested content\n const nextNonEmptyIndex = lines.slice(i + 1).findIndex(l => l.trim() !== '')\n if (nextNonEmptyIndex === -1) {\n // No more content\n break\n }\n\n const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex]\n const nextIndent = nextNonEmpty.match(/^(\\s*)/)?.[1]?.length || 0\n\n if (nextIndent > indentLevel) {\n // Nested content continues after empty line\n itemContent.push(nextLine)\n totalRaw = `${totalRaw}${nextLine}\\n`\n i += 1\n continue\n } else {\n // End of nested content\n break\n }\n }\n\n const nextIndent = nextLine.match(/^(\\s*)/)?.[1]?.length || 0\n\n if (nextIndent > indentLevel) {\n // This is nested content for the current item\n itemContent.push(nextLine)\n totalRaw = `${totalRaw}${nextLine}\\n`\n i += 1\n } else {\n // Same or less indentation - this belongs to parent level\n break\n }\n }\n\n // Parse nested content if present\n let nestedTokens: any[] | undefined\n const nestedContent = itemContent.slice(1)\n\n if (nestedContent.length > 0) {\n // Remove the base indentation from nested content\n const dedentedNested = nestedContent\n .map(nestedLine => nestedLine.slice(indentLevel + baseIndentSize)) // Remove base indent + 2 spaces\n .join('\\n')\n\n if (dedentedNested.trim()) {\n // Use custom nested parser if provided, otherwise fall back to default\n if (config.customNestedParser) {\n nestedTokens = config.customNestedParser(dedentedNested)\n } else {\n nestedTokens = lexer.blockTokens(dedentedNested)\n }\n }\n }\n\n // Create the token using the provided factory function\n const token = config.createToken(itemData, nestedTokens)\n items.push(token)\n }\n\n if (items.length === 0) {\n return undefined\n }\n\n return {\n items,\n raw: totalRaw,\n }\n}\n", "import type { JSONContent } from '@tiptap/core'\n\n/**\n * @fileoverview Utility functions for rendering nested content in markdown.\n *\n * This module provides reusable utilities for extensions that need to render\n * content with a prefix on the main line and properly indented nested content.\n */\n\n/**\n * Utility function for rendering content with a main line prefix and nested indented content.\n *\n * This function handles the common pattern of rendering content with:\n * 1. A main line with a prefix (like \"- \" for lists, \"> \" for blockquotes, etc.)\n * 2. Nested content that gets indented properly\n *\n * @param node - The ProseMirror node representing the content\n * @param h - The markdown renderer helper\n * @param prefixOrGenerator - Either a string prefix or a function that generates the prefix from context\n * @param ctx - Optional context object (used when prefixOrGenerator is a function)\n * @returns The rendered markdown string\n *\n * @example\n * ```ts\n * // For a bullet list item with static prefix\n * return renderNestedMarkdownContent(node, h, '- ')\n *\n * // For a task item with static prefix\n * const prefix = `- [${node.attrs?.checked ? 'x' : ' '}] `\n * return renderNestedMarkdownContent(node, h, prefix)\n *\n * // For a blockquote with static prefix\n * return renderNestedMarkdownContent(node, h, '> ')\n *\n * // For content with dynamic prefix based on context\n * return renderNestedMarkdownContent(node, h, ctx => {\n * if (ctx.parentType === 'orderedList') {\n * return `${ctx.index + 1}. `\n * }\n * return '- '\n * }, ctx)\n *\n * // Custom extension example\n * const CustomContainer = Node.create({\n * name: 'customContainer',\n * // ... other config\n * markdown: {\n * render: (node, h) => {\n * const type = node.attrs?.type || 'info'\n * return renderNestedMarkdownContent(node, h, `[${type}] `)\n * }\n * }\n * })\n * ```\n */\nexport function renderNestedMarkdownContent(\n node: JSONContent,\n h: {\n renderChildren: (nodes: JSONContent[]) => string\n indent: (text: string) => string\n },\n prefixOrGenerator: string | ((ctx: any) => string),\n ctx?: any,\n): string {\n if (!node || !Array.isArray(node.content)) {\n return ''\n }\n\n // Determine the prefix based on the input\n const prefix = typeof prefixOrGenerator === 'function' ? prefixOrGenerator(ctx) : prefixOrGenerator\n\n const [content, ...children] = node.content\n\n // Render the main content (typically a paragraph)\n const mainContent = h.renderChildren([content])\n const output = [`${prefix}${mainContent}`]\n\n // Handle nested children with proper indentation\n if (children && children.length > 0) {\n children.forEach(child => {\n const childContent = h.renderChildren([child])\n if (childContent) {\n // Split the child content by lines and indent each line\n const indentedChild = childContent\n .split('\\n')\n .map(line => (line ? h.indent(line) : ''))\n .join('\\n')\n output.push(indentedChild)\n }\n })\n }\n\n return output.join('\\n')\n}\n", "import type { Mark } from '@tiptap/pm/model'\nimport type { ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor } from './Editor.js'\nimport type { MarkViewProps, MarkViewRendererOptions } from './types.js'\nimport { isAndroid, isiOS } from './utilities/index.js'\n\nexport function updateMarkViewAttributes(checkMark: Mark, editor: Editor, attrs: Record = {}): void {\n const { state } = editor\n const { doc, tr } = state\n const thisMark = checkMark\n\n doc.descendants((node, pos) => {\n const from = tr.mapping.map(pos)\n const to = tr.mapping.map(pos) + node.nodeSize\n let foundMark: Mark | null = null\n\n // find the mark on the current node\n node.marks.forEach(mark => {\n if (mark !== thisMark) {\n return false\n }\n\n foundMark = mark\n })\n\n if (!foundMark) {\n return\n }\n\n // check if we need to update given the attributes\n let needsUpdate = false\n Object.keys(attrs).forEach(k => {\n if (attrs[k] !== foundMark!.attrs[k]) {\n needsUpdate = true\n }\n })\n\n if (needsUpdate) {\n const updatedMark = checkMark.type.create({\n ...checkMark.attrs,\n ...attrs,\n })\n\n tr.removeMark(from, to, checkMark.type)\n tr.addMark(from, to, updatedMark)\n }\n })\n\n if (tr.docChanged) {\n editor.view.dispatch(tr)\n }\n}\n\nexport class MarkView {\n component: Component\n editor: Editor\n options: Options\n mark: MarkViewProps['mark']\n HTMLAttributes: MarkViewProps['HTMLAttributes']\n\n constructor(component: Component, props: MarkViewProps, options?: Partial) {\n this.component = component\n this.editor = props.editor\n this.options = { ...options } as Options\n this.mark = props.mark\n this.HTMLAttributes = props.HTMLAttributes\n }\n\n get dom(): HTMLElement {\n return this.editor.view.dom\n }\n\n get contentDOM(): HTMLElement | null {\n return null\n }\n\n /**\n * Update the attributes of the mark in the document.\n * @param attrs The attributes to update.\n */\n updateAttributes(attrs: Record, checkMark?: Mark): void {\n updateMarkViewAttributes(checkMark || this.mark, this.editor, attrs)\n }\n\n ignoreMutation(mutation: ViewMutationRecord): boolean {\n if (!this.dom || !this.contentDOM) {\n return true\n }\n\n if (typeof this.options.ignoreMutation === 'function') {\n return this.options.ignoreMutation({ mutation })\n }\n\n if (mutation.type === 'selection') {\n return false\n }\n\n if (\n this.dom.contains(mutation.target) &&\n mutation.type === 'childList' &&\n (isiOS() || isAndroid()) &&\n this.editor.isFocused\n ) {\n const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)] as HTMLElement[]\n\n if (changedNodes.every(node => node.isContentEditable)) {\n return false\n }\n }\n\n if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n return true\n }\n\n if (this.contentDOM.contains(mutation.target)) {\n return false\n }\n\n return true\n }\n}\n", "import type { DOMOutputSpec, Node as ProseMirrorNode, NodeSpec, NodeType } from '@tiptap/pm/model'\n\nimport type { Editor } from './Editor.js'\nimport type { ExtendableConfig } from './Extendable.js'\nimport { Extendable } from './Extendable.js'\nimport type { Attributes, NodeViewRenderer, ParentConfig } from './types.js'\n\nexport interface NodeConfig\n extends ExtendableConfig, NodeType> {\n /**\n * Node View\n */\n addNodeView?:\n | ((this: {\n name: string\n options: Options\n storage: Storage\n editor: Editor\n type: NodeType\n parent: ParentConfig>['addNodeView']\n }) => NodeViewRenderer | null)\n | null\n\n /**\n * Defines if this node should be a top level node (doc)\n * @default false\n * @example true\n */\n topNode?: boolean\n\n /**\n * The content expression for this node, as described in the [schema\n * guide](/docs/guide/#schema.content_expressions). When not given,\n * the node does not allow any content.\n *\n * You can read more about it on the Prosemirror documentation here\n * @see https://prosemirror.net/docs/guide/#schema.content_expressions\n * @default undefined\n * @example content: 'block+'\n * @example content: 'headline paragraph block*'\n */\n content?:\n | NodeSpec['content']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['content']\n editor?: Editor\n }) => NodeSpec['content'])\n\n /**\n * The marks that are allowed inside of this node. May be a\n * space-separated string referring to mark names or groups, `\"_\"`\n * to explicitly allow all marks, or `\"\"` to disallow marks. When\n * not given, nodes with inline content default to allowing all\n * marks, other nodes default to not allowing marks.\n *\n * @example marks: 'strong em'\n */\n marks?:\n | NodeSpec['marks']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['marks']\n editor?: Editor\n }) => NodeSpec['marks'])\n\n /**\n * The group or space-separated groups to which this node belongs,\n * which can be referred to in the content expressions for the\n * schema.\n *\n * By default Tiptap uses the groups 'block' and 'inline' for nodes. You\n * can also use custom groups if you want to group specific nodes together\n * and handle them in your schema.\n * @example group: 'block'\n * @example group: 'inline'\n * @example group: 'customBlock' // this uses a custom group\n */\n group?:\n | NodeSpec['group']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['group']\n editor?: Editor\n }) => NodeSpec['group'])\n\n /**\n * Should be set to true for inline nodes. (Implied for text nodes.)\n */\n inline?:\n | NodeSpec['inline']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['inline']\n editor?: Editor\n }) => NodeSpec['inline'])\n\n /**\n * Can be set to true to indicate that, though this isn't a [leaf\n * node](https://prosemirror.net/docs/ref/#model.NodeType.isLeaf), it doesn't have directly editable\n * content and should be treated as a single unit in the view.\n *\n * @example atom: true\n */\n atom?:\n | NodeSpec['atom']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['atom']\n editor?: Editor\n }) => NodeSpec['atom'])\n\n /**\n * Controls whether nodes of this type can be selected as a [node\n * selection](https://prosemirror.net/docs/ref/#state.NodeSelection). Defaults to true for non-text\n * nodes.\n *\n * @default true\n * @example selectable: false\n */\n selectable?:\n | NodeSpec['selectable']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['selectable']\n editor?: Editor\n }) => NodeSpec['selectable'])\n\n /**\n * Determines whether nodes of this type can be dragged without\n * being selected. Defaults to false.\n *\n * @default: false\n * @example: draggable: true\n */\n draggable?:\n | NodeSpec['draggable']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['draggable']\n editor?: Editor\n }) => NodeSpec['draggable'])\n\n /**\n * Can be used to indicate that this node contains code, which\n * causes some commands to behave differently.\n */\n code?:\n | NodeSpec['code']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['code']\n editor?: Editor\n }) => NodeSpec['code'])\n\n /**\n * Controls way whitespace in this a node is parsed. The default is\n * `\"normal\"`, which causes the [DOM parser](https://prosemirror.net/docs/ref/#model.DOMParser) to\n * collapse whitespace in normal mode, and normalize it (replacing\n * newlines and such with spaces) otherwise. `\"pre\"` causes the\n * parser to preserve spaces inside the node. When this option isn't\n * given, but [`code`](https://prosemirror.net/docs/ref/#model.NodeSpec.code) is true, `whitespace`\n * will default to `\"pre\"`. Note that this option doesn't influence\n * the way the node is rendered—that should be handled by `toDOM`\n * and/or styling.\n */\n whitespace?:\n | NodeSpec['whitespace']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['whitespace']\n editor?: Editor\n }) => NodeSpec['whitespace'])\n\n /**\n * Allows a **single** node to be set as linebreak equivalent (e.g. hardBreak).\n * When converting between block types that have whitespace set to \"pre\"\n * and don't support the linebreak node (e.g. codeBlock) and other block types\n * that do support the linebreak node (e.g. paragraphs) - this node will be used\n * as the linebreak instead of stripping the newline.\n *\n * See [linebreakReplacement](https://prosemirror.net/docs/ref/#model.NodeSpec.linebreakReplacement).\n */\n linebreakReplacement?:\n | NodeSpec['linebreakReplacement']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['linebreakReplacement']\n editor?: Editor\n }) => NodeSpec['linebreakReplacement'])\n\n /**\n * When enabled, enables both\n * [`definingAsContext`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext) and\n * [`definingForContent`](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).\n *\n * @default false\n * @example isolating: true\n */\n defining?:\n | NodeSpec['defining']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['defining']\n editor?: Editor\n }) => NodeSpec['defining'])\n\n /**\n * When enabled (default is false), the sides of nodes of this type\n * count as boundaries that regular editing operations, like\n * backspacing or lifting, won't cross. An example of a node that\n * should probably have this enabled is a table cell.\n */\n isolating?:\n | NodeSpec['isolating']\n | ((this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['isolating']\n editor?: Editor\n }) => NodeSpec['isolating'])\n\n /**\n * Associates DOM parser information with this node, which can be\n * used by [`DOMParser.fromSchema`](https://prosemirror.net/docs/ref/#model.DOMParser^fromSchema) to\n * automatically derive a parser. The `node` field in the rules is\n * implied (the name of this node will be filled in automatically).\n * If you supply your own parser, you do not need to also specify\n * parsing rules in your schema.\n *\n * @example parseHTML: [{ tag: 'div', attrs: { 'data-id': 'my-block' } }]\n */\n parseHTML?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['parseHTML']\n editor?: Editor\n }) => NodeSpec['parseDOM']\n\n /**\n * A description of a DOM structure. Can be either a string, which is\n * interpreted as a text node, a DOM node, which is interpreted as\n * itself, a `{dom, contentDOM}` object, or an array.\n *\n * An array describes a DOM element. The first value in the array\n * should be a string—the name of the DOM element, optionally prefixed\n * by a namespace URL and a space. If the second element is plain\n * object, it is interpreted as a set of attributes for the element.\n * Any elements after that (including the 2nd if it's not an attribute\n * object) are interpreted as children of the DOM elements, and must\n * either be valid `DOMOutputSpec` values, or the number zero.\n *\n * The number zero (pronounced “hole”) is used to indicate the place\n * where a node's child nodes should be inserted. If it occurs in an\n * output spec, it should be the only child element in its parent\n * node.\n *\n * @example toDOM: ['div[data-id=\"my-block\"]', { class: 'my-block' }, 0]\n */\n renderHTML?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['renderHTML']\n editor?: Editor\n },\n props: {\n node: ProseMirrorNode\n HTMLAttributes: Record\n },\n ) => DOMOutputSpec)\n | null\n\n /**\n * renders the node as text\n * @example renderText: () => 'foo\n */\n renderText?:\n | ((\n this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['renderText']\n editor?: Editor\n },\n props: {\n node: ProseMirrorNode\n pos: number\n parent: ProseMirrorNode\n index: number\n },\n ) => string)\n | null\n\n /**\n * Add attributes to the node\n * @example addAttributes: () => ({ class: 'foo' })\n */\n addAttributes?: (this: {\n name: string\n options: Options\n storage: Storage\n parent: ParentConfig>['addAttributes']\n editor?: Editor\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n }) => Attributes | {}\n}\n\n/**\n * The Node class is used to create custom node extensions.\n * @see https://tiptap.dev/api/extensions#create-a-new-extension\n */\nexport class Node extends Extendable> {\n type = 'node'\n\n /**\n * Create a new Node instance\n * @param config - Node configuration object or a function that returns a configuration object\n */\n static create(config: Partial> | (() => Partial>) = {}) {\n // If the config is a function, execute it to get the configuration object\n const resolvedConfig = typeof config === 'function' ? config() : config\n return new Node(resolvedConfig)\n }\n\n configure(options?: Partial) {\n return super.configure(options) as Node\n }\n\n extend<\n ExtendedOptions = Options,\n ExtendedStorage = Storage,\n ExtendedConfig extends NodeConfig = NodeConfig,\n >(\n extendedConfig?:\n | (() => Partial)\n | (Partial &\n ThisType<{\n name: string\n options: ExtendedOptions\n storage: ExtendedStorage\n editor: Editor\n type: NodeType\n }>),\n ): Node {\n // If the extended config is a function, execute it to get the configuration object\n const resolvedConfig = typeof extendedConfig === 'function' ? extendedConfig() : extendedConfig\n return super.extend(resolvedConfig) as Node\n }\n}\n", "import { NodeSelection } from '@tiptap/pm/state'\nimport type { NodeView as ProseMirrorNodeView, ViewMutationRecord } from '@tiptap/pm/view'\n\nimport type { Editor as CoreEditor } from './Editor.js'\nimport type { DecorationWithType, NodeViewRendererOptions, NodeViewRendererProps } from './types.js'\nimport { isAndroid } from './utilities/isAndroid.js'\nimport { isiOS } from './utilities/isiOS.js'\n\n/**\n * Node views are used to customize the rendered DOM structure of a node.\n * @see https://tiptap.dev/guide/node-views\n */\nexport class NodeView<\n Component,\n NodeEditor extends CoreEditor = CoreEditor,\n Options extends NodeViewRendererOptions = NodeViewRendererOptions,\n> implements ProseMirrorNodeView\n{\n component: Component\n\n editor: NodeEditor\n\n options: Options\n\n extension: NodeViewRendererProps['extension']\n\n node: NodeViewRendererProps['node']\n\n decorations: NodeViewRendererProps['decorations']\n\n innerDecorations: NodeViewRendererProps['innerDecorations']\n\n view: NodeViewRendererProps['view']\n\n getPos: NodeViewRendererProps['getPos']\n\n HTMLAttributes: NodeViewRendererProps['HTMLAttributes']\n\n isDragging = false\n\n constructor(component: Component, props: NodeViewRendererProps, options?: Partial) {\n this.component = component\n this.editor = props.editor as NodeEditor\n this.options = {\n stopEvent: null,\n ignoreMutation: null,\n ...options,\n } as Options\n this.extension = props.extension\n this.node = props.node\n this.decorations = props.decorations as DecorationWithType[]\n this.innerDecorations = props.innerDecorations\n this.view = props.view\n this.HTMLAttributes = props.HTMLAttributes\n this.getPos = props.getPos\n this.mount()\n }\n\n mount() {\n // eslint-disable-next-line\n return\n }\n\n get dom(): HTMLElement {\n return this.editor.view.dom as HTMLElement\n }\n\n get contentDOM(): HTMLElement | null {\n return null\n }\n\n onDragStart(event: DragEvent) {\n const { view } = this.editor\n const target = event.target as HTMLElement\n\n // get the drag handle element\n // `closest` is not available for text nodes so we may have to use its parent\n const dragHandle =\n target.nodeType === 3 ? target.parentElement?.closest('[data-drag-handle]') : target.closest('[data-drag-handle]')\n\n if (!this.dom || this.contentDOM?.contains(target) || !dragHandle) {\n return\n }\n\n let x = 0\n let y = 0\n\n // calculate offset for drag element if we use a different drag handle element\n if (this.dom !== dragHandle) {\n const domBox = this.dom.getBoundingClientRect()\n const handleBox = dragHandle.getBoundingClientRect()\n\n // In React, we have to go through nativeEvent to reach offsetX/offsetY.\n const offsetX = event.offsetX ?? (event as any).nativeEvent?.offsetX\n const offsetY = event.offsetY ?? (event as any).nativeEvent?.offsetY\n\n x = handleBox.x - domBox.x + offsetX\n y = handleBox.y - domBox.y + offsetY\n }\n\n const clonedNode = this.dom.cloneNode(true) as HTMLElement\n\n // Preserve the visual size of the original when using the clone as\n // the drag image.\n try {\n const domBox = this.dom.getBoundingClientRect()\n clonedNode.style.width = `${Math.round(domBox.width)}px`\n clonedNode.style.height = `${Math.round(domBox.height)}px`\n clonedNode.style.boxSizing = 'border-box'\n // Ensure the clone doesn't capture pointer events while offscreen\n clonedNode.style.pointerEvents = 'none'\n } catch {\n // ignore measurement errors (e.g. if element not in DOM)\n }\n\n // Some browsers (notably Safari) require the element passed to\n // setDragImage to be present in the DOM. Using a detached node can\n // cause the drag to immediately end.\n let dragImageWrapper: HTMLElement | null = null\n\n try {\n dragImageWrapper = document.createElement('div')\n dragImageWrapper.style.position = 'absolute'\n dragImageWrapper.style.top = '-9999px'\n dragImageWrapper.style.left = '-9999px'\n dragImageWrapper.style.pointerEvents = 'none'\n dragImageWrapper.appendChild(clonedNode)\n document.body.appendChild(dragImageWrapper)\n\n event.dataTransfer?.setDragImage(clonedNode, x, y)\n } finally {\n // Remove the wrapper on the next tick so the browser can use the\n // element as the drag image. A 0ms timeout is enough in practice.\n if (dragImageWrapper) {\n setTimeout(() => {\n try {\n dragImageWrapper?.remove()\n } catch {\n // ignore removal errors\n }\n }, 0)\n }\n }\n\n const pos = this.getPos()\n\n if (typeof pos !== 'number') {\n return\n }\n // we need to tell ProseMirror that we want to move the whole node\n // so we create a NodeSelection\n const selection = NodeSelection.create(view.state.doc, pos)\n const transaction = view.state.tr.setSelection(selection)\n\n view.dispatch(transaction)\n }\n\n stopEvent(event: Event) {\n if (!this.dom) {\n return false\n }\n\n if (typeof this.options.stopEvent === 'function') {\n return this.options.stopEvent({ event })\n }\n\n const target = event.target as HTMLElement\n const isInElement = this.dom.contains(target) && !this.contentDOM?.contains(target)\n\n // any event from child nodes should be handled by ProseMirror\n if (!isInElement) {\n return false\n }\n\n const isDragEvent = event.type.startsWith('drag')\n const isDropEvent = event.type === 'drop'\n const isInput = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName) || target.isContentEditable\n\n // any input event within node views should be ignored by ProseMirror\n if (isInput && !isDropEvent && !isDragEvent) {\n return true\n }\n\n const { isEditable } = this.editor\n const { isDragging } = this\n const isDraggable = !!this.node.type.spec.draggable\n const isSelectable = NodeSelection.isSelectable(this.node)\n const isCopyEvent = event.type === 'copy'\n const isPasteEvent = event.type === 'paste'\n const isCutEvent = event.type === 'cut'\n const isClickEvent = event.type === 'mousedown'\n\n // ProseMirror tries to drag selectable nodes\n // even if `draggable` is set to `false`\n // this fix prevents that\n if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) {\n event.preventDefault()\n }\n\n if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) {\n event.preventDefault()\n return false\n }\n\n // we have to store that dragging started\n if (isDraggable && isEditable && !isDragging && isClickEvent) {\n const dragHandle = target.closest('[data-drag-handle]')\n const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle))\n\n if (isValidDragHandle) {\n this.isDragging = true\n\n document.addEventListener(\n 'dragend',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n\n document.addEventListener(\n 'drop',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n\n document.addEventListener(\n 'mouseup',\n () => {\n this.isDragging = false\n },\n { once: true },\n )\n }\n }\n\n // these events are handled by prosemirror\n if (isDragging || isDropEvent || isCopyEvent || isPasteEvent || isCutEvent || (isClickEvent && isSelectable)) {\n return false\n }\n\n return true\n }\n\n /**\n * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.\n * @return `false` if the editor should re-read the selection or re-parse the range around the mutation\n * @return `true` if it can safely be ignored.\n */\n ignoreMutation(mutation: ViewMutationRecord) {\n if (!this.dom || !this.contentDOM) {\n return true\n }\n\n if (typeof this.options.ignoreMutation === 'function') {\n return this.options.ignoreMutation({ mutation })\n }\n\n // a leaf/atom node is like a black box for ProseMirror\n // and should be fully handled by the node view\n if (this.node.isLeaf || this.node.isAtom) {\n return true\n }\n\n // ProseMirror should handle any selections\n if (mutation.type === 'selection') {\n return false\n }\n\n // try to prevent a bug on iOS and Android that will break node views on enter\n // this is because ProseMirror can’t preventDispatch on enter\n // this will lead to a re-render of the node view on enter\n // see: https://github.com/ueberdosis/tiptap/issues/1214\n // see: https://github.com/ueberdosis/tiptap/issues/2534\n if (\n this.dom.contains(mutation.target) &&\n mutation.type === 'childList' &&\n (isiOS() || isAndroid()) &&\n this.editor.isFocused\n ) {\n const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)] as HTMLElement[]\n\n // we’ll check if every changed node is contentEditable\n // to make sure it’s probably mutated by ProseMirror\n if (changedNodes.every(node => node.isContentEditable)) {\n return false\n }\n }\n\n // we will allow mutation contentDOM with attributes\n // so we can for example adding classes within our node view\n if (this.contentDOM === mutation.target && mutation.type === 'attributes') {\n return true\n }\n\n // ProseMirror should handle any changes within contentDOM\n if (this.contentDOM.contains(mutation.target)) {\n return false\n }\n\n return true\n }\n\n /**\n * Update the attributes of the prosemirror node.\n */\n updateAttributes(attributes: Record): void {\n this.editor.commands.command(({ tr }) => {\n const pos = this.getPos()\n\n if (typeof pos !== 'number') {\n return false\n }\n\n tr.setNodeMarkup(pos, undefined, {\n ...this.node.attrs,\n ...attributes,\n })\n\n return true\n })\n }\n\n /**\n * Delete the node.\n */\n deleteNode(): void {\n const from = this.getPos()\n\n if (typeof from !== 'number') {\n return\n }\n const to = from + this.node.nodeSize\n\n this.editor.commands.deleteRange({ from, to })\n }\n}\n", "import type { MarkType } from '@tiptap/pm/model'\n\nimport { getMarksBetween } from '../helpers/getMarksBetween.js'\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray } from '../types.js'\nimport { callOrReturn } from '../utilities/callOrReturn.js'\n\n/**\n * Build an paste rule that adds a mark when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function markPasteRule(config: {\n find: PasteRuleFinder\n type: MarkType\n getAttributes?:\n | Record\n | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record)\n | false\n | null\n}) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match, pasteEvent }) => {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const { tr } = state\n const captureGroup = match[match.length - 1]\n const fullMatch = match[0]\n let markEnd = range.to\n\n if (captureGroup) {\n const startSpaces = fullMatch.search(/\\S/)\n const textStart = range.from + fullMatch.indexOf(captureGroup)\n const textEnd = textStart + captureGroup.length\n\n const excludedMarks = getMarksBetween(range.from, range.to, state.doc)\n .filter(item => {\n // @ts-ignore\n const excluded = item.mark.type.excluded as MarkType[]\n\n return excluded.find(type => type === config.type && type !== item.mark.type)\n })\n .filter(item => item.to > textStart)\n\n if (excludedMarks.length) {\n return null\n }\n\n if (textEnd < range.to) {\n tr.delete(textEnd, range.to)\n }\n\n if (textStart > range.from) {\n tr.delete(range.from + startSpaces, textStart)\n }\n\n markEnd = range.from + startSpaces + captureGroup.length\n\n tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}))\n\n tr.removeStoredMark(config.type)\n }\n },\n })\n}\n", "import type { NodeType } from '@tiptap/pm/model'\n\nimport type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\nimport type { ExtendedRegExpMatchArray, JSONContent } from '../types.js'\nimport { callOrReturn } from '../utilities/index.js'\n\n/**\n * Build an paste rule that adds a node when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/api/paste-rules\n */\nexport function nodePasteRule(config: {\n find: PasteRuleFinder\n type: NodeType\n getAttributes?:\n | Record\n | ((match: ExtendedRegExpMatchArray, event: ClipboardEvent) => Record)\n | false\n | null\n getContent?: JSONContent[] | ((attrs: Record) => JSONContent[]) | false | null\n}) {\n return new PasteRule({\n find: config.find,\n handler({ match, chain, range, pasteEvent }) {\n const attributes = callOrReturn(config.getAttributes, undefined, match, pasteEvent)\n const content = callOrReturn(config.getContent, undefined, attributes)\n\n if (attributes === false || attributes === null) {\n return null\n }\n\n const node = { type: config.type.name, attrs: attributes } as JSONContent\n\n if (content) {\n node.content = content\n }\n\n if (match.input) {\n chain().deleteRange(range).insertContentAt(range.from, node)\n }\n },\n })\n}\n", "import type { PasteRuleFinder } from '../PasteRule.js'\nimport { PasteRule } from '../PasteRule.js'\n\n/**\n * Build an paste rule that replaces text when the\n * matched text is pasted into it.\n * @see https://tiptap.dev/docs/editor/extensions/custom-extensions/extend-existing#paste-rules\n */\nexport function textPasteRule(config: { find: PasteRuleFinder; replace: string }) {\n return new PasteRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace\n let start = range.from\n const end = range.to\n\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1])\n\n insert += match[0].slice(offset + match[1].length)\n start += offset\n\n const cutOff = start - end\n\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert\n start = end\n }\n }\n\n state.tr.insertText(insert, start, end)\n },\n })\n}\n", "import type { Transaction } from '@tiptap/pm/state'\n\nexport interface TrackerResult {\n position: number\n deleted: boolean\n}\n\nexport class Tracker {\n transaction: Transaction\n\n currentStep: number\n\n constructor(transaction: Transaction) {\n this.transaction = transaction\n this.currentStep = this.transaction.steps.length\n }\n\n map(position: number): TrackerResult {\n let deleted = false\n\n const mappedPosition = this.transaction.steps.slice(this.currentStep).reduce((newPosition, step) => {\n const mapResult = step.getMap().mapResult(newPosition)\n\n if (mapResult.deleted) {\n deleted = true\n }\n\n return mapResult.pos\n }, position)\n\n return {\n position: mappedPosition,\n deleted,\n }\n }\n}\n"], + "mappings": ";AAEA,SAAS,WAAW,SAAS;AAC3B,OAAK,UAAU;AACjB;AAEA,WAAW,YAAY;AAAA,EACrB,aAAa;AAAA,EAEb,MAAM,SAAS,KAAK;AAClB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,QAAQ,KAAK;AAC5C,UAAI,KAAK,QAAQ,CAAC,MAAM,IAAK,QAAO;AACtC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,KAAK,SAAS,KAAK;AACjB,QAAIA,SAAQ,KAAK,KAAK,GAAG;AACzB,WAAOA,UAAS,KAAK,SAAY,KAAK,QAAQA,SAAQ,CAAC;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,SAAS,KAAK,OAAO,QAAQ;AACnC,QAAI,OAAO,UAAU,UAAU,MAAM,KAAK,OAAO,MAAM,IAAI;AAC3D,QAAIA,SAAQ,KAAK,KAAK,GAAG,GAAG,UAAU,KAAK,QAAQ,MAAM;AACzD,QAAIA,UAAS,IAAI;AACf,cAAQ,KAAK,UAAU,KAAK,KAA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,SAAS,OAAO;AACpB,UAAI,QAAQ,MAAM;AAClB,YAAM,MAAM,MAAM;AAElB,UAAI,MAAM,CAAC,GAAG;AACZ,cAAM,SAAS,MAAM,CAAC,EAAE,YAAY,MAAM,CAAC,CAAC;AAE5C,kBAAU,MAAM,CAAC,EAAE,MAAM,SAAS,MAAM,CAAC,EAAE,MAAM;AACjD,iBAAS;AAET,cAAM,SAAS,QAAQ;AAEvB,YAAI,SAAS,GAAG;AACd,mBAAS,MAAM,CAAC,EAAE,MAAM,SAAS,QAAQ,MAAM,IAAI;AACnD,kBAAQ;QACV;MACF;AAEA,YAAM,GAAG,WAAW,QAAQ,OAAO,GAAG;IACxC;EACF,CAAC;AACH;AC1BO,IAAM,UAAN,MAAc;EAKnB,YAAY,aAA0B;AACpC,SAAK,cAAc;AACnB,SAAK,cAAc,KAAK,YAAY,MAAM;EAC5C;EAEA,IAAI,UAAiC;AACnC,QAAI,UAAU;AAEd,UAAM,iBAAiB,KAAK,YAAY,MAAM,MAAM,KAAK,WAAW,EAAE,OAAO,CAAC,aAAa,SAAS;AAClG,YAAM,YAAY,KAAK,OAAO,EAAE,UAAU,WAAW;AAErD,UAAI,UAAU,SAAS;AACrB,kBAAU;MACZ;AAEA,aAAO,UAAU;IACnB,GAAG,QAAQ;AAEX,WAAO;MACL,UAAU;MACV;IACF;EACF;AACF;", + "names": ["found", "first", "copy", "found", "_Mark", "doc", "_Node", "base", "i", "type", "nfa", "edge", "expr", "node", "states", "name", "mark", "style", "wrap", "space", "del", "doc", "parent", "found", "style", "base", "index", "joinable", "first", "wrap", "matches", "match", "type", "close", "TransformError", "found", "doc", "empty", "lift", "first", "wrap", "setBlockType", "doc", "wrap", "found", "first", "doc", "mac", "first", "i", "enter", "base", "wrap", "copy", "spec", "found", "preMatch", "matches", "empty", "dom", "event", "handlers", "sel", "cut", "NodeType", "oldOffset", "anchor", "found", "prop", "mac", "ie", "mac", "windows", "shift", "copy", "doc", "command", "run", "createParagraphNear", "deleteRange", "deleteSelection", "exitCode", "joinBackward", "joinDown", "joinForward", "joinTextblockBackward", "joinTextblockForward", "joinUp", "lift", "liftEmptyBlock", "liftListItem", "newlineInCode", "selectAll", "selectNodeBackward", "selectNodeForward", "selectParentNode", "selectTextblockEnd", "selectTextblockStart", "sinkListItem", "splitBlock", "wrapIn", "wrapInList", "keys", "mark", "TextSelection", "selectionToInsertionEnd", "Selection", "Fragment", "isTextSelection", "joinPoint", "originalCommand", "normalizeKeyName", "shift", "empty", "isActive", "document", "defaultBlockAt", "style", "Schema", "DOMParser", "getText", "Node", "node", "output", "range", "parentNode", "setBlockType", "NodeSelection", "first", "wrap", "newNextTypeAttributes", "nextType", "canSplit", "Mark", "removeMark", "matches", "handlers", "Plugin", "from", "to", "_a", "_b", "_c", "PluginKey", "tr", "isInline", "focus", "blur", "canJoin", "constrainedWidth", "constrainedHeight", "parseAttributes", "serializeAttributes", "h", "nextIndent"] +} diff --git a/frontend/node_modules/@floating-ui/core/LICENSE b/frontend/node_modules/@floating-ui/core/LICENSE new file mode 100644 index 00000000..639cdc6c --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2021-present Floating UI 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/@floating-ui/core/README.md b/frontend/node_modules/@floating-ui/core/README.md new file mode 100644 index 00000000..c4b69b2e --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/README.md @@ -0,0 +1,4 @@ +# @floating-ui/core + +This is the platform-agnostic core of Floating UI, exposing the main +`computePosition` function but no platform interface logic. diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs new file mode 100644 index 00000000..f82eeb1a --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.browser.min.mjs @@ -0,0 +1 @@ +const t=["top","right","bottom","left"],e=["start","end"],n=t.reduce(((t,n)=>t.concat(n,n+"-"+e[0],n+"-"+e[1])),[]),r=Math.min,o=Math.max,i={left:"right",right:"left",bottom:"top",top:"bottom"},a={start:"end",end:"start"};function l(t,e,n){return o(t,r(e,n))}function s(t,e){return"function"==typeof t?t(e):t}function c(t){return t.split("-")[0]}function f(t){return t.split("-")[1]}function m(t){return"x"===t?"y":"x"}function u(t){return"y"===t?"height":"width"}const d=new Set(["top","bottom"]);function g(t){return d.has(c(t))?"y":"x"}function p(t){return m(g(t))}function h(t,e,n){void 0===n&&(n=!1);const r=f(t),o=p(t),i=u(o);let a="x"===o?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return e.reference[i]>e.floating[i]&&(a=R(a)),[a,R(a)]}function y(t){return t.replace(/start|end/g,(t=>a[t]))}const w=["left","right"],x=["right","left"],v=["top","bottom"],b=["bottom","top"];function A(t,e,n,r){const o=f(t);let i=function(t,e,n){switch(t){case"top":case"bottom":return n?e?x:w:e?w:x;case"left":case"right":return e?v:b;default:return[]}}(c(t),"start"===n,r);return o&&(i=i.map((t=>t+"-"+o)),e&&(i=i.concat(i.map(y)))),i}function R(t){return t.replace(/left|right|bottom|top/g,(t=>i[t]))}function O(t){return"number"!=typeof t?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(t):{top:t,right:t,bottom:t,left:t}}function D(t){const{x:e,y:n,width:r,height:o}=t;return{width:r,height:o,top:n,left:e,right:e+r,bottom:n+o,x:e,y:n}}function P(t,e,n){let{reference:r,floating:o}=t;const i=g(e),a=p(e),l=u(a),s=c(e),m="y"===i,d=r.x+r.width/2-o.width/2,h=r.y+r.height/2-o.height/2,y=r[l]/2-o[l]/2;let w;switch(s){case"top":w={x:d,y:r.y-o.height};break;case"bottom":w={x:d,y:r.y+r.height};break;case"right":w={x:r.x+r.width,y:h};break;case"left":w={x:r.x-o.width,y:h};break;default:w={x:r.x,y:r.y}}switch(f(e)){case"start":w[a]-=y*(n&&m?-1:1);break;case"end":w[a]+=y*(n&&m?-1:1)}return w}async function E(t,e){var n;void 0===e&&(e={});const{x:r,y:o,platform:i,rects:a,elements:l,strategy:c}=t,{boundary:f="clippingAncestors",rootBoundary:m="viewport",elementContext:u="floating",altBoundary:d=!1,padding:g=0}=s(e,t),p=O(g),h=l[d?"floating"===u?"reference":"floating":u],y=D(await i.getClippingRect({element:null==(n=await(null==i.isElement?void 0:i.isElement(h)))||n?h:h.contextElement||await(null==i.getDocumentElement?void 0:i.getDocumentElement(l.floating)),boundary:f,rootBoundary:m,strategy:c})),w="floating"===u?{x:r,y:o,width:a.floating.width,height:a.floating.height}:a.reference,x=await(null==i.getOffsetParent?void 0:i.getOffsetParent(l.floating)),v=await(null==i.isElement?void 0:i.isElement(x))&&await(null==i.getScale?void 0:i.getScale(x))||{x:1,y:1},b=D(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:w,offsetParent:x,strategy:c}):w);return{top:(y.top-b.top+p.top)/v.y,bottom:(b.bottom-y.bottom+p.bottom)/v.y,left:(y.left-b.left+p.left)/v.x,right:(b.right-y.right+p.right)/v.x}}const T=async(t,e,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:a}=n,l=i.filter(Boolean),s=await(null==a.isRTL?void 0:a.isRTL(e));let c=await a.getElementRects({reference:t,floating:e,strategy:o}),{x:f,y:m}=P(c,r,s),u=r,d={},g=0;for(let n=0;n({name:"arrow",options:t,async fn(e){const{x:n,y:o,placement:i,rects:a,platform:c,elements:m,middlewareData:d}=e,{element:g,padding:h=0}=s(t,e)||{};if(null==g)return{};const y=O(h),w={x:n,y:o},x=p(i),v=u(x),b=await c.getDimensions(g),A="y"===x,R=A?"top":"left",D=A?"bottom":"right",P=A?"clientHeight":"clientWidth",E=a.reference[v]+a.reference[x]-w[x]-a.floating[v],T=w[x]-a.reference[x],L=await(null==c.getOffsetParent?void 0:c.getOffsetParent(g));let k=L?L[P]:0;k&&await(null==c.isElement?void 0:c.isElement(L))||(k=m.floating[P]||a.floating[v]);const B=E/2-T/2,C=k/2-b[v]/2-1,H=r(y[R],C),S=r(y[D],C),F=H,M=k-b[v]-S,V=k/2-b[v]/2+B,W=l(F,V,M),j=!d.arrow&&null!=f(i)&&V!==W&&a.reference[v]/2-(Vf(e)===t)),...n.filter((e=>f(e)!==t))]:n.filter((t=>c(t)===t))).filter((n=>!t||f(n)===t||!!e&&y(n)!==n))}(p||null,x,w):w,A=await u.detectOverflow(e,v),R=(null==(r=l.autoPlacement)?void 0:r.index)||0,O=b[R];if(null==O)return{};const D=h(O,a,await(null==u.isRTL?void 0:u.isRTL(d.floating)));if(m!==O)return{reset:{placement:b[0]}};const P=[A[c(O)],A[D[0]],A[D[1]]],E=[...(null==(o=l.autoPlacement)?void 0:o.overflows)||[],{placement:O,overflows:P}],T=b[R+1];if(T)return{data:{index:R+1,overflows:E},reset:{placement:T}};const L=E.map((t=>{const e=f(t.placement);return[t.placement,e&&g?t.overflows.slice(0,2).reduce(((t,e)=>t+e),0):t.overflows[0],t.overflows]})).sort(((t,e)=>t[1]-e[1])),k=(null==(i=L.filter((t=>t[2].slice(0,f(t[0])?2:3).every((t=>t<=0))))[0])?void 0:i[0])||L[0][0];return k!==m?{data:{index:R+1,overflows:E},reset:{placement:k}}:{}}}},B=function(t){return void 0===t&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:o,middlewareData:i,rects:a,initialPlacement:l,platform:f,elements:m}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:p,fallbackStrategy:w="bestFit",fallbackAxisSideDirection:x="none",flipAlignment:v=!0,...b}=s(t,e);if(null!=(n=i.arrow)&&n.alignmentOffset)return{};const O=c(o),D=g(l),P=c(l)===l,E=await(null==f.isRTL?void 0:f.isRTL(m.floating)),T=p||(P||!v?[R(l)]:function(t){const e=R(t);return[y(t),e,y(e)]}(l)),L="none"!==x;!p&&L&&T.push(...A(l,v,x,E));const k=[l,...T],B=await f.detectOverflow(e,b),C=[];let H=(null==(r=i.flip)?void 0:r.overflows)||[];if(u&&C.push(B[O]),d){const t=h(o,a,E);C.push(B[t[0]],B[t[1]])}if(H=[...H,{placement:o,overflows:C}],!C.every((t=>t<=0))){var S,F;const t=((null==(S=i.flip)?void 0:S.index)||0)+1,e=k[t];if(e){if(!("alignment"===d&&D!==g(e))||H.every((t=>g(t.placement)!==D||t.overflows[0]>0)))return{data:{index:t,overflows:H},reset:{placement:e}}}let n=null==(F=H.filter((t=>t.overflows[0]<=0)).sort(((t,e)=>t.overflows[1]-e.overflows[1]))[0])?void 0:F.placement;if(!n)switch(w){case"bestFit":{var M;const t=null==(M=H.filter((t=>{if(L){const e=g(t.placement);return e===D||"y"===e}return!0})).map((t=>[t.placement,t.overflows.filter((t=>t>0)).reduce(((t,e)=>t+e),0)])).sort(((t,e)=>t[1]-e[1]))[0])?void 0:M[0];t&&(n=t);break}case"initialPlacement":n=l}if(o!==n)return{reset:{placement:n}}}return{}}}};function C(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function H(e){return t.some((t=>e[t]>=0))}const S=function(t){return void 0===t&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n,platform:r}=e,{strategy:o="referenceHidden",...i}=s(t,e);switch(o){case"referenceHidden":{const t=C(await r.detectOverflow(e,{...i,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:t,referenceHidden:H(t)}}}case"escaped":{const t=C(await r.detectOverflow(e,{...i,altBoundary:!0}),n.floating);return{data:{escapedOffsets:t,escaped:H(t)}}}default:return{}}}}};function F(t){const e=r(...t.map((t=>t.left))),n=r(...t.map((t=>t.top)));return{x:e,y:n,width:o(...t.map((t=>t.right)))-e,height:o(...t.map((t=>t.bottom)))-n}}const M=function(t){return void 0===t&&(t={}),{name:"inline",options:t,async fn(e){const{placement:n,elements:i,rects:a,platform:l,strategy:f}=e,{padding:m=2,x:u,y:d}=s(t,e),p=Array.from(await(null==l.getClientRects?void 0:l.getClientRects(i.reference))||[]),h=function(t){const e=t.slice().sort(((t,e)=>t.y-e.y)),n=[];let r=null;for(let t=0;tr.height/2?n.push([o]):n[n.length-1].push(o),r=o}return n.map((t=>D(F(t))))}(p),y=D(F(p)),w=O(m);const x=await l.getElementRects({reference:{getBoundingClientRect:function(){if(2===h.length&&h[0].left>h[1].right&&null!=u&&null!=d)return h.find((t=>u>t.left-w.left&&ut.top-w.top&&d=2){if("y"===g(n)){const t=h[0],e=h[h.length-1],r="top"===c(n),o=t.top,i=e.bottom,a=r?t.left:e.left,l=r?t.right:e.right;return{top:o,bottom:i,left:a,right:l,width:l-a,height:i-o,x:a,y:o}}const t="left"===c(n),e=o(...h.map((t=>t.right))),i=r(...h.map((t=>t.left))),a=h.filter((n=>t?n.left===i:n.right===e)),l=a[0].top,s=a[a.length-1].bottom;return{top:l,bottom:s,left:i,right:e,width:e-i,height:s-l,x:i,y:l}}return y}},floating:i.floating,strategy:f});return a.reference.x!==x.reference.x||a.reference.y!==x.reference.y||a.reference.width!==x.reference.width||a.reference.height!==x.reference.height?{reset:{rects:x}}:{}}}},V=new Set(["left","top"]);const W=function(t){return void 0===t&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:o,y:i,placement:a,middlewareData:l}=e,m=await async function(t,e){const{placement:n,platform:r,elements:o}=t,i=await(null==r.isRTL?void 0:r.isRTL(o.floating)),a=c(n),l=f(n),m="y"===g(n),u=V.has(a)?-1:1,d=i&&m?-1:1,p=s(e,t);let{mainAxis:h,crossAxis:y,alignmentAxis:w}="number"==typeof p?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&"number"==typeof w&&(y="end"===l?-1*w:w),m?{x:y*d,y:h*u}:{x:h*u,y:y*d}}(e,t);return a===(null==(n=l.offset)?void 0:n.placement)&&null!=(r=l.arrow)&&r.alignmentOffset?{}:{x:o+m.x,y:i+m.y,data:{...m,placement:a}}}}},j=function(t){return void 0===t&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:o,platform:i}=e,{mainAxis:a=!0,crossAxis:f=!1,limiter:u={fn:t=>{let{x:e,y:n}=t;return{x:e,y:n}}},...d}=s(t,e),p={x:n,y:r},h=await i.detectOverflow(e,d),y=g(c(o)),w=m(y);let x=p[w],v=p[y];if(a){const t="y"===w?"bottom":"right";x=l(x+h["y"===w?"top":"left"],x,x-h[t])}if(f){const t="y"===y?"bottom":"right";v=l(v+h["y"===y?"top":"left"],v,v-h[t])}const b=u.fn({...e,[w]:x,[y]:v});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[w]:a,[y]:f}}}}}},z=function(t){return void 0===t&&(t={}),{options:t,fn(e){const{x:n,y:r,placement:o,rects:i,middlewareData:a}=e,{offset:l=0,mainAxis:f=!0,crossAxis:u=!0}=s(t,e),d={x:n,y:r},p=g(o),h=m(p);let y=d[h],w=d[p];const x=s(l,e),v="number"==typeof x?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(f){const t="y"===h?"height":"width",e=i.reference[h]-i.floating[t]+v.mainAxis,n=i.reference[h]+i.reference[t]-v.mainAxis;yn&&(y=n)}if(u){var b,A;const t="y"===h?"width":"height",e=V.has(c(o)),n=i.reference[p]-i.floating[t]+(e&&(null==(b=a.offset)?void 0:b[p])||0)+(e?0:v.crossAxis),r=i.reference[p]+i.reference[t]+(e?0:(null==(A=a.offset)?void 0:A[p])||0)-(e?v.crossAxis:0);wr&&(w=r)}return{[h]:y,[p]:w}}}},q=function(t){return void 0===t&&(t={}),{name:"size",options:t,async fn(e){var n,i;const{placement:a,rects:l,platform:m,elements:u}=e,{apply:d=()=>{},...p}=s(t,e),h=await m.detectOverflow(e,p),y=c(a),w=f(a),x="y"===g(a),{width:v,height:b}=l.floating;let A,R;"top"===y||"bottom"===y?(A=y,R=w===(await(null==m.isRTL?void 0:m.isRTL(u.floating))?"start":"end")?"left":"right"):(R=y,A="end"===w?"top":"bottom");const O=b-h.top-h.bottom,D=v-h.left-h.right,P=r(b-h[A],O),E=r(v-h[R],D),T=!e.middlewareData.shift;let L=P,k=E;if(null!=(n=e.middlewareData.shift)&&n.enabled.x&&(k=D),null!=(i=e.middlewareData.shift)&&i.enabled.y&&(L=O),T&&!w){const t=o(h.left,0),e=o(h.right,0),n=o(h.top,0),r=o(h.bottom,0);x?k=v-2*(0!==t||0!==e?t+e:o(h.left,h.right)):L=b-2*(0!==n||0!==r?n+r:o(h.top,h.bottom))}await d({...e,availableWidth:k,availableHeight:L});const B=await m.getDimensions(u.floating);return v!==B.width||b!==B.height?{reset:{rects:!0}}:{}}}};export{L as arrow,k as autoPlacement,T as computePosition,E as detectOverflow,B as flip,S as hide,M as inline,z as limitShift,W as offset,D as rectToClientRect,j as shift,q as size}; diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.browser.mjs b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.browser.mjs new file mode 100644 index 00000000..1a805534 --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.browser.mjs @@ -0,0 +1,1184 @@ +/** + * Custom positioning reference element. + * @see https://floating-ui.com/docs/virtual-elements + */ + +const sides = ['top', 'right', 'bottom', 'left']; +const alignments = ['start', 'end']; +const placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), []); +const min = Math.min; +const max = Math.max; +const oppositeSideMap = { + left: 'right', + right: 'left', + bottom: 'top', + top: 'bottom' +}; +const oppositeAlignmentMap = { + start: 'end', + end: 'start' +}; +function clamp(start, value, end) { + return max(start, min(value, end)); +} +function evaluate(value, param) { + return typeof value === 'function' ? value(param) : value; +} +function getSide(placement) { + return placement.split('-')[0]; +} +function getAlignment(placement) { + return placement.split('-')[1]; +} +function getOppositeAxis(axis) { + return axis === 'x' ? 'y' : 'x'; +} +function getAxisLength(axis) { + return axis === 'y' ? 'height' : 'width'; +} +const yAxisSides = /*#__PURE__*/new Set(['top', 'bottom']); +function getSideAxis(placement) { + return yAxisSides.has(getSide(placement)) ? 'y' : 'x'; +} +function getAlignmentAxis(placement) { + return getOppositeAxis(getSideAxis(placement)); +} +function getAlignmentSides(placement, rects, rtl) { + if (rtl === void 0) { + rtl = false; + } + const alignment = getAlignment(placement); + const alignmentAxis = getAlignmentAxis(placement); + const length = getAxisLength(alignmentAxis); + let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; + if (rects.reference[length] > rects.floating[length]) { + mainAlignmentSide = getOppositePlacement(mainAlignmentSide); + } + return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)]; +} +function getExpandedPlacements(placement) { + const oppositePlacement = getOppositePlacement(placement); + return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; +} +function getOppositeAlignmentPlacement(placement) { + return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); +} +const lrPlacement = ['left', 'right']; +const rlPlacement = ['right', 'left']; +const tbPlacement = ['top', 'bottom']; +const btPlacement = ['bottom', 'top']; +function getSideList(side, isStart, rtl) { + switch (side) { + case 'top': + case 'bottom': + if (rtl) return isStart ? rlPlacement : lrPlacement; + return isStart ? lrPlacement : rlPlacement; + case 'left': + case 'right': + return isStart ? tbPlacement : btPlacement; + default: + return []; + } +} +function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { + const alignment = getAlignment(placement); + let list = getSideList(getSide(placement), direction === 'start', rtl); + if (alignment) { + list = list.map(side => side + "-" + alignment); + if (flipAlignment) { + list = list.concat(list.map(getOppositeAlignmentPlacement)); + } + } + return list; +} +function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); +} +function expandPaddingObject(padding) { + return { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...padding + }; +} +function getPaddingObject(padding) { + return typeof padding !== 'number' ? expandPaddingObject(padding) : { + top: padding, + right: padding, + bottom: padding, + left: padding + }; +} +function rectToClientRect(rect) { + const { + x, + y, + width, + height + } = rect; + return { + width, + height, + top: y, + left: x, + right: x + width, + bottom: y + height, + x, + y + }; +} + +function computeCoordsFromPlacement(_ref, placement, rtl) { + let { + reference, + floating + } = _ref; + const sideAxis = getSideAxis(placement); + const alignmentAxis = getAlignmentAxis(placement); + const alignLength = getAxisLength(alignmentAxis); + const side = getSide(placement); + const isVertical = sideAxis === 'y'; + const commonX = reference.x + reference.width / 2 - floating.width / 2; + const commonY = reference.y + reference.height / 2 - floating.height / 2; + const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; + let coords; + switch (side) { + case 'top': + coords = { + x: commonX, + y: reference.y - floating.height + }; + break; + case 'bottom': + coords = { + x: commonX, + y: reference.y + reference.height + }; + break; + case 'right': + coords = { + x: reference.x + reference.width, + y: commonY + }; + break; + case 'left': + coords = { + x: reference.x - floating.width, + y: commonY + }; + break; + default: + coords = { + x: reference.x, + y: reference.y + }; + } + switch (getAlignment(placement)) { + case 'start': + coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); + break; + case 'end': + coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); + break; + } + return coords; +} + +/** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ +async function detectOverflow(state, options) { + var _await$platform$isEle; + if (options === void 0) { + options = {}; + } + const { + x, + y, + platform, + rects, + elements, + strategy + } = state; + const { + boundary = 'clippingAncestors', + rootBoundary = 'viewport', + elementContext = 'floating', + altBoundary = false, + padding = 0 + } = evaluate(options, state); + const paddingObject = getPaddingObject(padding); + const altContext = elementContext === 'floating' ? 'reference' : 'floating'; + const element = elements[altBoundary ? altContext : elementContext]; + const clippingClientRect = rectToClientRect(await platform.getClippingRect({ + element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), + boundary, + rootBoundary, + strategy + })); + const rect = elementContext === 'floating' ? { + x, + y, + width: rects.floating.width, + height: rects.floating.height + } : rects.reference; + const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); + const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { + x: 1, + y: 1 + } : { + x: 1, + y: 1 + }; + const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ + elements, + rect, + offsetParent, + strategy + }) : rect); + return { + top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, + bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, + left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, + right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x + }; +} + +/** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a given reference element. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ +const computePosition = async (reference, floating, config) => { + const { + placement = 'bottom', + strategy = 'absolute', + middleware = [], + platform + } = config; + const validMiddleware = middleware.filter(Boolean); + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); + let rects = await platform.getElementRects({ + reference, + floating, + strategy + }); + let { + x, + y + } = computeCoordsFromPlacement(rects, placement, rtl); + let statefulPlacement = placement; + let middlewareData = {}; + let resetCount = 0; + for (let i = 0; i < validMiddleware.length; i++) { + var _platform$detectOverf; + const { + name, + fn + } = validMiddleware[i]; + const { + x: nextX, + y: nextY, + data, + reset + } = await fn({ + x, + y, + initialPlacement: placement, + placement: statefulPlacement, + strategy, + middlewareData, + rects, + platform: { + ...platform, + detectOverflow: (_platform$detectOverf = platform.detectOverflow) != null ? _platform$detectOverf : detectOverflow + }, + elements: { + reference, + floating + } + }); + x = nextX != null ? nextX : x; + y = nextY != null ? nextY : y; + middlewareData = { + ...middlewareData, + [name]: { + ...middlewareData[name], + ...data + } + }; + if (reset && resetCount <= 50) { + resetCount++; + if (typeof reset === 'object') { + if (reset.placement) { + statefulPlacement = reset.placement; + } + if (reset.rects) { + rects = reset.rects === true ? await platform.getElementRects({ + reference, + floating, + strategy + }) : reset.rects; + } + ({ + x, + y + } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); + } + i = -1; + } + } + return { + x, + y, + placement: statefulPlacement, + strategy, + middlewareData + }; +}; + +/** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ +const arrow = options => ({ + name: 'arrow', + options, + async fn(state) { + const { + x, + y, + placement, + rects, + platform, + elements, + middlewareData + } = state; + // Since `element` is required, we don't Partial<> the type. + const { + element, + padding = 0 + } = evaluate(options, state) || {}; + if (element == null) { + return {}; + } + const paddingObject = getPaddingObject(padding); + const coords = { + x, + y + }; + const axis = getAlignmentAxis(placement); + const length = getAxisLength(axis); + const arrowDimensions = await platform.getDimensions(element); + const isYAxis = axis === 'y'; + const minProp = isYAxis ? 'top' : 'left'; + const maxProp = isYAxis ? 'bottom' : 'right'; + const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; + const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; + const startDiff = coords[axis] - rects.reference[axis]; + const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); + let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; + + // DOM platform can return `window` as the `offsetParent`. + if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { + clientSize = elements.floating[clientProp] || rects.floating[length]; + } + const centerToReference = endDiff / 2 - startDiff / 2; + + // If the padding is large enough that it causes the arrow to no longer be + // centered, modify the padding so that it is centered. + const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; + const minPadding = min(paddingObject[minProp], largestPossiblePadding); + const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); + + // Make sure the arrow doesn't overflow the floating element if the center + // point is outside the floating element's bounds. + const min$1 = minPadding; + const max = clientSize - arrowDimensions[length] - maxPadding; + const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; + const offset = clamp(min$1, center, max); + + // If the reference is small enough that the arrow's padding causes it to + // to point to nothing for an aligned placement, adjust the offset of the + // floating element itself. To ensure `shift()` continues to take action, + // a single reset is performed when this is true. + const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; + const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; + return { + [axis]: coords[axis] + alignmentOffset, + data: { + [axis]: offset, + centerOffset: center - offset - alignmentOffset, + ...(shouldAddOffset && { + alignmentOffset + }) + }, + reset: shouldAddOffset + }; + } +}); + +function getPlacementList(alignment, autoAlignment, allowedPlacements) { + const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); + return allowedPlacementsSortedByAlignment.filter(placement => { + if (alignment) { + return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); + } + return true; + }); +} +/** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ +const autoPlacement = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'autoPlacement', + options, + async fn(state) { + var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; + const { + rects, + middlewareData, + placement, + platform, + elements + } = state; + const { + crossAxis = false, + alignment, + allowedPlacements = placements, + autoAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; + const currentPlacement = placements$1[currentIndex]; + if (currentPlacement == null) { + return {}; + } + const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); + + // Make `computeCoords` start from the right place. + if (placement !== currentPlacement) { + return { + reset: { + placement: placements$1[0] + } + }; + } + const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; + const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { + placement: currentPlacement, + overflows: currentOverflows + }]; + const nextPlacement = placements$1[currentIndex + 1]; + + // There are more placements to check. + if (nextPlacement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: nextPlacement + } + }; + } + const placementsSortedByMostSpace = allOverflows.map(d => { + const alignment = getAlignment(d.placement); + return [d.placement, alignment && crossAxis ? + // Check along the mainAxis and main crossAxis side. + d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : + // Check only the mainAxis. + d.overflows[0], d.overflows]; + }).sort((a, b) => a[1] - b[1]); + const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, + // Aligned placements should not check their opposite crossAxis + // side. + getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); + const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; + if (resetPlacement !== placement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: resetPlacement + } + }; + } + return {}; + } + }; +}; + +/** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ +const flip = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'flip', + options, + async fn(state) { + var _middlewareData$arrow, _middlewareData$flip; + const { + placement, + middlewareData, + rects, + initialPlacement, + platform, + elements + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + fallbackPlacements: specifiedFallbackPlacements, + fallbackStrategy = 'bestFit', + fallbackAxisSideDirection = 'none', + flipAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + + // If a reset by the arrow was caused due to an alignment offset being + // added, we should skip any logic now since `flip()` has already done its + // work. + // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 + if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + const side = getSide(placement); + const initialSideAxis = getSideAxis(initialPlacement); + const isBasePlacement = getSide(initialPlacement) === initialPlacement; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); + const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; + if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { + fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); + } + const placements = [initialPlacement, ...fallbackPlacements]; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const overflows = []; + let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; + if (checkMainAxis) { + overflows.push(overflow[side]); + } + if (checkCrossAxis) { + const sides = getAlignmentSides(placement, rects, rtl); + overflows.push(overflow[sides[0]], overflow[sides[1]]); + } + overflowsData = [...overflowsData, { + placement, + overflows + }]; + + // One or more sides is overflowing. + if (!overflows.every(side => side <= 0)) { + var _middlewareData$flip2, _overflowsData$filter; + const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; + const nextPlacement = placements[nextIndex]; + if (nextPlacement) { + const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; + if (!ignoreCrossAxisOverflow || + // We leave the current main axis only if every placement on that axis + // overflows the main axis. + overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) { + // Try next placement and re-run the lifecycle. + return { + data: { + index: nextIndex, + overflows: overflowsData + }, + reset: { + placement: nextPlacement + } + }; + } + } + + // First, find the candidates that fit on the mainAxis side of overflow, + // then find the placement that fits the best on the main crossAxis side. + let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; + + // Otherwise fallback. + if (!resetPlacement) { + switch (fallbackStrategy) { + case 'bestFit': + { + var _overflowsData$filter2; + const placement = (_overflowsData$filter2 = overflowsData.filter(d => { + if (hasFallbackAxisSideDirection) { + const currentSideAxis = getSideAxis(d.placement); + return currentSideAxis === initialSideAxis || + // Create a bias to the `y` side axis due to horizontal + // reading directions favoring greater width. + currentSideAxis === 'y'; + } + return true; + }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; + if (placement) { + resetPlacement = placement; + } + break; + } + case 'initialPlacement': + resetPlacement = initialPlacement; + break; + } + } + if (placement !== resetPlacement) { + return { + reset: { + placement: resetPlacement + } + }; + } + } + return {}; + } + }; +}; + +function getSideOffsets(overflow, rect) { + return { + top: overflow.top - rect.height, + right: overflow.right - rect.width, + bottom: overflow.bottom - rect.height, + left: overflow.left - rect.width + }; +} +function isAnySideFullyClipped(overflow) { + return sides.some(side => overflow[side] >= 0); +} +/** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ +const hide = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'hide', + options, + async fn(state) { + const { + rects, + platform + } = state; + const { + strategy = 'referenceHidden', + ...detectOverflowOptions + } = evaluate(options, state); + switch (strategy) { + case 'referenceHidden': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + elementContext: 'reference' + }); + const offsets = getSideOffsets(overflow, rects.reference); + return { + data: { + referenceHiddenOffsets: offsets, + referenceHidden: isAnySideFullyClipped(offsets) + } + }; + } + case 'escaped': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + altBoundary: true + }); + const offsets = getSideOffsets(overflow, rects.floating); + return { + data: { + escapedOffsets: offsets, + escaped: isAnySideFullyClipped(offsets) + } + }; + } + default: + { + return {}; + } + } + } + }; +}; + +function getBoundingRect(rects) { + const minX = min(...rects.map(rect => rect.left)); + const minY = min(...rects.map(rect => rect.top)); + const maxX = max(...rects.map(rect => rect.right)); + const maxY = max(...rects.map(rect => rect.bottom)); + return { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY + }; +} +function getRectsByLine(rects) { + const sortedRects = rects.slice().sort((a, b) => a.y - b.y); + const groups = []; + let prevRect = null; + for (let i = 0; i < sortedRects.length; i++) { + const rect = sortedRects[i]; + if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { + groups.push([rect]); + } else { + groups[groups.length - 1].push(rect); + } + prevRect = rect; + } + return groups.map(rect => rectToClientRect(getBoundingRect(rect))); +} +/** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ +const inline = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'inline', + options, + async fn(state) { + const { + placement, + elements, + rects, + platform, + strategy + } = state; + // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a + // ClientRect's bounds, despite the event listener being triggered. A + // padding of 2 seems to handle this issue. + const { + padding = 2, + x, + y + } = evaluate(options, state); + const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); + const clientRects = getRectsByLine(nativeClientRects); + const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); + const paddingObject = getPaddingObject(padding); + function getBoundingClientRect() { + // There are two rects and they are disjoined. + if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { + // Find the first rect in which the point is fully inside. + return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; + } + + // There are 2 or more connected rects. + if (clientRects.length >= 2) { + if (getSideAxis(placement) === 'y') { + const firstRect = clientRects[0]; + const lastRect = clientRects[clientRects.length - 1]; + const isTop = getSide(placement) === 'top'; + const top = firstRect.top; + const bottom = lastRect.bottom; + const left = isTop ? firstRect.left : lastRect.left; + const right = isTop ? firstRect.right : lastRect.right; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + const isLeftSide = getSide(placement) === 'left'; + const maxRight = max(...clientRects.map(rect => rect.right)); + const minLeft = min(...clientRects.map(rect => rect.left)); + const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); + const top = measureRects[0].top; + const bottom = measureRects[measureRects.length - 1].bottom; + const left = minLeft; + const right = maxRight; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + return fallback; + } + const resetRects = await platform.getElementRects({ + reference: { + getBoundingClientRect + }, + floating: elements.floating, + strategy + }); + if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { + return { + reset: { + rects: resetRects + } + }; + } + return {}; + } + }; +}; + +const originSides = /*#__PURE__*/new Set(['left', 'top']); + +// For type backwards-compatibility, the `OffsetOptions` type was also +// Derivable. + +async function convertValueToCoords(state, options) { + const { + placement, + platform, + elements + } = state; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isVertical = getSideAxis(placement) === 'y'; + const mainAxisMulti = originSides.has(side) ? -1 : 1; + const crossAxisMulti = rtl && isVertical ? -1 : 1; + const rawValue = evaluate(options, state); + + // eslint-disable-next-line prefer-const + let { + mainAxis, + crossAxis, + alignmentAxis + } = typeof rawValue === 'number' ? { + mainAxis: rawValue, + crossAxis: 0, + alignmentAxis: null + } : { + mainAxis: rawValue.mainAxis || 0, + crossAxis: rawValue.crossAxis || 0, + alignmentAxis: rawValue.alignmentAxis + }; + if (alignment && typeof alignmentAxis === 'number') { + crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; + } + return isVertical ? { + x: crossAxis * crossAxisMulti, + y: mainAxis * mainAxisMulti + } : { + x: mainAxis * mainAxisMulti, + y: crossAxis * crossAxisMulti + }; +} + +/** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ +const offset = function (options) { + if (options === void 0) { + options = 0; + } + return { + name: 'offset', + options, + async fn(state) { + var _middlewareData$offse, _middlewareData$arrow; + const { + x, + y, + placement, + middlewareData + } = state; + const diffCoords = await convertValueToCoords(state, options); + + // If the placement is the same and the arrow caused an alignment offset + // then we don't need to change the positioning coordinates. + if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + return { + x: x + diffCoords.x, + y: y + diffCoords.y, + data: { + ...diffCoords, + placement + } + }; + } + }; +}; + +/** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ +const shift = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'shift', + options, + async fn(state) { + const { + x, + y, + placement, + platform + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = false, + limiter = { + fn: _ref => { + let { + x, + y + } = _ref; + return { + x, + y + }; + } + }, + ...detectOverflowOptions + } = evaluate(options, state); + const coords = { + x, + y + }; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const crossAxis = getSideAxis(getSide(placement)); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + if (checkMainAxis) { + const minSide = mainAxis === 'y' ? 'top' : 'left'; + const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; + const min = mainAxisCoord + overflow[minSide]; + const max = mainAxisCoord - overflow[maxSide]; + mainAxisCoord = clamp(min, mainAxisCoord, max); + } + if (checkCrossAxis) { + const minSide = crossAxis === 'y' ? 'top' : 'left'; + const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; + const min = crossAxisCoord + overflow[minSide]; + const max = crossAxisCoord - overflow[maxSide]; + crossAxisCoord = clamp(min, crossAxisCoord, max); + } + const limitedCoords = limiter.fn({ + ...state, + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }); + return { + ...limitedCoords, + data: { + x: limitedCoords.x - x, + y: limitedCoords.y - y, + enabled: { + [mainAxis]: checkMainAxis, + [crossAxis]: checkCrossAxis + } + } + }; + } + }; +}; +/** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ +const limitShift = function (options) { + if (options === void 0) { + options = {}; + } + return { + options, + fn(state) { + const { + x, + y, + placement, + rects, + middlewareData + } = state; + const { + offset = 0, + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true + } = evaluate(options, state); + const coords = { + x, + y + }; + const crossAxis = getSideAxis(placement); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + const rawOffset = evaluate(offset, state); + const computedOffset = typeof rawOffset === 'number' ? { + mainAxis: rawOffset, + crossAxis: 0 + } : { + mainAxis: 0, + crossAxis: 0, + ...rawOffset + }; + if (checkMainAxis) { + const len = mainAxis === 'y' ? 'height' : 'width'; + const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; + const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; + if (mainAxisCoord < limitMin) { + mainAxisCoord = limitMin; + } else if (mainAxisCoord > limitMax) { + mainAxisCoord = limitMax; + } + } + if (checkCrossAxis) { + var _middlewareData$offse, _middlewareData$offse2; + const len = mainAxis === 'y' ? 'width' : 'height'; + const isOriginSide = originSides.has(getSide(placement)); + const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); + const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); + if (crossAxisCoord < limitMin) { + crossAxisCoord = limitMin; + } else if (crossAxisCoord > limitMax) { + crossAxisCoord = limitMax; + } + } + return { + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }; + } + }; +}; + +/** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ +const size = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'size', + options, + async fn(state) { + var _state$middlewareData, _state$middlewareData2; + const { + placement, + rects, + platform, + elements + } = state; + const { + apply = () => {}, + ...detectOverflowOptions + } = evaluate(options, state); + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isYAxis = getSideAxis(placement) === 'y'; + const { + width, + height + } = rects.floating; + let heightSide; + let widthSide; + if (side === 'top' || side === 'bottom') { + heightSide = side; + widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; + } else { + widthSide = side; + heightSide = alignment === 'end' ? 'top' : 'bottom'; + } + const maximumClippingHeight = height - overflow.top - overflow.bottom; + const maximumClippingWidth = width - overflow.left - overflow.right; + const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); + const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); + const noShift = !state.middlewareData.shift; + let availableHeight = overflowAvailableHeight; + let availableWidth = overflowAvailableWidth; + if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { + availableWidth = maximumClippingWidth; + } + if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { + availableHeight = maximumClippingHeight; + } + if (noShift && !alignment) { + const xMin = max(overflow.left, 0); + const xMax = max(overflow.right, 0); + const yMin = max(overflow.top, 0); + const yMax = max(overflow.bottom, 0); + if (isYAxis) { + availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); + } else { + availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); + } + } + await apply({ + ...state, + availableWidth, + availableHeight + }); + const nextDimensions = await platform.getDimensions(elements.floating); + if (width !== nextDimensions.width || height !== nextDimensions.height) { + return { + reset: { + rects: true + } + }; + } + return {}; + } + }; +}; + +export { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, rectToClientRect, shift, size }; diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.d.mts b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.d.mts new file mode 100644 index 00000000..28aede2f --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.d.mts @@ -0,0 +1,531 @@ +import { AlignedPlacement } from '@floating-ui/utils'; +import { Alignment } from '@floating-ui/utils'; +import { Axis } from '@floating-ui/utils'; +import { ClientRectObject } from '@floating-ui/utils'; +import { Coords } from '@floating-ui/utils'; +import { Dimensions } from '@floating-ui/utils'; +import { ElementRects } from '@floating-ui/utils'; +import { Length } from '@floating-ui/utils'; +import { Padding } from '@floating-ui/utils'; +import { Placement } from '@floating-ui/utils'; +import { Rect } from '@floating-ui/utils'; +import { rectToClientRect } from '@floating-ui/utils'; +import { Side } from '@floating-ui/utils'; +import { SideObject } from '@floating-ui/utils'; +import { Strategy } from '@floating-ui/utils'; +import { VirtualElement } from '@floating-ui/utils'; + +export { AlignedPlacement } + +export { Alignment } + +/** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ +export declare const arrow: (options: ArrowOptions | Derivable) => Middleware; + +export declare interface ArrowOptions { + /** + * The arrow element to be positioned. + * @default undefined + */ + element: any; + /** + * The padding between the arrow element and the floating element edges. + * Useful when the floating element has rounded corners. + * @default 0 + */ + padding?: Padding; +} + +/** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ +export declare const autoPlacement: (options?: AutoPlacementOptions | Derivable) => Middleware; + +export declare interface AutoPlacementOptions extends DetectOverflowOptions { + /** + * The axis that runs along the alignment of the floating element. Determines + * whether to check for most space along this axis. + * @default false + */ + crossAxis?: boolean; + /** + * Choose placements with a particular alignment. + * @default undefined + */ + alignment?: Alignment | null; + /** + * Whether to choose placements with the opposite alignment if the preferred + * alignment does not fit. + * @default true + */ + autoAlignment?: boolean; + /** + * Which placements are allowed to be chosen. Placements must be within the + * `alignment` option if explicitly set. + * @default allPlacements (variable) + */ + allowedPlacements?: Array; +} + +export { Axis } + +export declare type Boundary = any; + +export { ClientRectObject } + +export declare type ComputePosition = (reference: unknown, floating: unknown, config: ComputePositionConfig) => Promise; + +/** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a given reference element. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ +export declare const computePosition: ComputePosition; + +export declare interface ComputePositionConfig { + /** + * Object to interface with the current platform. + */ + platform: Platform; + /** + * Where to place the floating element relative to the reference element. + */ + placement?: Placement; + /** + * The strategy to use when positioning the floating element. + */ + strategy?: Strategy; + /** + * Array of middleware objects to modify the positioning or provide data for + * rendering. + */ + middleware?: Array; +} + +export declare interface ComputePositionReturn extends Coords { + /** + * The final chosen placement of the floating element. + */ + placement: Placement; + /** + * The strategy used to position the floating element. + */ + strategy: Strategy; + /** + * Object containing data returned from all middleware, keyed by their name. + */ + middlewareData: MiddlewareData; +} + +export { Coords } + +/** + * Function option to derive middleware options from state. + */ +export declare type Derivable = (state: MiddlewareState) => T; + +/** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ +export declare function detectOverflow(state: MiddlewareState, options?: DetectOverflowOptions | Derivable): Promise; + +export declare interface DetectOverflowOptions { + /** + * The clipping element(s) or area in which overflow will be checked. + * @default 'clippingAncestors' + */ + boundary?: Boundary; + /** + * The root clipping area in which overflow will be checked. + * @default 'viewport' + */ + rootBoundary?: RootBoundary; + /** + * The element in which overflow is being checked relative to a boundary. + * @default 'floating' + */ + elementContext?: ElementContext; + /** + * Whether to check for overflow using the alternate element's boundary + * (`clippingAncestors` boundary only). + * @default false + */ + altBoundary?: boolean; + /** + * Virtual padding for the resolved overflow detection offsets. + * @default 0 + */ + padding?: Padding; +} + +export { Dimensions } + +export declare type ElementContext = 'reference' | 'floating'; + +export { ElementRects } + +export declare interface Elements { + reference: ReferenceElement; + floating: FloatingElement; +} + +/** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ +export declare const flip: (options?: FlipOptions | Derivable) => Middleware; + +export declare interface FlipOptions extends DetectOverflowOptions { + /** + * The axis that runs along the side of the floating element. Determines + * whether overflow along this axis is checked to perform a flip. + * @default true + */ + mainAxis?: boolean; + /** + * The axis that runs along the alignment of the floating element. Determines + * whether overflow along this axis is checked to perform a flip. + * - `true`: Whether to check cross axis overflow for both side and alignment flipping. + * - `false`: Whether to disable all cross axis overflow checking. + * - `'alignment'`: Whether to check cross axis overflow for alignment flipping only. + * @default true + */ + crossAxis?: boolean | 'alignment'; + /** + * Placements to try sequentially if the preferred `placement` does not fit. + * @default [oppositePlacement] (computed) + */ + fallbackPlacements?: Array; + /** + * What strategy to use when no placements fit. + * @default 'bestFit' + */ + fallbackStrategy?: 'bestFit' | 'initialPlacement'; + /** + * Whether to allow fallback to the perpendicular axis of the preferred + * placement, and if so, which side direction along the axis to prefer. + * @default 'none' (disallow fallback) + */ + fallbackAxisSideDirection?: 'none' | 'start' | 'end'; + /** + * Whether to flip to placements with the opposite alignment if they fit + * better. + * @default true + */ + flipAlignment?: boolean; +} + +export declare type FloatingElement = any; + +/** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ +export declare const hide: (options?: HideOptions | Derivable) => Middleware; + +export declare interface HideOptions extends DetectOverflowOptions { + /** + * The strategy used to determine when to hide the floating element. + */ + strategy?: 'referenceHidden' | 'escaped'; +} + +/** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ +export declare const inline: (options?: InlineOptions | Derivable) => Middleware; + +export declare interface InlineOptions { + /** + * Viewport-relative `x` coordinate to choose a `ClientRect`. + * @default undefined + */ + x?: number; + /** + * Viewport-relative `y` coordinate to choose a `ClientRect`. + * @default undefined + */ + y?: number; + /** + * Represents the padding around a disjoined rect when choosing it. + * @default 2 + */ + padding?: Padding; +} + +export { Length } + +/** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ +export declare const limitShift: (options?: LimitShiftOptions | Derivable) => { + options: any; + fn: (state: MiddlewareState) => Coords; +}; + +declare type LimitShiftOffset = number | { + /** + * Offset the limiting of the axis that runs along the alignment of the + * floating element. + */ + mainAxis?: number; + /** + * Offset the limiting of the axis that runs along the side of the + * floating element. + */ + crossAxis?: number; +}; + +export declare interface LimitShiftOptions { + /** + * Offset when limiting starts. `0` will limit when the opposite edges of the + * reference and floating elements are aligned. + * - positive = start limiting earlier + * - negative = start limiting later + */ + offset?: LimitShiftOffset | Derivable; + /** + * Whether to limit the axis that runs along the alignment of the floating + * element. + */ + mainAxis?: boolean; + /** + * Whether to limit the axis that runs along the side of the floating element. + */ + crossAxis?: boolean; +} + +export declare type Middleware = { + name: string; + options?: any; + fn: (state: MiddlewareState) => Promisable; +}; + +/** + * @deprecated use `MiddlewareState` instead. + */ +export declare type MiddlewareArguments = MiddlewareState; + +export declare interface MiddlewareData { + [key: string]: any; + arrow?: Partial & { + centerOffset: number; + alignmentOffset?: number; + }; + autoPlacement?: { + index?: number; + overflows: Array<{ + placement: Placement; + overflows: Array; + }>; + }; + flip?: { + index?: number; + overflows: Array<{ + placement: Placement; + overflows: Array; + }>; + }; + hide?: { + referenceHidden?: boolean; + escaped?: boolean; + referenceHiddenOffsets?: SideObject; + escapedOffsets?: SideObject; + }; + offset?: Coords & { + placement: Placement; + }; + shift?: Coords & { + enabled: { + [key in Axis]: boolean; + }; + }; +} + +export declare interface MiddlewareReturn extends Partial { + data?: { + [key: string]: any; + }; + reset?: boolean | { + placement?: Placement; + rects?: boolean | ElementRects; + }; +} + +export declare interface MiddlewareState extends Coords { + initialPlacement: Placement; + placement: Placement; + strategy: Strategy; + middlewareData: MiddlewareData; + elements: Elements; + rects: ElementRects; + platform: { + detectOverflow: typeof detectOverflow; + } & Platform; +} + +/** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ +export declare const offset: (options?: OffsetOptions) => Middleware; + +export declare type OffsetOptions = OffsetValue | Derivable; + +declare type OffsetValue = number | { + /** + * The axis that runs along the side of the floating element. Represents + * the distance (gutter or margin) between the reference and floating + * element. + * @default 0 + */ + mainAxis?: number; + /** + * The axis that runs along the alignment of the floating element. + * Represents the skidding between the reference and floating element. + * @default 0 + */ + crossAxis?: number; + /** + * The same axis as `crossAxis` but applies only to aligned placements + * and inverts the `end` alignment. When set to a number, it overrides the + * `crossAxis` value. + * + * A positive number will move the floating element in the direction of + * the opposite edge to the one that is aligned, while a negative number + * the reverse. + * @default null + */ + alignmentAxis?: number | null; +}; + +export { Padding } + +export { Placement } + +/** + * Platform interface methods to work with the current platform. + * @see https://floating-ui.com/docs/platform + */ +export declare interface Platform { + getElementRects: (args: { + reference: ReferenceElement; + floating: FloatingElement; + strategy: Strategy; + }) => Promisable; + getClippingRect: (args: { + element: any; + boundary: Boundary; + rootBoundary: RootBoundary; + strategy: Strategy; + }) => Promisable; + getDimensions: (element: any) => Promisable; + convertOffsetParentRelativeRectToViewportRelativeRect?: (args: { + elements?: Elements; + rect: Rect; + offsetParent: any; + strategy: Strategy; + }) => Promisable; + getOffsetParent?: (element: any) => Promisable; + isElement?: (value: any) => Promisable; + getDocumentElement?: (element: any) => Promisable; + getClientRects?: (element: any) => Promisable>; + isRTL?: (element: any) => Promisable; + getScale?: (element: any) => Promisable<{ + x: number; + y: number; + }>; + detectOverflow?: typeof detectOverflow; +} + +declare type Promisable = T | Promise; + +export { Rect } + +export { rectToClientRect } + +export declare type ReferenceElement = any; + +export declare type RootBoundary = 'viewport' | 'document' | Rect; + +/** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ +export declare const shift: (options?: ShiftOptions | Derivable) => Middleware; + +export declare interface ShiftOptions extends DetectOverflowOptions { + /** + * The axis that runs along the alignment of the floating element. Determines + * whether overflow along this axis is checked to perform shifting. + * @default true + */ + mainAxis?: boolean; + /** + * The axis that runs along the side of the floating element. Determines + * whether overflow along this axis is checked to perform shifting. + * @default false + */ + crossAxis?: boolean; + /** + * Accepts a function that limits the shifting done in order to prevent + * detachment. + */ + limiter?: { + fn: (state: MiddlewareState) => Coords; + options?: any; + }; +} + +export { Side } + +export { SideObject } + +/** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ +export declare const size: (options?: SizeOptions | Derivable) => Middleware; + +export declare interface SizeOptions extends DetectOverflowOptions { + /** + * Function that is called to perform style mutations to the floating element + * to change its size. + * @default undefined + */ + apply?(args: MiddlewareState & { + availableWidth: number; + availableHeight: number; + }): void | Promise; +} + +export { Strategy } + +export { VirtualElement } + +export { } diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.d.ts b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.d.ts new file mode 100644 index 00000000..28aede2f --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.d.ts @@ -0,0 +1,531 @@ +import { AlignedPlacement } from '@floating-ui/utils'; +import { Alignment } from '@floating-ui/utils'; +import { Axis } from '@floating-ui/utils'; +import { ClientRectObject } from '@floating-ui/utils'; +import { Coords } from '@floating-ui/utils'; +import { Dimensions } from '@floating-ui/utils'; +import { ElementRects } from '@floating-ui/utils'; +import { Length } from '@floating-ui/utils'; +import { Padding } from '@floating-ui/utils'; +import { Placement } from '@floating-ui/utils'; +import { Rect } from '@floating-ui/utils'; +import { rectToClientRect } from '@floating-ui/utils'; +import { Side } from '@floating-ui/utils'; +import { SideObject } from '@floating-ui/utils'; +import { Strategy } from '@floating-ui/utils'; +import { VirtualElement } from '@floating-ui/utils'; + +export { AlignedPlacement } + +export { Alignment } + +/** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ +export declare const arrow: (options: ArrowOptions | Derivable) => Middleware; + +export declare interface ArrowOptions { + /** + * The arrow element to be positioned. + * @default undefined + */ + element: any; + /** + * The padding between the arrow element and the floating element edges. + * Useful when the floating element has rounded corners. + * @default 0 + */ + padding?: Padding; +} + +/** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ +export declare const autoPlacement: (options?: AutoPlacementOptions | Derivable) => Middleware; + +export declare interface AutoPlacementOptions extends DetectOverflowOptions { + /** + * The axis that runs along the alignment of the floating element. Determines + * whether to check for most space along this axis. + * @default false + */ + crossAxis?: boolean; + /** + * Choose placements with a particular alignment. + * @default undefined + */ + alignment?: Alignment | null; + /** + * Whether to choose placements with the opposite alignment if the preferred + * alignment does not fit. + * @default true + */ + autoAlignment?: boolean; + /** + * Which placements are allowed to be chosen. Placements must be within the + * `alignment` option if explicitly set. + * @default allPlacements (variable) + */ + allowedPlacements?: Array; +} + +export { Axis } + +export declare type Boundary = any; + +export { ClientRectObject } + +export declare type ComputePosition = (reference: unknown, floating: unknown, config: ComputePositionConfig) => Promise; + +/** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a given reference element. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ +export declare const computePosition: ComputePosition; + +export declare interface ComputePositionConfig { + /** + * Object to interface with the current platform. + */ + platform: Platform; + /** + * Where to place the floating element relative to the reference element. + */ + placement?: Placement; + /** + * The strategy to use when positioning the floating element. + */ + strategy?: Strategy; + /** + * Array of middleware objects to modify the positioning or provide data for + * rendering. + */ + middleware?: Array; +} + +export declare interface ComputePositionReturn extends Coords { + /** + * The final chosen placement of the floating element. + */ + placement: Placement; + /** + * The strategy used to position the floating element. + */ + strategy: Strategy; + /** + * Object containing data returned from all middleware, keyed by their name. + */ + middlewareData: MiddlewareData; +} + +export { Coords } + +/** + * Function option to derive middleware options from state. + */ +export declare type Derivable = (state: MiddlewareState) => T; + +/** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ +export declare function detectOverflow(state: MiddlewareState, options?: DetectOverflowOptions | Derivable): Promise; + +export declare interface DetectOverflowOptions { + /** + * The clipping element(s) or area in which overflow will be checked. + * @default 'clippingAncestors' + */ + boundary?: Boundary; + /** + * The root clipping area in which overflow will be checked. + * @default 'viewport' + */ + rootBoundary?: RootBoundary; + /** + * The element in which overflow is being checked relative to a boundary. + * @default 'floating' + */ + elementContext?: ElementContext; + /** + * Whether to check for overflow using the alternate element's boundary + * (`clippingAncestors` boundary only). + * @default false + */ + altBoundary?: boolean; + /** + * Virtual padding for the resolved overflow detection offsets. + * @default 0 + */ + padding?: Padding; +} + +export { Dimensions } + +export declare type ElementContext = 'reference' | 'floating'; + +export { ElementRects } + +export declare interface Elements { + reference: ReferenceElement; + floating: FloatingElement; +} + +/** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ +export declare const flip: (options?: FlipOptions | Derivable) => Middleware; + +export declare interface FlipOptions extends DetectOverflowOptions { + /** + * The axis that runs along the side of the floating element. Determines + * whether overflow along this axis is checked to perform a flip. + * @default true + */ + mainAxis?: boolean; + /** + * The axis that runs along the alignment of the floating element. Determines + * whether overflow along this axis is checked to perform a flip. + * - `true`: Whether to check cross axis overflow for both side and alignment flipping. + * - `false`: Whether to disable all cross axis overflow checking. + * - `'alignment'`: Whether to check cross axis overflow for alignment flipping only. + * @default true + */ + crossAxis?: boolean | 'alignment'; + /** + * Placements to try sequentially if the preferred `placement` does not fit. + * @default [oppositePlacement] (computed) + */ + fallbackPlacements?: Array; + /** + * What strategy to use when no placements fit. + * @default 'bestFit' + */ + fallbackStrategy?: 'bestFit' | 'initialPlacement'; + /** + * Whether to allow fallback to the perpendicular axis of the preferred + * placement, and if so, which side direction along the axis to prefer. + * @default 'none' (disallow fallback) + */ + fallbackAxisSideDirection?: 'none' | 'start' | 'end'; + /** + * Whether to flip to placements with the opposite alignment if they fit + * better. + * @default true + */ + flipAlignment?: boolean; +} + +export declare type FloatingElement = any; + +/** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ +export declare const hide: (options?: HideOptions | Derivable) => Middleware; + +export declare interface HideOptions extends DetectOverflowOptions { + /** + * The strategy used to determine when to hide the floating element. + */ + strategy?: 'referenceHidden' | 'escaped'; +} + +/** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ +export declare const inline: (options?: InlineOptions | Derivable) => Middleware; + +export declare interface InlineOptions { + /** + * Viewport-relative `x` coordinate to choose a `ClientRect`. + * @default undefined + */ + x?: number; + /** + * Viewport-relative `y` coordinate to choose a `ClientRect`. + * @default undefined + */ + y?: number; + /** + * Represents the padding around a disjoined rect when choosing it. + * @default 2 + */ + padding?: Padding; +} + +export { Length } + +/** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ +export declare const limitShift: (options?: LimitShiftOptions | Derivable) => { + options: any; + fn: (state: MiddlewareState) => Coords; +}; + +declare type LimitShiftOffset = number | { + /** + * Offset the limiting of the axis that runs along the alignment of the + * floating element. + */ + mainAxis?: number; + /** + * Offset the limiting of the axis that runs along the side of the + * floating element. + */ + crossAxis?: number; +}; + +export declare interface LimitShiftOptions { + /** + * Offset when limiting starts. `0` will limit when the opposite edges of the + * reference and floating elements are aligned. + * - positive = start limiting earlier + * - negative = start limiting later + */ + offset?: LimitShiftOffset | Derivable; + /** + * Whether to limit the axis that runs along the alignment of the floating + * element. + */ + mainAxis?: boolean; + /** + * Whether to limit the axis that runs along the side of the floating element. + */ + crossAxis?: boolean; +} + +export declare type Middleware = { + name: string; + options?: any; + fn: (state: MiddlewareState) => Promisable; +}; + +/** + * @deprecated use `MiddlewareState` instead. + */ +export declare type MiddlewareArguments = MiddlewareState; + +export declare interface MiddlewareData { + [key: string]: any; + arrow?: Partial & { + centerOffset: number; + alignmentOffset?: number; + }; + autoPlacement?: { + index?: number; + overflows: Array<{ + placement: Placement; + overflows: Array; + }>; + }; + flip?: { + index?: number; + overflows: Array<{ + placement: Placement; + overflows: Array; + }>; + }; + hide?: { + referenceHidden?: boolean; + escaped?: boolean; + referenceHiddenOffsets?: SideObject; + escapedOffsets?: SideObject; + }; + offset?: Coords & { + placement: Placement; + }; + shift?: Coords & { + enabled: { + [key in Axis]: boolean; + }; + }; +} + +export declare interface MiddlewareReturn extends Partial { + data?: { + [key: string]: any; + }; + reset?: boolean | { + placement?: Placement; + rects?: boolean | ElementRects; + }; +} + +export declare interface MiddlewareState extends Coords { + initialPlacement: Placement; + placement: Placement; + strategy: Strategy; + middlewareData: MiddlewareData; + elements: Elements; + rects: ElementRects; + platform: { + detectOverflow: typeof detectOverflow; + } & Platform; +} + +/** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ +export declare const offset: (options?: OffsetOptions) => Middleware; + +export declare type OffsetOptions = OffsetValue | Derivable; + +declare type OffsetValue = number | { + /** + * The axis that runs along the side of the floating element. Represents + * the distance (gutter or margin) between the reference and floating + * element. + * @default 0 + */ + mainAxis?: number; + /** + * The axis that runs along the alignment of the floating element. + * Represents the skidding between the reference and floating element. + * @default 0 + */ + crossAxis?: number; + /** + * The same axis as `crossAxis` but applies only to aligned placements + * and inverts the `end` alignment. When set to a number, it overrides the + * `crossAxis` value. + * + * A positive number will move the floating element in the direction of + * the opposite edge to the one that is aligned, while a negative number + * the reverse. + * @default null + */ + alignmentAxis?: number | null; +}; + +export { Padding } + +export { Placement } + +/** + * Platform interface methods to work with the current platform. + * @see https://floating-ui.com/docs/platform + */ +export declare interface Platform { + getElementRects: (args: { + reference: ReferenceElement; + floating: FloatingElement; + strategy: Strategy; + }) => Promisable; + getClippingRect: (args: { + element: any; + boundary: Boundary; + rootBoundary: RootBoundary; + strategy: Strategy; + }) => Promisable; + getDimensions: (element: any) => Promisable; + convertOffsetParentRelativeRectToViewportRelativeRect?: (args: { + elements?: Elements; + rect: Rect; + offsetParent: any; + strategy: Strategy; + }) => Promisable; + getOffsetParent?: (element: any) => Promisable; + isElement?: (value: any) => Promisable; + getDocumentElement?: (element: any) => Promisable; + getClientRects?: (element: any) => Promisable>; + isRTL?: (element: any) => Promisable; + getScale?: (element: any) => Promisable<{ + x: number; + y: number; + }>; + detectOverflow?: typeof detectOverflow; +} + +declare type Promisable = T | Promise; + +export { Rect } + +export { rectToClientRect } + +export declare type ReferenceElement = any; + +export declare type RootBoundary = 'viewport' | 'document' | Rect; + +/** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ +export declare const shift: (options?: ShiftOptions | Derivable) => Middleware; + +export declare interface ShiftOptions extends DetectOverflowOptions { + /** + * The axis that runs along the alignment of the floating element. Determines + * whether overflow along this axis is checked to perform shifting. + * @default true + */ + mainAxis?: boolean; + /** + * The axis that runs along the side of the floating element. Determines + * whether overflow along this axis is checked to perform shifting. + * @default false + */ + crossAxis?: boolean; + /** + * Accepts a function that limits the shifting done in order to prevent + * detachment. + */ + limiter?: { + fn: (state: MiddlewareState) => Coords; + options?: any; + }; +} + +export { Side } + +export { SideObject } + +/** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ +export declare const size: (options?: SizeOptions | Derivable) => Middleware; + +export declare interface SizeOptions extends DetectOverflowOptions { + /** + * Function that is called to perform style mutations to the floating element + * to change its size. + * @default undefined + */ + apply?(args: MiddlewareState & { + availableWidth: number; + availableHeight: number; + }): void | Promise; +} + +export { Strategy } + +export { VirtualElement } + +export { } diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.esm.js b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.esm.js new file mode 100644 index 00000000..e6b585d5 --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.esm.js @@ -0,0 +1,1055 @@ +import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils'; +export { rectToClientRect } from '@floating-ui/utils'; + +function computeCoordsFromPlacement(_ref, placement, rtl) { + let { + reference, + floating + } = _ref; + const sideAxis = getSideAxis(placement); + const alignmentAxis = getAlignmentAxis(placement); + const alignLength = getAxisLength(alignmentAxis); + const side = getSide(placement); + const isVertical = sideAxis === 'y'; + const commonX = reference.x + reference.width / 2 - floating.width / 2; + const commonY = reference.y + reference.height / 2 - floating.height / 2; + const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; + let coords; + switch (side) { + case 'top': + coords = { + x: commonX, + y: reference.y - floating.height + }; + break; + case 'bottom': + coords = { + x: commonX, + y: reference.y + reference.height + }; + break; + case 'right': + coords = { + x: reference.x + reference.width, + y: commonY + }; + break; + case 'left': + coords = { + x: reference.x - floating.width, + y: commonY + }; + break; + default: + coords = { + x: reference.x, + y: reference.y + }; + } + switch (getAlignment(placement)) { + case 'start': + coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); + break; + case 'end': + coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); + break; + } + return coords; +} + +/** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ +async function detectOverflow(state, options) { + var _await$platform$isEle; + if (options === void 0) { + options = {}; + } + const { + x, + y, + platform, + rects, + elements, + strategy + } = state; + const { + boundary = 'clippingAncestors', + rootBoundary = 'viewport', + elementContext = 'floating', + altBoundary = false, + padding = 0 + } = evaluate(options, state); + const paddingObject = getPaddingObject(padding); + const altContext = elementContext === 'floating' ? 'reference' : 'floating'; + const element = elements[altBoundary ? altContext : elementContext]; + const clippingClientRect = rectToClientRect(await platform.getClippingRect({ + element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), + boundary, + rootBoundary, + strategy + })); + const rect = elementContext === 'floating' ? { + x, + y, + width: rects.floating.width, + height: rects.floating.height + } : rects.reference; + const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); + const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { + x: 1, + y: 1 + } : { + x: 1, + y: 1 + }; + const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ + elements, + rect, + offsetParent, + strategy + }) : rect); + return { + top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, + bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, + left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, + right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x + }; +} + +/** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a given reference element. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ +const computePosition = async (reference, floating, config) => { + const { + placement = 'bottom', + strategy = 'absolute', + middleware = [], + platform + } = config; + const validMiddleware = middleware.filter(Boolean); + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); + let rects = await platform.getElementRects({ + reference, + floating, + strategy + }); + let { + x, + y + } = computeCoordsFromPlacement(rects, placement, rtl); + let statefulPlacement = placement; + let middlewareData = {}; + let resetCount = 0; + for (let i = 0; i < validMiddleware.length; i++) { + var _platform$detectOverf; + const { + name, + fn + } = validMiddleware[i]; + const { + x: nextX, + y: nextY, + data, + reset + } = await fn({ + x, + y, + initialPlacement: placement, + placement: statefulPlacement, + strategy, + middlewareData, + rects, + platform: { + ...platform, + detectOverflow: (_platform$detectOverf = platform.detectOverflow) != null ? _platform$detectOverf : detectOverflow + }, + elements: { + reference, + floating + } + }); + x = nextX != null ? nextX : x; + y = nextY != null ? nextY : y; + middlewareData = { + ...middlewareData, + [name]: { + ...middlewareData[name], + ...data + } + }; + if (reset && resetCount <= 50) { + resetCount++; + if (typeof reset === 'object') { + if (reset.placement) { + statefulPlacement = reset.placement; + } + if (reset.rects) { + rects = reset.rects === true ? await platform.getElementRects({ + reference, + floating, + strategy + }) : reset.rects; + } + ({ + x, + y + } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); + } + i = -1; + } + } + return { + x, + y, + placement: statefulPlacement, + strategy, + middlewareData + }; +}; + +/** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ +const arrow = options => ({ + name: 'arrow', + options, + async fn(state) { + const { + x, + y, + placement, + rects, + platform, + elements, + middlewareData + } = state; + // Since `element` is required, we don't Partial<> the type. + const { + element, + padding = 0 + } = evaluate(options, state) || {}; + if (element == null) { + return {}; + } + const paddingObject = getPaddingObject(padding); + const coords = { + x, + y + }; + const axis = getAlignmentAxis(placement); + const length = getAxisLength(axis); + const arrowDimensions = await platform.getDimensions(element); + const isYAxis = axis === 'y'; + const minProp = isYAxis ? 'top' : 'left'; + const maxProp = isYAxis ? 'bottom' : 'right'; + const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; + const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; + const startDiff = coords[axis] - rects.reference[axis]; + const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); + let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; + + // DOM platform can return `window` as the `offsetParent`. + if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { + clientSize = elements.floating[clientProp] || rects.floating[length]; + } + const centerToReference = endDiff / 2 - startDiff / 2; + + // If the padding is large enough that it causes the arrow to no longer be + // centered, modify the padding so that it is centered. + const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; + const minPadding = min(paddingObject[minProp], largestPossiblePadding); + const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); + + // Make sure the arrow doesn't overflow the floating element if the center + // point is outside the floating element's bounds. + const min$1 = minPadding; + const max = clientSize - arrowDimensions[length] - maxPadding; + const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; + const offset = clamp(min$1, center, max); + + // If the reference is small enough that the arrow's padding causes it to + // to point to nothing for an aligned placement, adjust the offset of the + // floating element itself. To ensure `shift()` continues to take action, + // a single reset is performed when this is true. + const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; + const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; + return { + [axis]: coords[axis] + alignmentOffset, + data: { + [axis]: offset, + centerOffset: center - offset - alignmentOffset, + ...(shouldAddOffset && { + alignmentOffset + }) + }, + reset: shouldAddOffset + }; + } +}); + +function getPlacementList(alignment, autoAlignment, allowedPlacements) { + const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); + return allowedPlacementsSortedByAlignment.filter(placement => { + if (alignment) { + return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); + } + return true; + }); +} +/** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ +const autoPlacement = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'autoPlacement', + options, + async fn(state) { + var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; + const { + rects, + middlewareData, + placement, + platform, + elements + } = state; + const { + crossAxis = false, + alignment, + allowedPlacements = placements, + autoAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; + const currentPlacement = placements$1[currentIndex]; + if (currentPlacement == null) { + return {}; + } + const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); + + // Make `computeCoords` start from the right place. + if (placement !== currentPlacement) { + return { + reset: { + placement: placements$1[0] + } + }; + } + const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; + const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { + placement: currentPlacement, + overflows: currentOverflows + }]; + const nextPlacement = placements$1[currentIndex + 1]; + + // There are more placements to check. + if (nextPlacement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: nextPlacement + } + }; + } + const placementsSortedByMostSpace = allOverflows.map(d => { + const alignment = getAlignment(d.placement); + return [d.placement, alignment && crossAxis ? + // Check along the mainAxis and main crossAxis side. + d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : + // Check only the mainAxis. + d.overflows[0], d.overflows]; + }).sort((a, b) => a[1] - b[1]); + const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, + // Aligned placements should not check their opposite crossAxis + // side. + getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); + const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; + if (resetPlacement !== placement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: resetPlacement + } + }; + } + return {}; + } + }; +}; + +/** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ +const flip = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'flip', + options, + async fn(state) { + var _middlewareData$arrow, _middlewareData$flip; + const { + placement, + middlewareData, + rects, + initialPlacement, + platform, + elements + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + fallbackPlacements: specifiedFallbackPlacements, + fallbackStrategy = 'bestFit', + fallbackAxisSideDirection = 'none', + flipAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + + // If a reset by the arrow was caused due to an alignment offset being + // added, we should skip any logic now since `flip()` has already done its + // work. + // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 + if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + const side = getSide(placement); + const initialSideAxis = getSideAxis(initialPlacement); + const isBasePlacement = getSide(initialPlacement) === initialPlacement; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); + const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; + if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { + fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); + } + const placements = [initialPlacement, ...fallbackPlacements]; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const overflows = []; + let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; + if (checkMainAxis) { + overflows.push(overflow[side]); + } + if (checkCrossAxis) { + const sides = getAlignmentSides(placement, rects, rtl); + overflows.push(overflow[sides[0]], overflow[sides[1]]); + } + overflowsData = [...overflowsData, { + placement, + overflows + }]; + + // One or more sides is overflowing. + if (!overflows.every(side => side <= 0)) { + var _middlewareData$flip2, _overflowsData$filter; + const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; + const nextPlacement = placements[nextIndex]; + if (nextPlacement) { + const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; + if (!ignoreCrossAxisOverflow || + // We leave the current main axis only if every placement on that axis + // overflows the main axis. + overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) { + // Try next placement and re-run the lifecycle. + return { + data: { + index: nextIndex, + overflows: overflowsData + }, + reset: { + placement: nextPlacement + } + }; + } + } + + // First, find the candidates that fit on the mainAxis side of overflow, + // then find the placement that fits the best on the main crossAxis side. + let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; + + // Otherwise fallback. + if (!resetPlacement) { + switch (fallbackStrategy) { + case 'bestFit': + { + var _overflowsData$filter2; + const placement = (_overflowsData$filter2 = overflowsData.filter(d => { + if (hasFallbackAxisSideDirection) { + const currentSideAxis = getSideAxis(d.placement); + return currentSideAxis === initialSideAxis || + // Create a bias to the `y` side axis due to horizontal + // reading directions favoring greater width. + currentSideAxis === 'y'; + } + return true; + }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; + if (placement) { + resetPlacement = placement; + } + break; + } + case 'initialPlacement': + resetPlacement = initialPlacement; + break; + } + } + if (placement !== resetPlacement) { + return { + reset: { + placement: resetPlacement + } + }; + } + } + return {}; + } + }; +}; + +function getSideOffsets(overflow, rect) { + return { + top: overflow.top - rect.height, + right: overflow.right - rect.width, + bottom: overflow.bottom - rect.height, + left: overflow.left - rect.width + }; +} +function isAnySideFullyClipped(overflow) { + return sides.some(side => overflow[side] >= 0); +} +/** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ +const hide = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'hide', + options, + async fn(state) { + const { + rects, + platform + } = state; + const { + strategy = 'referenceHidden', + ...detectOverflowOptions + } = evaluate(options, state); + switch (strategy) { + case 'referenceHidden': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + elementContext: 'reference' + }); + const offsets = getSideOffsets(overflow, rects.reference); + return { + data: { + referenceHiddenOffsets: offsets, + referenceHidden: isAnySideFullyClipped(offsets) + } + }; + } + case 'escaped': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + altBoundary: true + }); + const offsets = getSideOffsets(overflow, rects.floating); + return { + data: { + escapedOffsets: offsets, + escaped: isAnySideFullyClipped(offsets) + } + }; + } + default: + { + return {}; + } + } + } + }; +}; + +function getBoundingRect(rects) { + const minX = min(...rects.map(rect => rect.left)); + const minY = min(...rects.map(rect => rect.top)); + const maxX = max(...rects.map(rect => rect.right)); + const maxY = max(...rects.map(rect => rect.bottom)); + return { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY + }; +} +function getRectsByLine(rects) { + const sortedRects = rects.slice().sort((a, b) => a.y - b.y); + const groups = []; + let prevRect = null; + for (let i = 0; i < sortedRects.length; i++) { + const rect = sortedRects[i]; + if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { + groups.push([rect]); + } else { + groups[groups.length - 1].push(rect); + } + prevRect = rect; + } + return groups.map(rect => rectToClientRect(getBoundingRect(rect))); +} +/** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ +const inline = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'inline', + options, + async fn(state) { + const { + placement, + elements, + rects, + platform, + strategy + } = state; + // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a + // ClientRect's bounds, despite the event listener being triggered. A + // padding of 2 seems to handle this issue. + const { + padding = 2, + x, + y + } = evaluate(options, state); + const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); + const clientRects = getRectsByLine(nativeClientRects); + const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); + const paddingObject = getPaddingObject(padding); + function getBoundingClientRect() { + // There are two rects and they are disjoined. + if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { + // Find the first rect in which the point is fully inside. + return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; + } + + // There are 2 or more connected rects. + if (clientRects.length >= 2) { + if (getSideAxis(placement) === 'y') { + const firstRect = clientRects[0]; + const lastRect = clientRects[clientRects.length - 1]; + const isTop = getSide(placement) === 'top'; + const top = firstRect.top; + const bottom = lastRect.bottom; + const left = isTop ? firstRect.left : lastRect.left; + const right = isTop ? firstRect.right : lastRect.right; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + const isLeftSide = getSide(placement) === 'left'; + const maxRight = max(...clientRects.map(rect => rect.right)); + const minLeft = min(...clientRects.map(rect => rect.left)); + const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); + const top = measureRects[0].top; + const bottom = measureRects[measureRects.length - 1].bottom; + const left = minLeft; + const right = maxRight; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + return fallback; + } + const resetRects = await platform.getElementRects({ + reference: { + getBoundingClientRect + }, + floating: elements.floating, + strategy + }); + if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { + return { + reset: { + rects: resetRects + } + }; + } + return {}; + } + }; +}; + +const originSides = /*#__PURE__*/new Set(['left', 'top']); + +// For type backwards-compatibility, the `OffsetOptions` type was also +// Derivable. + +async function convertValueToCoords(state, options) { + const { + placement, + platform, + elements + } = state; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isVertical = getSideAxis(placement) === 'y'; + const mainAxisMulti = originSides.has(side) ? -1 : 1; + const crossAxisMulti = rtl && isVertical ? -1 : 1; + const rawValue = evaluate(options, state); + + // eslint-disable-next-line prefer-const + let { + mainAxis, + crossAxis, + alignmentAxis + } = typeof rawValue === 'number' ? { + mainAxis: rawValue, + crossAxis: 0, + alignmentAxis: null + } : { + mainAxis: rawValue.mainAxis || 0, + crossAxis: rawValue.crossAxis || 0, + alignmentAxis: rawValue.alignmentAxis + }; + if (alignment && typeof alignmentAxis === 'number') { + crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; + } + return isVertical ? { + x: crossAxis * crossAxisMulti, + y: mainAxis * mainAxisMulti + } : { + x: mainAxis * mainAxisMulti, + y: crossAxis * crossAxisMulti + }; +} + +/** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ +const offset = function (options) { + if (options === void 0) { + options = 0; + } + return { + name: 'offset', + options, + async fn(state) { + var _middlewareData$offse, _middlewareData$arrow; + const { + x, + y, + placement, + middlewareData + } = state; + const diffCoords = await convertValueToCoords(state, options); + + // If the placement is the same and the arrow caused an alignment offset + // then we don't need to change the positioning coordinates. + if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + return { + x: x + diffCoords.x, + y: y + diffCoords.y, + data: { + ...diffCoords, + placement + } + }; + } + }; +}; + +/** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ +const shift = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'shift', + options, + async fn(state) { + const { + x, + y, + placement, + platform + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = false, + limiter = { + fn: _ref => { + let { + x, + y + } = _ref; + return { + x, + y + }; + } + }, + ...detectOverflowOptions + } = evaluate(options, state); + const coords = { + x, + y + }; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const crossAxis = getSideAxis(getSide(placement)); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + if (checkMainAxis) { + const minSide = mainAxis === 'y' ? 'top' : 'left'; + const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; + const min = mainAxisCoord + overflow[minSide]; + const max = mainAxisCoord - overflow[maxSide]; + mainAxisCoord = clamp(min, mainAxisCoord, max); + } + if (checkCrossAxis) { + const minSide = crossAxis === 'y' ? 'top' : 'left'; + const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; + const min = crossAxisCoord + overflow[minSide]; + const max = crossAxisCoord - overflow[maxSide]; + crossAxisCoord = clamp(min, crossAxisCoord, max); + } + const limitedCoords = limiter.fn({ + ...state, + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }); + return { + ...limitedCoords, + data: { + x: limitedCoords.x - x, + y: limitedCoords.y - y, + enabled: { + [mainAxis]: checkMainAxis, + [crossAxis]: checkCrossAxis + } + } + }; + } + }; +}; +/** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ +const limitShift = function (options) { + if (options === void 0) { + options = {}; + } + return { + options, + fn(state) { + const { + x, + y, + placement, + rects, + middlewareData + } = state; + const { + offset = 0, + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true + } = evaluate(options, state); + const coords = { + x, + y + }; + const crossAxis = getSideAxis(placement); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + const rawOffset = evaluate(offset, state); + const computedOffset = typeof rawOffset === 'number' ? { + mainAxis: rawOffset, + crossAxis: 0 + } : { + mainAxis: 0, + crossAxis: 0, + ...rawOffset + }; + if (checkMainAxis) { + const len = mainAxis === 'y' ? 'height' : 'width'; + const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; + const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; + if (mainAxisCoord < limitMin) { + mainAxisCoord = limitMin; + } else if (mainAxisCoord > limitMax) { + mainAxisCoord = limitMax; + } + } + if (checkCrossAxis) { + var _middlewareData$offse, _middlewareData$offse2; + const len = mainAxis === 'y' ? 'width' : 'height'; + const isOriginSide = originSides.has(getSide(placement)); + const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); + const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); + if (crossAxisCoord < limitMin) { + crossAxisCoord = limitMin; + } else if (crossAxisCoord > limitMax) { + crossAxisCoord = limitMax; + } + } + return { + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }; + } + }; +}; + +/** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ +const size = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'size', + options, + async fn(state) { + var _state$middlewareData, _state$middlewareData2; + const { + placement, + rects, + platform, + elements + } = state; + const { + apply = () => {}, + ...detectOverflowOptions + } = evaluate(options, state); + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isYAxis = getSideAxis(placement) === 'y'; + const { + width, + height + } = rects.floating; + let heightSide; + let widthSide; + if (side === 'top' || side === 'bottom') { + heightSide = side; + widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; + } else { + widthSide = side; + heightSide = alignment === 'end' ? 'top' : 'bottom'; + } + const maximumClippingHeight = height - overflow.top - overflow.bottom; + const maximumClippingWidth = width - overflow.left - overflow.right; + const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); + const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); + const noShift = !state.middlewareData.shift; + let availableHeight = overflowAvailableHeight; + let availableWidth = overflowAvailableWidth; + if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { + availableWidth = maximumClippingWidth; + } + if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { + availableHeight = maximumClippingHeight; + } + if (noShift && !alignment) { + const xMin = max(overflow.left, 0); + const xMax = max(overflow.right, 0); + const yMin = max(overflow.top, 0); + const yMax = max(overflow.bottom, 0); + if (isYAxis) { + availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); + } else { + availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); + } + } + await apply({ + ...state, + availableWidth, + availableHeight + }); + const nextDimensions = await platform.getDimensions(elements.floating); + if (width !== nextDimensions.width || height !== nextDimensions.height) { + return { + reset: { + rects: true + } + }; + } + return {}; + } + }; +}; + +export { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size }; diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.mjs b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.mjs new file mode 100644 index 00000000..e6b585d5 --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.mjs @@ -0,0 +1,1055 @@ +import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils'; +export { rectToClientRect } from '@floating-ui/utils'; + +function computeCoordsFromPlacement(_ref, placement, rtl) { + let { + reference, + floating + } = _ref; + const sideAxis = getSideAxis(placement); + const alignmentAxis = getAlignmentAxis(placement); + const alignLength = getAxisLength(alignmentAxis); + const side = getSide(placement); + const isVertical = sideAxis === 'y'; + const commonX = reference.x + reference.width / 2 - floating.width / 2; + const commonY = reference.y + reference.height / 2 - floating.height / 2; + const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; + let coords; + switch (side) { + case 'top': + coords = { + x: commonX, + y: reference.y - floating.height + }; + break; + case 'bottom': + coords = { + x: commonX, + y: reference.y + reference.height + }; + break; + case 'right': + coords = { + x: reference.x + reference.width, + y: commonY + }; + break; + case 'left': + coords = { + x: reference.x - floating.width, + y: commonY + }; + break; + default: + coords = { + x: reference.x, + y: reference.y + }; + } + switch (getAlignment(placement)) { + case 'start': + coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); + break; + case 'end': + coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); + break; + } + return coords; +} + +/** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ +async function detectOverflow(state, options) { + var _await$platform$isEle; + if (options === void 0) { + options = {}; + } + const { + x, + y, + platform, + rects, + elements, + strategy + } = state; + const { + boundary = 'clippingAncestors', + rootBoundary = 'viewport', + elementContext = 'floating', + altBoundary = false, + padding = 0 + } = evaluate(options, state); + const paddingObject = getPaddingObject(padding); + const altContext = elementContext === 'floating' ? 'reference' : 'floating'; + const element = elements[altBoundary ? altContext : elementContext]; + const clippingClientRect = rectToClientRect(await platform.getClippingRect({ + element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), + boundary, + rootBoundary, + strategy + })); + const rect = elementContext === 'floating' ? { + x, + y, + width: rects.floating.width, + height: rects.floating.height + } : rects.reference; + const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); + const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { + x: 1, + y: 1 + } : { + x: 1, + y: 1 + }; + const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ + elements, + rect, + offsetParent, + strategy + }) : rect); + return { + top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, + bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, + left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, + right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x + }; +} + +/** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a given reference element. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ +const computePosition = async (reference, floating, config) => { + const { + placement = 'bottom', + strategy = 'absolute', + middleware = [], + platform + } = config; + const validMiddleware = middleware.filter(Boolean); + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); + let rects = await platform.getElementRects({ + reference, + floating, + strategy + }); + let { + x, + y + } = computeCoordsFromPlacement(rects, placement, rtl); + let statefulPlacement = placement; + let middlewareData = {}; + let resetCount = 0; + for (let i = 0; i < validMiddleware.length; i++) { + var _platform$detectOverf; + const { + name, + fn + } = validMiddleware[i]; + const { + x: nextX, + y: nextY, + data, + reset + } = await fn({ + x, + y, + initialPlacement: placement, + placement: statefulPlacement, + strategy, + middlewareData, + rects, + platform: { + ...platform, + detectOverflow: (_platform$detectOverf = platform.detectOverflow) != null ? _platform$detectOverf : detectOverflow + }, + elements: { + reference, + floating + } + }); + x = nextX != null ? nextX : x; + y = nextY != null ? nextY : y; + middlewareData = { + ...middlewareData, + [name]: { + ...middlewareData[name], + ...data + } + }; + if (reset && resetCount <= 50) { + resetCount++; + if (typeof reset === 'object') { + if (reset.placement) { + statefulPlacement = reset.placement; + } + if (reset.rects) { + rects = reset.rects === true ? await platform.getElementRects({ + reference, + floating, + strategy + }) : reset.rects; + } + ({ + x, + y + } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); + } + i = -1; + } + } + return { + x, + y, + placement: statefulPlacement, + strategy, + middlewareData + }; +}; + +/** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ +const arrow = options => ({ + name: 'arrow', + options, + async fn(state) { + const { + x, + y, + placement, + rects, + platform, + elements, + middlewareData + } = state; + // Since `element` is required, we don't Partial<> the type. + const { + element, + padding = 0 + } = evaluate(options, state) || {}; + if (element == null) { + return {}; + } + const paddingObject = getPaddingObject(padding); + const coords = { + x, + y + }; + const axis = getAlignmentAxis(placement); + const length = getAxisLength(axis); + const arrowDimensions = await platform.getDimensions(element); + const isYAxis = axis === 'y'; + const minProp = isYAxis ? 'top' : 'left'; + const maxProp = isYAxis ? 'bottom' : 'right'; + const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; + const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; + const startDiff = coords[axis] - rects.reference[axis]; + const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); + let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; + + // DOM platform can return `window` as the `offsetParent`. + if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { + clientSize = elements.floating[clientProp] || rects.floating[length]; + } + const centerToReference = endDiff / 2 - startDiff / 2; + + // If the padding is large enough that it causes the arrow to no longer be + // centered, modify the padding so that it is centered. + const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; + const minPadding = min(paddingObject[minProp], largestPossiblePadding); + const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); + + // Make sure the arrow doesn't overflow the floating element if the center + // point is outside the floating element's bounds. + const min$1 = minPadding; + const max = clientSize - arrowDimensions[length] - maxPadding; + const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; + const offset = clamp(min$1, center, max); + + // If the reference is small enough that the arrow's padding causes it to + // to point to nothing for an aligned placement, adjust the offset of the + // floating element itself. To ensure `shift()` continues to take action, + // a single reset is performed when this is true. + const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; + const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; + return { + [axis]: coords[axis] + alignmentOffset, + data: { + [axis]: offset, + centerOffset: center - offset - alignmentOffset, + ...(shouldAddOffset && { + alignmentOffset + }) + }, + reset: shouldAddOffset + }; + } +}); + +function getPlacementList(alignment, autoAlignment, allowedPlacements) { + const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); + return allowedPlacementsSortedByAlignment.filter(placement => { + if (alignment) { + return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); + } + return true; + }); +} +/** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ +const autoPlacement = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'autoPlacement', + options, + async fn(state) { + var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; + const { + rects, + middlewareData, + placement, + platform, + elements + } = state; + const { + crossAxis = false, + alignment, + allowedPlacements = placements, + autoAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; + const currentPlacement = placements$1[currentIndex]; + if (currentPlacement == null) { + return {}; + } + const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); + + // Make `computeCoords` start from the right place. + if (placement !== currentPlacement) { + return { + reset: { + placement: placements$1[0] + } + }; + } + const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; + const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { + placement: currentPlacement, + overflows: currentOverflows + }]; + const nextPlacement = placements$1[currentIndex + 1]; + + // There are more placements to check. + if (nextPlacement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: nextPlacement + } + }; + } + const placementsSortedByMostSpace = allOverflows.map(d => { + const alignment = getAlignment(d.placement); + return [d.placement, alignment && crossAxis ? + // Check along the mainAxis and main crossAxis side. + d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : + // Check only the mainAxis. + d.overflows[0], d.overflows]; + }).sort((a, b) => a[1] - b[1]); + const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, + // Aligned placements should not check their opposite crossAxis + // side. + getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); + const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; + if (resetPlacement !== placement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: resetPlacement + } + }; + } + return {}; + } + }; +}; + +/** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ +const flip = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'flip', + options, + async fn(state) { + var _middlewareData$arrow, _middlewareData$flip; + const { + placement, + middlewareData, + rects, + initialPlacement, + platform, + elements + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + fallbackPlacements: specifiedFallbackPlacements, + fallbackStrategy = 'bestFit', + fallbackAxisSideDirection = 'none', + flipAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + + // If a reset by the arrow was caused due to an alignment offset being + // added, we should skip any logic now since `flip()` has already done its + // work. + // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 + if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + const side = getSide(placement); + const initialSideAxis = getSideAxis(initialPlacement); + const isBasePlacement = getSide(initialPlacement) === initialPlacement; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); + const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; + if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { + fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); + } + const placements = [initialPlacement, ...fallbackPlacements]; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const overflows = []; + let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; + if (checkMainAxis) { + overflows.push(overflow[side]); + } + if (checkCrossAxis) { + const sides = getAlignmentSides(placement, rects, rtl); + overflows.push(overflow[sides[0]], overflow[sides[1]]); + } + overflowsData = [...overflowsData, { + placement, + overflows + }]; + + // One or more sides is overflowing. + if (!overflows.every(side => side <= 0)) { + var _middlewareData$flip2, _overflowsData$filter; + const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; + const nextPlacement = placements[nextIndex]; + if (nextPlacement) { + const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; + if (!ignoreCrossAxisOverflow || + // We leave the current main axis only if every placement on that axis + // overflows the main axis. + overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) { + // Try next placement and re-run the lifecycle. + return { + data: { + index: nextIndex, + overflows: overflowsData + }, + reset: { + placement: nextPlacement + } + }; + } + } + + // First, find the candidates that fit on the mainAxis side of overflow, + // then find the placement that fits the best on the main crossAxis side. + let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; + + // Otherwise fallback. + if (!resetPlacement) { + switch (fallbackStrategy) { + case 'bestFit': + { + var _overflowsData$filter2; + const placement = (_overflowsData$filter2 = overflowsData.filter(d => { + if (hasFallbackAxisSideDirection) { + const currentSideAxis = getSideAxis(d.placement); + return currentSideAxis === initialSideAxis || + // Create a bias to the `y` side axis due to horizontal + // reading directions favoring greater width. + currentSideAxis === 'y'; + } + return true; + }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; + if (placement) { + resetPlacement = placement; + } + break; + } + case 'initialPlacement': + resetPlacement = initialPlacement; + break; + } + } + if (placement !== resetPlacement) { + return { + reset: { + placement: resetPlacement + } + }; + } + } + return {}; + } + }; +}; + +function getSideOffsets(overflow, rect) { + return { + top: overflow.top - rect.height, + right: overflow.right - rect.width, + bottom: overflow.bottom - rect.height, + left: overflow.left - rect.width + }; +} +function isAnySideFullyClipped(overflow) { + return sides.some(side => overflow[side] >= 0); +} +/** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ +const hide = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'hide', + options, + async fn(state) { + const { + rects, + platform + } = state; + const { + strategy = 'referenceHidden', + ...detectOverflowOptions + } = evaluate(options, state); + switch (strategy) { + case 'referenceHidden': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + elementContext: 'reference' + }); + const offsets = getSideOffsets(overflow, rects.reference); + return { + data: { + referenceHiddenOffsets: offsets, + referenceHidden: isAnySideFullyClipped(offsets) + } + }; + } + case 'escaped': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + altBoundary: true + }); + const offsets = getSideOffsets(overflow, rects.floating); + return { + data: { + escapedOffsets: offsets, + escaped: isAnySideFullyClipped(offsets) + } + }; + } + default: + { + return {}; + } + } + } + }; +}; + +function getBoundingRect(rects) { + const minX = min(...rects.map(rect => rect.left)); + const minY = min(...rects.map(rect => rect.top)); + const maxX = max(...rects.map(rect => rect.right)); + const maxY = max(...rects.map(rect => rect.bottom)); + return { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY + }; +} +function getRectsByLine(rects) { + const sortedRects = rects.slice().sort((a, b) => a.y - b.y); + const groups = []; + let prevRect = null; + for (let i = 0; i < sortedRects.length; i++) { + const rect = sortedRects[i]; + if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { + groups.push([rect]); + } else { + groups[groups.length - 1].push(rect); + } + prevRect = rect; + } + return groups.map(rect => rectToClientRect(getBoundingRect(rect))); +} +/** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ +const inline = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'inline', + options, + async fn(state) { + const { + placement, + elements, + rects, + platform, + strategy + } = state; + // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a + // ClientRect's bounds, despite the event listener being triggered. A + // padding of 2 seems to handle this issue. + const { + padding = 2, + x, + y + } = evaluate(options, state); + const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); + const clientRects = getRectsByLine(nativeClientRects); + const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); + const paddingObject = getPaddingObject(padding); + function getBoundingClientRect() { + // There are two rects and they are disjoined. + if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { + // Find the first rect in which the point is fully inside. + return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; + } + + // There are 2 or more connected rects. + if (clientRects.length >= 2) { + if (getSideAxis(placement) === 'y') { + const firstRect = clientRects[0]; + const lastRect = clientRects[clientRects.length - 1]; + const isTop = getSide(placement) === 'top'; + const top = firstRect.top; + const bottom = lastRect.bottom; + const left = isTop ? firstRect.left : lastRect.left; + const right = isTop ? firstRect.right : lastRect.right; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + const isLeftSide = getSide(placement) === 'left'; + const maxRight = max(...clientRects.map(rect => rect.right)); + const minLeft = min(...clientRects.map(rect => rect.left)); + const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); + const top = measureRects[0].top; + const bottom = measureRects[measureRects.length - 1].bottom; + const left = minLeft; + const right = maxRight; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + return fallback; + } + const resetRects = await platform.getElementRects({ + reference: { + getBoundingClientRect + }, + floating: elements.floating, + strategy + }); + if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { + return { + reset: { + rects: resetRects + } + }; + } + return {}; + } + }; +}; + +const originSides = /*#__PURE__*/new Set(['left', 'top']); + +// For type backwards-compatibility, the `OffsetOptions` type was also +// Derivable. + +async function convertValueToCoords(state, options) { + const { + placement, + platform, + elements + } = state; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isVertical = getSideAxis(placement) === 'y'; + const mainAxisMulti = originSides.has(side) ? -1 : 1; + const crossAxisMulti = rtl && isVertical ? -1 : 1; + const rawValue = evaluate(options, state); + + // eslint-disable-next-line prefer-const + let { + mainAxis, + crossAxis, + alignmentAxis + } = typeof rawValue === 'number' ? { + mainAxis: rawValue, + crossAxis: 0, + alignmentAxis: null + } : { + mainAxis: rawValue.mainAxis || 0, + crossAxis: rawValue.crossAxis || 0, + alignmentAxis: rawValue.alignmentAxis + }; + if (alignment && typeof alignmentAxis === 'number') { + crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; + } + return isVertical ? { + x: crossAxis * crossAxisMulti, + y: mainAxis * mainAxisMulti + } : { + x: mainAxis * mainAxisMulti, + y: crossAxis * crossAxisMulti + }; +} + +/** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ +const offset = function (options) { + if (options === void 0) { + options = 0; + } + return { + name: 'offset', + options, + async fn(state) { + var _middlewareData$offse, _middlewareData$arrow; + const { + x, + y, + placement, + middlewareData + } = state; + const diffCoords = await convertValueToCoords(state, options); + + // If the placement is the same and the arrow caused an alignment offset + // then we don't need to change the positioning coordinates. + if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + return { + x: x + diffCoords.x, + y: y + diffCoords.y, + data: { + ...diffCoords, + placement + } + }; + } + }; +}; + +/** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ +const shift = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'shift', + options, + async fn(state) { + const { + x, + y, + placement, + platform + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = false, + limiter = { + fn: _ref => { + let { + x, + y + } = _ref; + return { + x, + y + }; + } + }, + ...detectOverflowOptions + } = evaluate(options, state); + const coords = { + x, + y + }; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const crossAxis = getSideAxis(getSide(placement)); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + if (checkMainAxis) { + const minSide = mainAxis === 'y' ? 'top' : 'left'; + const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; + const min = mainAxisCoord + overflow[minSide]; + const max = mainAxisCoord - overflow[maxSide]; + mainAxisCoord = clamp(min, mainAxisCoord, max); + } + if (checkCrossAxis) { + const minSide = crossAxis === 'y' ? 'top' : 'left'; + const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; + const min = crossAxisCoord + overflow[minSide]; + const max = crossAxisCoord - overflow[maxSide]; + crossAxisCoord = clamp(min, crossAxisCoord, max); + } + const limitedCoords = limiter.fn({ + ...state, + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }); + return { + ...limitedCoords, + data: { + x: limitedCoords.x - x, + y: limitedCoords.y - y, + enabled: { + [mainAxis]: checkMainAxis, + [crossAxis]: checkCrossAxis + } + } + }; + } + }; +}; +/** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ +const limitShift = function (options) { + if (options === void 0) { + options = {}; + } + return { + options, + fn(state) { + const { + x, + y, + placement, + rects, + middlewareData + } = state; + const { + offset = 0, + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true + } = evaluate(options, state); + const coords = { + x, + y + }; + const crossAxis = getSideAxis(placement); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + const rawOffset = evaluate(offset, state); + const computedOffset = typeof rawOffset === 'number' ? { + mainAxis: rawOffset, + crossAxis: 0 + } : { + mainAxis: 0, + crossAxis: 0, + ...rawOffset + }; + if (checkMainAxis) { + const len = mainAxis === 'y' ? 'height' : 'width'; + const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; + const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; + if (mainAxisCoord < limitMin) { + mainAxisCoord = limitMin; + } else if (mainAxisCoord > limitMax) { + mainAxisCoord = limitMax; + } + } + if (checkCrossAxis) { + var _middlewareData$offse, _middlewareData$offse2; + const len = mainAxis === 'y' ? 'width' : 'height'; + const isOriginSide = originSides.has(getSide(placement)); + const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); + const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); + if (crossAxisCoord < limitMin) { + crossAxisCoord = limitMin; + } else if (crossAxisCoord > limitMax) { + crossAxisCoord = limitMax; + } + } + return { + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }; + } + }; +}; + +/** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ +const size = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'size', + options, + async fn(state) { + var _state$middlewareData, _state$middlewareData2; + const { + placement, + rects, + platform, + elements + } = state; + const { + apply = () => {}, + ...detectOverflowOptions + } = evaluate(options, state); + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isYAxis = getSideAxis(placement) === 'y'; + const { + width, + height + } = rects.floating; + let heightSide; + let widthSide; + if (side === 'top' || side === 'bottom') { + heightSide = side; + widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; + } else { + widthSide = side; + heightSide = alignment === 'end' ? 'top' : 'bottom'; + } + const maximumClippingHeight = height - overflow.top - overflow.bottom; + const maximumClippingWidth = width - overflow.left - overflow.right; + const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); + const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); + const noShift = !state.middlewareData.shift; + let availableHeight = overflowAvailableHeight; + let availableWidth = overflowAvailableWidth; + if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { + availableWidth = maximumClippingWidth; + } + if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { + availableHeight = maximumClippingHeight; + } + if (noShift && !alignment) { + const xMin = max(overflow.left, 0); + const xMax = max(overflow.right, 0); + const yMin = max(overflow.top, 0); + const yMax = max(overflow.bottom, 0); + if (isYAxis) { + availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); + } else { + availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); + } + } + await apply({ + ...state, + availableWidth, + availableHeight + }); + const nextDimensions = await platform.getDimensions(elements.floating); + if (width !== nextDimensions.width || height !== nextDimensions.height) { + return { + reset: { + rects: true + } + }; + } + return {}; + } + }; +}; + +export { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size }; diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.umd.js b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.umd.js new file mode 100644 index 00000000..0f6b67f5 --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.umd.js @@ -0,0 +1,1203 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FloatingUICore = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Custom positioning reference element. + * @see https://floating-ui.com/docs/virtual-elements + */ + + const sides = ['top', 'right', 'bottom', 'left']; + const alignments = ['start', 'end']; + const placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), []); + const min = Math.min; + const max = Math.max; + const oppositeSideMap = { + left: 'right', + right: 'left', + bottom: 'top', + top: 'bottom' + }; + const oppositeAlignmentMap = { + start: 'end', + end: 'start' + }; + function clamp(start, value, end) { + return max(start, min(value, end)); + } + function evaluate(value, param) { + return typeof value === 'function' ? value(param) : value; + } + function getSide(placement) { + return placement.split('-')[0]; + } + function getAlignment(placement) { + return placement.split('-')[1]; + } + function getOppositeAxis(axis) { + return axis === 'x' ? 'y' : 'x'; + } + function getAxisLength(axis) { + return axis === 'y' ? 'height' : 'width'; + } + const yAxisSides = /*#__PURE__*/new Set(['top', 'bottom']); + function getSideAxis(placement) { + return yAxisSides.has(getSide(placement)) ? 'y' : 'x'; + } + function getAlignmentAxis(placement) { + return getOppositeAxis(getSideAxis(placement)); + } + function getAlignmentSides(placement, rects, rtl) { + if (rtl === void 0) { + rtl = false; + } + const alignment = getAlignment(placement); + const alignmentAxis = getAlignmentAxis(placement); + const length = getAxisLength(alignmentAxis); + let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top'; + if (rects.reference[length] > rects.floating[length]) { + mainAlignmentSide = getOppositePlacement(mainAlignmentSide); + } + return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)]; + } + function getExpandedPlacements(placement) { + const oppositePlacement = getOppositePlacement(placement); + return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; + } + function getOppositeAlignmentPlacement(placement) { + return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]); + } + const lrPlacement = ['left', 'right']; + const rlPlacement = ['right', 'left']; + const tbPlacement = ['top', 'bottom']; + const btPlacement = ['bottom', 'top']; + function getSideList(side, isStart, rtl) { + switch (side) { + case 'top': + case 'bottom': + if (rtl) return isStart ? rlPlacement : lrPlacement; + return isStart ? lrPlacement : rlPlacement; + case 'left': + case 'right': + return isStart ? tbPlacement : btPlacement; + default: + return []; + } + } + function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { + const alignment = getAlignment(placement); + let list = getSideList(getSide(placement), direction === 'start', rtl); + if (alignment) { + list = list.map(side => side + "-" + alignment); + if (flipAlignment) { + list = list.concat(list.map(getOppositeAlignmentPlacement)); + } + } + return list; + } + function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]); + } + function expandPaddingObject(padding) { + return { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...padding + }; + } + function getPaddingObject(padding) { + return typeof padding !== 'number' ? expandPaddingObject(padding) : { + top: padding, + right: padding, + bottom: padding, + left: padding + }; + } + function rectToClientRect(rect) { + const { + x, + y, + width, + height + } = rect; + return { + width, + height, + top: y, + left: x, + right: x + width, + bottom: y + height, + x, + y + }; + } + + function computeCoordsFromPlacement(_ref, placement, rtl) { + let { + reference, + floating + } = _ref; + const sideAxis = getSideAxis(placement); + const alignmentAxis = getAlignmentAxis(placement); + const alignLength = getAxisLength(alignmentAxis); + const side = getSide(placement); + const isVertical = sideAxis === 'y'; + const commonX = reference.x + reference.width / 2 - floating.width / 2; + const commonY = reference.y + reference.height / 2 - floating.height / 2; + const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; + let coords; + switch (side) { + case 'top': + coords = { + x: commonX, + y: reference.y - floating.height + }; + break; + case 'bottom': + coords = { + x: commonX, + y: reference.y + reference.height + }; + break; + case 'right': + coords = { + x: reference.x + reference.width, + y: commonY + }; + break; + case 'left': + coords = { + x: reference.x - floating.width, + y: commonY + }; + break; + default: + coords = { + x: reference.x, + y: reference.y + }; + } + switch (getAlignment(placement)) { + case 'start': + coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); + break; + case 'end': + coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); + break; + } + return coords; + } + + /** + * Resolves with an object of overflow side offsets that determine how much the + * element is overflowing a given clipping boundary on each side. + * - positive = overflowing the boundary by that number of pixels + * - negative = how many pixels left before it will overflow + * - 0 = lies flush with the boundary + * @see https://floating-ui.com/docs/detectOverflow + */ + async function detectOverflow(state, options) { + var _await$platform$isEle; + if (options === void 0) { + options = {}; + } + const { + x, + y, + platform, + rects, + elements, + strategy + } = state; + const { + boundary = 'clippingAncestors', + rootBoundary = 'viewport', + elementContext = 'floating', + altBoundary = false, + padding = 0 + } = evaluate(options, state); + const paddingObject = getPaddingObject(padding); + const altContext = elementContext === 'floating' ? 'reference' : 'floating'; + const element = elements[altBoundary ? altContext : elementContext]; + const clippingClientRect = rectToClientRect(await platform.getClippingRect({ + element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))), + boundary, + rootBoundary, + strategy + })); + const rect = elementContext === 'floating' ? { + x, + y, + width: rects.floating.width, + height: rects.floating.height + } : rects.reference; + const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating)); + const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || { + x: 1, + y: 1 + } : { + x: 1, + y: 1 + }; + const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({ + elements, + rect, + offsetParent, + strategy + }) : rect); + return { + top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, + bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, + left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, + right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x + }; + } + + /** + * Computes the `x` and `y` coordinates that will place the floating element + * next to a given reference element. + * + * This export does not have any `platform` interface logic. You will need to + * write one for the platform you are using Floating UI with. + */ + const computePosition = async (reference, floating, config) => { + const { + placement = 'bottom', + strategy = 'absolute', + middleware = [], + platform + } = config; + const validMiddleware = middleware.filter(Boolean); + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating)); + let rects = await platform.getElementRects({ + reference, + floating, + strategy + }); + let { + x, + y + } = computeCoordsFromPlacement(rects, placement, rtl); + let statefulPlacement = placement; + let middlewareData = {}; + let resetCount = 0; + for (let i = 0; i < validMiddleware.length; i++) { + var _platform$detectOverf; + const { + name, + fn + } = validMiddleware[i]; + const { + x: nextX, + y: nextY, + data, + reset + } = await fn({ + x, + y, + initialPlacement: placement, + placement: statefulPlacement, + strategy, + middlewareData, + rects, + platform: { + ...platform, + detectOverflow: (_platform$detectOverf = platform.detectOverflow) != null ? _platform$detectOverf : detectOverflow + }, + elements: { + reference, + floating + } + }); + x = nextX != null ? nextX : x; + y = nextY != null ? nextY : y; + middlewareData = { + ...middlewareData, + [name]: { + ...middlewareData[name], + ...data + } + }; + if (reset && resetCount <= 50) { + resetCount++; + if (typeof reset === 'object') { + if (reset.placement) { + statefulPlacement = reset.placement; + } + if (reset.rects) { + rects = reset.rects === true ? await platform.getElementRects({ + reference, + floating, + strategy + }) : reset.rects; + } + ({ + x, + y + } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); + } + i = -1; + } + } + return { + x, + y, + placement: statefulPlacement, + strategy, + middlewareData + }; + }; + + /** + * Provides data to position an inner element of the floating element so that it + * appears centered to the reference element. + * @see https://floating-ui.com/docs/arrow + */ + const arrow = options => ({ + name: 'arrow', + options, + async fn(state) { + const { + x, + y, + placement, + rects, + platform, + elements, + middlewareData + } = state; + // Since `element` is required, we don't Partial<> the type. + const { + element, + padding = 0 + } = evaluate(options, state) || {}; + if (element == null) { + return {}; + } + const paddingObject = getPaddingObject(padding); + const coords = { + x, + y + }; + const axis = getAlignmentAxis(placement); + const length = getAxisLength(axis); + const arrowDimensions = await platform.getDimensions(element); + const isYAxis = axis === 'y'; + const minProp = isYAxis ? 'top' : 'left'; + const maxProp = isYAxis ? 'bottom' : 'right'; + const clientProp = isYAxis ? 'clientHeight' : 'clientWidth'; + const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; + const startDiff = coords[axis] - rects.reference[axis]; + const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element)); + let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; + + // DOM platform can return `window` as the `offsetParent`. + if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) { + clientSize = elements.floating[clientProp] || rects.floating[length]; + } + const centerToReference = endDiff / 2 - startDiff / 2; + + // If the padding is large enough that it causes the arrow to no longer be + // centered, modify the padding so that it is centered. + const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; + const minPadding = min(paddingObject[minProp], largestPossiblePadding); + const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); + + // Make sure the arrow doesn't overflow the floating element if the center + // point is outside the floating element's bounds. + const min$1 = minPadding; + const max = clientSize - arrowDimensions[length] - maxPadding; + const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; + const offset = clamp(min$1, center, max); + + // If the reference is small enough that the arrow's padding causes it to + // to point to nothing for an aligned placement, adjust the offset of the + // floating element itself. To ensure `shift()` continues to take action, + // a single reset is performed when this is true. + const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; + const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0; + return { + [axis]: coords[axis] + alignmentOffset, + data: { + [axis]: offset, + centerOffset: center - offset - alignmentOffset, + ...(shouldAddOffset && { + alignmentOffset + }) + }, + reset: shouldAddOffset + }; + } + }); + + function getPlacementList(alignment, autoAlignment, allowedPlacements) { + const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement); + return allowedPlacementsSortedByAlignment.filter(placement => { + if (alignment) { + return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false); + } + return true; + }); + } + /** + * Optimizes the visibility of the floating element by choosing the placement + * that has the most space available automatically, without needing to specify a + * preferred placement. Alternative to `flip`. + * @see https://floating-ui.com/docs/autoPlacement + */ + const autoPlacement = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'autoPlacement', + options, + async fn(state) { + var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE; + const { + rects, + middlewareData, + placement, + platform, + elements + } = state; + const { + crossAxis = false, + alignment, + allowedPlacements = placements, + autoAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0; + const currentPlacement = placements$1[currentIndex]; + if (currentPlacement == null) { + return {}; + } + const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))); + + // Make `computeCoords` start from the right place. + if (placement !== currentPlacement) { + return { + reset: { + placement: placements$1[0] + } + }; + } + const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]]; + const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), { + placement: currentPlacement, + overflows: currentOverflows + }]; + const nextPlacement = placements$1[currentIndex + 1]; + + // There are more placements to check. + if (nextPlacement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: nextPlacement + } + }; + } + const placementsSortedByMostSpace = allOverflows.map(d => { + const alignment = getAlignment(d.placement); + return [d.placement, alignment && crossAxis ? + // Check along the mainAxis and main crossAxis side. + d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) : + // Check only the mainAxis. + d.overflows[0], d.overflows]; + }).sort((a, b) => a[1] - b[1]); + const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0, + // Aligned placements should not check their opposite crossAxis + // side. + getAlignment(d[0]) ? 2 : 3).every(v => v <= 0)); + const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0]; + if (resetPlacement !== placement) { + return { + data: { + index: currentIndex + 1, + overflows: allOverflows + }, + reset: { + placement: resetPlacement + } + }; + } + return {}; + } + }; + }; + + /** + * Optimizes the visibility of the floating element by flipping the `placement` + * in order to keep it in view when the preferred placement(s) will overflow the + * clipping boundary. Alternative to `autoPlacement`. + * @see https://floating-ui.com/docs/flip + */ + const flip = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'flip', + options, + async fn(state) { + var _middlewareData$arrow, _middlewareData$flip; + const { + placement, + middlewareData, + rects, + initialPlacement, + platform, + elements + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true, + fallbackPlacements: specifiedFallbackPlacements, + fallbackStrategy = 'bestFit', + fallbackAxisSideDirection = 'none', + flipAlignment = true, + ...detectOverflowOptions + } = evaluate(options, state); + + // If a reset by the arrow was caused due to an alignment offset being + // added, we should skip any logic now since `flip()` has already done its + // work. + // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643 + if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + const side = getSide(placement); + const initialSideAxis = getSideAxis(initialPlacement); + const isBasePlacement = getSide(initialPlacement) === initialPlacement; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); + const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none'; + if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { + fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); + } + const placements = [initialPlacement, ...fallbackPlacements]; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const overflows = []; + let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; + if (checkMainAxis) { + overflows.push(overflow[side]); + } + if (checkCrossAxis) { + const sides = getAlignmentSides(placement, rects, rtl); + overflows.push(overflow[sides[0]], overflow[sides[1]]); + } + overflowsData = [...overflowsData, { + placement, + overflows + }]; + + // One or more sides is overflowing. + if (!overflows.every(side => side <= 0)) { + var _middlewareData$flip2, _overflowsData$filter; + const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; + const nextPlacement = placements[nextIndex]; + if (nextPlacement) { + const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false; + if (!ignoreCrossAxisOverflow || + // We leave the current main axis only if every placement on that axis + // overflows the main axis. + overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) { + // Try next placement and re-run the lifecycle. + return { + data: { + index: nextIndex, + overflows: overflowsData + }, + reset: { + placement: nextPlacement + } + }; + } + } + + // First, find the candidates that fit on the mainAxis side of overflow, + // then find the placement that fits the best on the main crossAxis side. + let resetPlacement = (_overflowsData$filter = overflowsData.filter(d => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; + + // Otherwise fallback. + if (!resetPlacement) { + switch (fallbackStrategy) { + case 'bestFit': + { + var _overflowsData$filter2; + const placement = (_overflowsData$filter2 = overflowsData.filter(d => { + if (hasFallbackAxisSideDirection) { + const currentSideAxis = getSideAxis(d.placement); + return currentSideAxis === initialSideAxis || + // Create a bias to the `y` side axis due to horizontal + // reading directions favoring greater width. + currentSideAxis === 'y'; + } + return true; + }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; + if (placement) { + resetPlacement = placement; + } + break; + } + case 'initialPlacement': + resetPlacement = initialPlacement; + break; + } + } + if (placement !== resetPlacement) { + return { + reset: { + placement: resetPlacement + } + }; + } + } + return {}; + } + }; + }; + + function getSideOffsets(overflow, rect) { + return { + top: overflow.top - rect.height, + right: overflow.right - rect.width, + bottom: overflow.bottom - rect.height, + left: overflow.left - rect.width + }; + } + function isAnySideFullyClipped(overflow) { + return sides.some(side => overflow[side] >= 0); + } + /** + * Provides data to hide the floating element in applicable situations, such as + * when it is not in the same clipping context as the reference element. + * @see https://floating-ui.com/docs/hide + */ + const hide = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'hide', + options, + async fn(state) { + const { + rects, + platform + } = state; + const { + strategy = 'referenceHidden', + ...detectOverflowOptions + } = evaluate(options, state); + switch (strategy) { + case 'referenceHidden': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + elementContext: 'reference' + }); + const offsets = getSideOffsets(overflow, rects.reference); + return { + data: { + referenceHiddenOffsets: offsets, + referenceHidden: isAnySideFullyClipped(offsets) + } + }; + } + case 'escaped': + { + const overflow = await platform.detectOverflow(state, { + ...detectOverflowOptions, + altBoundary: true + }); + const offsets = getSideOffsets(overflow, rects.floating); + return { + data: { + escapedOffsets: offsets, + escaped: isAnySideFullyClipped(offsets) + } + }; + } + default: + { + return {}; + } + } + } + }; + }; + + function getBoundingRect(rects) { + const minX = min(...rects.map(rect => rect.left)); + const minY = min(...rects.map(rect => rect.top)); + const maxX = max(...rects.map(rect => rect.right)); + const maxY = max(...rects.map(rect => rect.bottom)); + return { + x: minX, + y: minY, + width: maxX - minX, + height: maxY - minY + }; + } + function getRectsByLine(rects) { + const sortedRects = rects.slice().sort((a, b) => a.y - b.y); + const groups = []; + let prevRect = null; + for (let i = 0; i < sortedRects.length; i++) { + const rect = sortedRects[i]; + if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) { + groups.push([rect]); + } else { + groups[groups.length - 1].push(rect); + } + prevRect = rect; + } + return groups.map(rect => rectToClientRect(getBoundingRect(rect))); + } + /** + * Provides improved positioning for inline reference elements that can span + * over multiple lines, such as hyperlinks or range selections. + * @see https://floating-ui.com/docs/inline + */ + const inline = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'inline', + options, + async fn(state) { + const { + placement, + elements, + rects, + platform, + strategy + } = state; + // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a + // ClientRect's bounds, despite the event listener being triggered. A + // padding of 2 seems to handle this issue. + const { + padding = 2, + x, + y + } = evaluate(options, state); + const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []); + const clientRects = getRectsByLine(nativeClientRects); + const fallback = rectToClientRect(getBoundingRect(nativeClientRects)); + const paddingObject = getPaddingObject(padding); + function getBoundingClientRect() { + // There are two rects and they are disjoined. + if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) { + // Find the first rect in which the point is fully inside. + return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback; + } + + // There are 2 or more connected rects. + if (clientRects.length >= 2) { + if (getSideAxis(placement) === 'y') { + const firstRect = clientRects[0]; + const lastRect = clientRects[clientRects.length - 1]; + const isTop = getSide(placement) === 'top'; + const top = firstRect.top; + const bottom = lastRect.bottom; + const left = isTop ? firstRect.left : lastRect.left; + const right = isTop ? firstRect.right : lastRect.right; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + const isLeftSide = getSide(placement) === 'left'; + const maxRight = max(...clientRects.map(rect => rect.right)); + const minLeft = min(...clientRects.map(rect => rect.left)); + const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight); + const top = measureRects[0].top; + const bottom = measureRects[measureRects.length - 1].bottom; + const left = minLeft; + const right = maxRight; + const width = right - left; + const height = bottom - top; + return { + top, + bottom, + left, + right, + width, + height, + x: left, + y: top + }; + } + return fallback; + } + const resetRects = await platform.getElementRects({ + reference: { + getBoundingClientRect + }, + floating: elements.floating, + strategy + }); + if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) { + return { + reset: { + rects: resetRects + } + }; + } + return {}; + } + }; + }; + + const originSides = /*#__PURE__*/new Set(['left', 'top']); + + // For type backwards-compatibility, the `OffsetOptions` type was also + // Derivable. + + async function convertValueToCoords(state, options) { + const { + placement, + platform, + elements + } = state; + const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isVertical = getSideAxis(placement) === 'y'; + const mainAxisMulti = originSides.has(side) ? -1 : 1; + const crossAxisMulti = rtl && isVertical ? -1 : 1; + const rawValue = evaluate(options, state); + + // eslint-disable-next-line prefer-const + let { + mainAxis, + crossAxis, + alignmentAxis + } = typeof rawValue === 'number' ? { + mainAxis: rawValue, + crossAxis: 0, + alignmentAxis: null + } : { + mainAxis: rawValue.mainAxis || 0, + crossAxis: rawValue.crossAxis || 0, + alignmentAxis: rawValue.alignmentAxis + }; + if (alignment && typeof alignmentAxis === 'number') { + crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis; + } + return isVertical ? { + x: crossAxis * crossAxisMulti, + y: mainAxis * mainAxisMulti + } : { + x: mainAxis * mainAxisMulti, + y: crossAxis * crossAxisMulti + }; + } + + /** + * Modifies the placement by translating the floating element along the + * specified axes. + * A number (shorthand for `mainAxis` or distance), or an axes configuration + * object may be passed. + * @see https://floating-ui.com/docs/offset + */ + const offset = function (options) { + if (options === void 0) { + options = 0; + } + return { + name: 'offset', + options, + async fn(state) { + var _middlewareData$offse, _middlewareData$arrow; + const { + x, + y, + placement, + middlewareData + } = state; + const diffCoords = await convertValueToCoords(state, options); + + // If the placement is the same and the arrow caused an alignment offset + // then we don't need to change the positioning coordinates. + if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { + return {}; + } + return { + x: x + diffCoords.x, + y: y + diffCoords.y, + data: { + ...diffCoords, + placement + } + }; + } + }; + }; + + /** + * Optimizes the visibility of the floating element by shifting it in order to + * keep it in view when it will overflow the clipping boundary. + * @see https://floating-ui.com/docs/shift + */ + const shift = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'shift', + options, + async fn(state) { + const { + x, + y, + placement, + platform + } = state; + const { + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = false, + limiter = { + fn: _ref => { + let { + x, + y + } = _ref; + return { + x, + y + }; + } + }, + ...detectOverflowOptions + } = evaluate(options, state); + const coords = { + x, + y + }; + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const crossAxis = getSideAxis(getSide(placement)); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + if (checkMainAxis) { + const minSide = mainAxis === 'y' ? 'top' : 'left'; + const maxSide = mainAxis === 'y' ? 'bottom' : 'right'; + const min = mainAxisCoord + overflow[minSide]; + const max = mainAxisCoord - overflow[maxSide]; + mainAxisCoord = clamp(min, mainAxisCoord, max); + } + if (checkCrossAxis) { + const minSide = crossAxis === 'y' ? 'top' : 'left'; + const maxSide = crossAxis === 'y' ? 'bottom' : 'right'; + const min = crossAxisCoord + overflow[minSide]; + const max = crossAxisCoord - overflow[maxSide]; + crossAxisCoord = clamp(min, crossAxisCoord, max); + } + const limitedCoords = limiter.fn({ + ...state, + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }); + return { + ...limitedCoords, + data: { + x: limitedCoords.x - x, + y: limitedCoords.y - y, + enabled: { + [mainAxis]: checkMainAxis, + [crossAxis]: checkCrossAxis + } + } + }; + } + }; + }; + /** + * Built-in `limiter` that will stop `shift()` at a certain point. + */ + const limitShift = function (options) { + if (options === void 0) { + options = {}; + } + return { + options, + fn(state) { + const { + x, + y, + placement, + rects, + middlewareData + } = state; + const { + offset = 0, + mainAxis: checkMainAxis = true, + crossAxis: checkCrossAxis = true + } = evaluate(options, state); + const coords = { + x, + y + }; + const crossAxis = getSideAxis(placement); + const mainAxis = getOppositeAxis(crossAxis); + let mainAxisCoord = coords[mainAxis]; + let crossAxisCoord = coords[crossAxis]; + const rawOffset = evaluate(offset, state); + const computedOffset = typeof rawOffset === 'number' ? { + mainAxis: rawOffset, + crossAxis: 0 + } : { + mainAxis: 0, + crossAxis: 0, + ...rawOffset + }; + if (checkMainAxis) { + const len = mainAxis === 'y' ? 'height' : 'width'; + const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; + const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; + if (mainAxisCoord < limitMin) { + mainAxisCoord = limitMin; + } else if (mainAxisCoord > limitMax) { + mainAxisCoord = limitMax; + } + } + if (checkCrossAxis) { + var _middlewareData$offse, _middlewareData$offse2; + const len = mainAxis === 'y' ? 'width' : 'height'; + const isOriginSide = originSides.has(getSide(placement)); + const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); + const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); + if (crossAxisCoord < limitMin) { + crossAxisCoord = limitMin; + } else if (crossAxisCoord > limitMax) { + crossAxisCoord = limitMax; + } + } + return { + [mainAxis]: mainAxisCoord, + [crossAxis]: crossAxisCoord + }; + } + }; + }; + + /** + * Provides data that allows you to change the size of the floating element — + * for instance, prevent it from overflowing the clipping boundary or match the + * width of the reference element. + * @see https://floating-ui.com/docs/size + */ + const size = function (options) { + if (options === void 0) { + options = {}; + } + return { + name: 'size', + options, + async fn(state) { + var _state$middlewareData, _state$middlewareData2; + const { + placement, + rects, + platform, + elements + } = state; + const { + apply = () => {}, + ...detectOverflowOptions + } = evaluate(options, state); + const overflow = await platform.detectOverflow(state, detectOverflowOptions); + const side = getSide(placement); + const alignment = getAlignment(placement); + const isYAxis = getSideAxis(placement) === 'y'; + const { + width, + height + } = rects.floating; + let heightSide; + let widthSide; + if (side === 'top' || side === 'bottom') { + heightSide = side; + widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right'; + } else { + widthSide = side; + heightSide = alignment === 'end' ? 'top' : 'bottom'; + } + const maximumClippingHeight = height - overflow.top - overflow.bottom; + const maximumClippingWidth = width - overflow.left - overflow.right; + const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); + const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); + const noShift = !state.middlewareData.shift; + let availableHeight = overflowAvailableHeight; + let availableWidth = overflowAvailableWidth; + if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { + availableWidth = maximumClippingWidth; + } + if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { + availableHeight = maximumClippingHeight; + } + if (noShift && !alignment) { + const xMin = max(overflow.left, 0); + const xMax = max(overflow.right, 0); + const yMin = max(overflow.top, 0); + const yMax = max(overflow.bottom, 0); + if (isYAxis) { + availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); + } else { + availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); + } + } + await apply({ + ...state, + availableWidth, + availableHeight + }); + const nextDimensions = await platform.getDimensions(elements.floating); + if (width !== nextDimensions.width || height !== nextDimensions.height) { + return { + reset: { + rects: true + } + }; + } + return {}; + } + }; + }; + + exports.arrow = arrow; + exports.autoPlacement = autoPlacement; + exports.computePosition = computePosition; + exports.detectOverflow = detectOverflow; + exports.flip = flip; + exports.hide = hide; + exports.inline = inline; + exports.limitShift = limitShift; + exports.offset = offset; + exports.rectToClientRect = rectToClientRect; + exports.shift = shift; + exports.size = size; + +})); diff --git a/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.umd.min.js b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.umd.min.js new file mode 100644 index 00000000..3bda0631 --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/dist/floating-ui.core.umd.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).FloatingUICore={})}(this,(function(t){"use strict";const e=["top","right","bottom","left"],n=["start","end"],i=e.reduce(((t,e)=>t.concat(e,e+"-"+n[0],e+"-"+n[1])),[]),o=Math.min,r=Math.max,a={left:"right",right:"left",bottom:"top",top:"bottom"},l={start:"end",end:"start"};function s(t,e,n){return r(t,o(e,n))}function f(t,e){return"function"==typeof t?t(e):t}function c(t){return t.split("-")[0]}function m(t){return t.split("-")[1]}function u(t){return"x"===t?"y":"x"}function d(t){return"y"===t?"height":"width"}const g=new Set(["top","bottom"]);function p(t){return g.has(c(t))?"y":"x"}function h(t){return u(p(t))}function y(t,e,n){void 0===n&&(n=!1);const i=m(t),o=h(t),r=d(o);let a="x"===o?i===(n?"end":"start")?"right":"left":"start"===i?"bottom":"top";return e.reference[r]>e.floating[r]&&(a=O(a)),[a,O(a)]}function w(t){return t.replace(/start|end/g,(t=>l[t]))}const x=["left","right"],v=["right","left"],b=["top","bottom"],A=["bottom","top"];function R(t,e,n,i){const o=m(t);let r=function(t,e,n){switch(t){case"top":case"bottom":return n?e?v:x:e?x:v;case"left":case"right":return e?b:A;default:return[]}}(c(t),"start"===n,i);return o&&(r=r.map((t=>t+"-"+o)),e&&(r=r.concat(r.map(w)))),r}function O(t){return t.replace(/left|right|bottom|top/g,(t=>a[t]))}function P(t){return"number"!=typeof t?function(t){return{top:0,right:0,bottom:0,left:0,...t}}(t):{top:t,right:t,bottom:t,left:t}}function D(t){const{x:e,y:n,width:i,height:o}=t;return{width:i,height:o,top:n,left:e,right:e+i,bottom:n+o,x:e,y:n}}function T(t,e,n){let{reference:i,floating:o}=t;const r=p(e),a=h(e),l=d(a),s=c(e),f="y"===r,u=i.x+i.width/2-o.width/2,g=i.y+i.height/2-o.height/2,y=i[l]/2-o[l]/2;let w;switch(s){case"top":w={x:u,y:i.y-o.height};break;case"bottom":w={x:u,y:i.y+i.height};break;case"right":w={x:i.x+i.width,y:g};break;case"left":w={x:i.x-o.width,y:g};break;default:w={x:i.x,y:i.y}}switch(m(e)){case"start":w[a]-=y*(n&&f?-1:1);break;case"end":w[a]+=y*(n&&f?-1:1)}return w}async function E(t,e){var n;void 0===e&&(e={});const{x:i,y:o,platform:r,rects:a,elements:l,strategy:s}=t,{boundary:c="clippingAncestors",rootBoundary:m="viewport",elementContext:u="floating",altBoundary:d=!1,padding:g=0}=f(e,t),p=P(g),h=l[d?"floating"===u?"reference":"floating":u],y=D(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(h)))||n?h:h.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(l.floating)),boundary:c,rootBoundary:m,strategy:s})),w="floating"===u?{x:i,y:o,width:a.floating.width,height:a.floating.height}:a.reference,x=await(null==r.getOffsetParent?void 0:r.getOffsetParent(l.floating)),v=await(null==r.isElement?void 0:r.isElement(x))&&await(null==r.getScale?void 0:r.getScale(x))||{x:1,y:1},b=D(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:w,offsetParent:x,strategy:s}):w);return{top:(y.top-b.top+p.top)/v.y,bottom:(b.bottom-y.bottom+p.bottom)/v.y,left:(y.left-b.left+p.left)/v.x,right:(b.right-y.right+p.right)/v.x}}function L(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function k(t){return e.some((e=>t[e]>=0))}function C(t){const e=o(...t.map((t=>t.left))),n=o(...t.map((t=>t.top)));return{x:e,y:n,width:r(...t.map((t=>t.right)))-e,height:r(...t.map((t=>t.bottom)))-n}}const S=new Set(["left","top"]);t.arrow=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:i,placement:r,rects:a,platform:l,elements:c,middlewareData:u}=e,{element:g,padding:p=0}=f(t,e)||{};if(null==g)return{};const y=P(p),w={x:n,y:i},x=h(r),v=d(x),b=await l.getDimensions(g),A="y"===x,R=A?"top":"left",O=A?"bottom":"right",D=A?"clientHeight":"clientWidth",T=a.reference[v]+a.reference[x]-w[x]-a.floating[v],E=w[x]-a.reference[x],L=await(null==l.getOffsetParent?void 0:l.getOffsetParent(g));let k=L?L[D]:0;k&&await(null==l.isElement?void 0:l.isElement(L))||(k=c.floating[D]||a.floating[v]);const C=T/2-E/2,S=k/2-b[v]/2-1,B=o(y[R],S),H=o(y[O],S),F=B,j=k-b[v]-H,z=k/2-b[v]/2+C,M=s(F,z,j),V=!u.arrow&&null!=m(r)&&z!==M&&a.reference[v]/2-(zm(e)===t)),...n.filter((e=>m(e)!==t))]:n.filter((t=>c(t)===t))).filter((n=>!t||m(n)===t||!!e&&w(n)!==n))}(p||null,x,h):h,A=await u.detectOverflow(e,v),R=(null==(n=l.autoPlacement)?void 0:n.index)||0,O=b[R];if(null==O)return{};const P=y(O,a,await(null==u.isRTL?void 0:u.isRTL(d.floating)));if(s!==O)return{reset:{placement:b[0]}};const D=[A[c(O)],A[P[0]],A[P[1]]],T=[...(null==(o=l.autoPlacement)?void 0:o.overflows)||[],{placement:O,overflows:D}],E=b[R+1];if(E)return{data:{index:R+1,overflows:T},reset:{placement:E}};const L=T.map((t=>{const e=m(t.placement);return[t.placement,e&&g?t.overflows.slice(0,2).reduce(((t,e)=>t+e),0):t.overflows[0],t.overflows]})).sort(((t,e)=>t[1]-e[1])),k=(null==(r=L.filter((t=>t[2].slice(0,m(t[0])?2:3).every((t=>t<=0))))[0])?void 0:r[0])||L[0][0];return k!==s?{data:{index:R+1,overflows:T},reset:{placement:k}}:{}}}},t.computePosition=async(t,e,n)=>{const{placement:i="bottom",strategy:o="absolute",middleware:r=[],platform:a}=n,l=r.filter(Boolean),s=await(null==a.isRTL?void 0:a.isRTL(e));let f=await a.getElementRects({reference:t,floating:e,strategy:o}),{x:c,y:m}=T(f,i,s),u=i,d={},g=0;for(let n=0;nt<=0))){var H,F;const t=((null==(H=r.flip)?void 0:H.index)||0)+1,e=k[t];if(e){if(!("alignment"===d&&P!==p(e))||B.every((t=>p(t.placement)!==P||t.overflows[0]>0)))return{data:{index:t,overflows:B},reset:{placement:e}}}let n=null==(F=B.filter((t=>t.overflows[0]<=0)).sort(((t,e)=>t.overflows[1]-e.overflows[1]))[0])?void 0:F.placement;if(!n)switch(h){case"bestFit":{var j;const t=null==(j=B.filter((t=>{if(L){const e=p(t.placement);return e===P||"y"===e}return!0})).map((t=>[t.placement,t.overflows.filter((t=>t>0)).reduce(((t,e)=>t+e),0)])).sort(((t,e)=>t[1]-e[1]))[0])?void 0:j[0];t&&(n=t);break}case"initialPlacement":n=l}if(o!==n)return{reset:{placement:n}}}return{}}}},t.hide=function(t){return void 0===t&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n,platform:i}=e,{strategy:o="referenceHidden",...r}=f(t,e);switch(o){case"referenceHidden":{const t=L(await i.detectOverflow(e,{...r,elementContext:"reference"}),n.reference);return{data:{referenceHiddenOffsets:t,referenceHidden:k(t)}}}case"escaped":{const t=L(await i.detectOverflow(e,{...r,altBoundary:!0}),n.floating);return{data:{escapedOffsets:t,escaped:k(t)}}}default:return{}}}}},t.inline=function(t){return void 0===t&&(t={}),{name:"inline",options:t,async fn(e){const{placement:n,elements:i,rects:a,platform:l,strategy:s}=e,{padding:m=2,x:u,y:d}=f(t,e),g=Array.from(await(null==l.getClientRects?void 0:l.getClientRects(i.reference))||[]),h=function(t){const e=t.slice().sort(((t,e)=>t.y-e.y)),n=[];let i=null;for(let t=0;ti.height/2?n.push([o]):n[n.length-1].push(o),i=o}return n.map((t=>D(C(t))))}(g),y=D(C(g)),w=P(m);const x=await l.getElementRects({reference:{getBoundingClientRect:function(){if(2===h.length&&h[0].left>h[1].right&&null!=u&&null!=d)return h.find((t=>u>t.left-w.left&&ut.top-w.top&&d=2){if("y"===p(n)){const t=h[0],e=h[h.length-1],i="top"===c(n),o=t.top,r=e.bottom,a=i?t.left:e.left,l=i?t.right:e.right;return{top:o,bottom:r,left:a,right:l,width:l-a,height:r-o,x:a,y:o}}const t="left"===c(n),e=r(...h.map((t=>t.right))),i=o(...h.map((t=>t.left))),a=h.filter((n=>t?n.left===i:n.right===e)),l=a[0].top,s=a[a.length-1].bottom;return{top:l,bottom:s,left:i,right:e,width:e-i,height:s-l,x:i,y:l}}return y}},floating:i.floating,strategy:s});return a.reference.x!==x.reference.x||a.reference.y!==x.reference.y||a.reference.width!==x.reference.width||a.reference.height!==x.reference.height?{reset:{rects:x}}:{}}}},t.limitShift=function(t){return void 0===t&&(t={}),{options:t,fn(e){const{x:n,y:i,placement:o,rects:r,middlewareData:a}=e,{offset:l=0,mainAxis:s=!0,crossAxis:m=!0}=f(t,e),d={x:n,y:i},g=p(o),h=u(g);let y=d[h],w=d[g];const x=f(l,e),v="number"==typeof x?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(s){const t="y"===h?"height":"width",e=r.reference[h]-r.floating[t]+v.mainAxis,n=r.reference[h]+r.reference[t]-v.mainAxis;yn&&(y=n)}if(m){var b,A;const t="y"===h?"width":"height",e=S.has(c(o)),n=r.reference[g]-r.floating[t]+(e&&(null==(b=a.offset)?void 0:b[g])||0)+(e?0:v.crossAxis),i=r.reference[g]+r.reference[t]+(e?0:(null==(A=a.offset)?void 0:A[g])||0)-(e?v.crossAxis:0);wi&&(w=i)}return{[h]:y,[g]:w}}}},t.offset=function(t){return void 0===t&&(t=0),{name:"offset",options:t,async fn(e){var n,i;const{x:o,y:r,placement:a,middlewareData:l}=e,s=await async function(t,e){const{placement:n,platform:i,elements:o}=t,r=await(null==i.isRTL?void 0:i.isRTL(o.floating)),a=c(n),l=m(n),s="y"===p(n),u=S.has(a)?-1:1,d=r&&s?-1:1,g=f(e,t);let{mainAxis:h,crossAxis:y,alignmentAxis:w}="number"==typeof g?{mainAxis:g,crossAxis:0,alignmentAxis:null}:{mainAxis:g.mainAxis||0,crossAxis:g.crossAxis||0,alignmentAxis:g.alignmentAxis};return l&&"number"==typeof w&&(y="end"===l?-1*w:w),s?{x:y*d,y:h*u}:{x:h*u,y:y*d}}(e,t);return a===(null==(n=l.offset)?void 0:n.placement)&&null!=(i=l.arrow)&&i.alignmentOffset?{}:{x:o+s.x,y:r+s.y,data:{...s,placement:a}}}}},t.rectToClientRect=D,t.shift=function(t){return void 0===t&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:i,placement:o,platform:r}=e,{mainAxis:a=!0,crossAxis:l=!1,limiter:m={fn:t=>{let{x:e,y:n}=t;return{x:e,y:n}}},...d}=f(t,e),g={x:n,y:i},h=await r.detectOverflow(e,d),y=p(c(o)),w=u(y);let x=g[w],v=g[y];if(a){const t="y"===w?"bottom":"right";x=s(x+h["y"===w?"top":"left"],x,x-h[t])}if(l){const t="y"===y?"bottom":"right";v=s(v+h["y"===y?"top":"left"],v,v-h[t])}const b=m.fn({...e,[w]:x,[y]:v});return{...b,data:{x:b.x-n,y:b.y-i,enabled:{[w]:a,[y]:l}}}}}},t.size=function(t){return void 0===t&&(t={}),{name:"size",options:t,async fn(e){var n,i;const{placement:a,rects:l,platform:s,elements:u}=e,{apply:d=()=>{},...g}=f(t,e),h=await s.detectOverflow(e,g),y=c(a),w=m(a),x="y"===p(a),{width:v,height:b}=l.floating;let A,R;"top"===y||"bottom"===y?(A=y,R=w===(await(null==s.isRTL?void 0:s.isRTL(u.floating))?"start":"end")?"left":"right"):(R=y,A="end"===w?"top":"bottom");const O=b-h.top-h.bottom,P=v-h.left-h.right,D=o(b-h[A],O),T=o(v-h[R],P),E=!e.middlewareData.shift;let L=D,k=T;if(null!=(n=e.middlewareData.shift)&&n.enabled.x&&(k=P),null!=(i=e.middlewareData.shift)&&i.enabled.y&&(L=O),E&&!w){const t=r(h.left,0),e=r(h.right,0),n=r(h.top,0),i=r(h.bottom,0);x?k=v-2*(0!==t||0!==e?t+e:r(h.left,h.right)):L=b-2*(0!==n||0!==i?n+i:r(h.top,h.bottom))}await d({...e,availableWidth:k,availableHeight:L});const C=await s.getDimensions(u.floating);return v!==C.width||b!==C.height?{reset:{rects:!0}}:{}}}}})); diff --git a/frontend/node_modules/@floating-ui/core/package.json b/frontend/node_modules/@floating-ui/core/package.json new file mode 100644 index 00000000..0cd5ce81 --- /dev/null +++ b/frontend/node_modules/@floating-ui/core/package.json @@ -0,0 +1,63 @@ +{ + "name": "@floating-ui/core", + "version": "1.7.4", + "description": "Positioning library for floating elements: tooltips, popovers, dropdowns, and more", + "publishConfig": { + "access": "public" + }, + "main": "./dist/floating-ui.core.umd.js", + "module": "./dist/floating-ui.core.esm.js", + "unpkg": "./dist/floating-ui.core.umd.min.js", + "types": "./dist/floating-ui.core.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/floating-ui.core.d.mts", + "default": "./dist/floating-ui.core.mjs" + }, + "types": "./dist/floating-ui.core.d.ts", + "module": "./dist/floating-ui.core.esm.js", + "default": "./dist/floating-ui.core.umd.js" + } + }, + "sideEffects": false, + "files": [ + "dist" + ], + "author": "atomiks", + "license": "MIT", + "bugs": "https://github.com/floating-ui/floating-ui", + "repository": { + "type": "git", + "url": "https://github.com/floating-ui/floating-ui.git", + "directory": "packages/core" + }, + "homepage": "https://floating-ui.com", + "keywords": [ + "tooltip", + "popover", + "dropdown", + "menu", + "popup", + "positioning" + ], + "dependencies": { + "@floating-ui/utils": "^0.2.10" + }, + "devDependencies": { + "config": "0.0.0" + }, + "scripts": { + "test": "vitest run", + "test:watch": "vitest watch", + "lint": "eslint .", + "format": "prettier --write .", + "clean": "rimraf dist out-tsc", + "dev": "rollup -c -w", + "build": "rollup -c", + "build:api": "build-api --tsc tsconfig.lib.json", + "publint": "publint", + "typecheck": "tsc -b" + } +} \ No newline at end of file diff --git a/frontend/node_modules/@floating-ui/dom/LICENSE b/frontend/node_modules/@floating-ui/dom/LICENSE new file mode 100644 index 00000000..639cdc6c --- /dev/null +++ b/frontend/node_modules/@floating-ui/dom/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2021-present Floating UI 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/@floating-ui/dom/README.md b/frontend/node_modules/@floating-ui/dom/README.md new file mode 100644 index 00000000..47ef9272 --- /dev/null +++ b/frontend/node_modules/@floating-ui/dom/README.md @@ -0,0 +1,4 @@ +# @floating-ui/dom + +This is the library to use Floating UI on the web, wrapping `@floating-ui/core` +with DOM interface logic. diff --git a/frontend/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs b/frontend/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs new file mode 100644 index 00000000..f1d7f07e --- /dev/null +++ b/frontend/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.min.mjs @@ -0,0 +1 @@ +import{rectToClientRect as t,arrow as e,autoPlacement as n,detectOverflow as o,flip as i,hide as r,inline as c,limitShift as l,offset as s,shift as f,size as u,computePosition as a}from"@floating-ui/core";const h=Math.min,d=Math.max,p=Math.round,g=Math.floor,m=t=>({x:t,y:t});function y(){return"undefined"!=typeof window}function w(t){return b(t)?(t.nodeName||"").toLowerCase():"#document"}function x(t){var e;return(null==t||null==(e=t.ownerDocument)?void 0:e.defaultView)||window}function v(t){var e;return null==(e=(b(t)?t.ownerDocument:t.document)||window.document)?void 0:e.documentElement}function b(t){return!!y()&&(t instanceof Node||t instanceof x(t).Node)}function L(t){return!!y()&&(t instanceof Element||t instanceof x(t).Element)}function R(t){return!!y()&&(t instanceof HTMLElement||t instanceof x(t).HTMLElement)}function T(t){return!(!y()||"undefined"==typeof ShadowRoot)&&(t instanceof ShadowRoot||t instanceof x(t).ShadowRoot)}const S=new Set(["inline","contents"]);function C(t){const{overflow:e,overflowX:n,overflowY:o,display:i}=A(t);return/auto|scroll|overlay|hidden|clip/.test(e+o+n)&&!S.has(i)}const E=new Set(["table","td","th"]);function F(t){return E.has(w(t))}const D=[":popover-open",":modal"];function W(t){return D.some((e=>{try{return t.matches(e)}catch(t){return!1}}))}const O=["transform","translate","scale","rotate","perspective"],H=["transform","translate","scale","rotate","perspective","filter"],M=["paint","layout","strict","content"];function P(t){const e=z(),n=L(t)?A(t):t;return O.some((t=>!!n[t]&&"none"!==n[t]))||!!n.containerType&&"normal"!==n.containerType||!e&&!!n.backdropFilter&&"none"!==n.backdropFilter||!e&&!!n.filter&&"none"!==n.filter||H.some((t=>(n.willChange||"").includes(t)))||M.some((t=>(n.contain||"").includes(t)))}function z(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const B=new Set(["html","body","#document"]);function V(t){return B.has(w(t))}function A(t){return x(t).getComputedStyle(t)}function N(t){return L(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function k(t){if("html"===w(t))return t;const e=t.assignedSlot||t.parentNode||T(t)&&t.host||v(t);return T(e)?e.host:e}function I(t){const e=k(t);return V(e)?t.ownerDocument?t.ownerDocument.body:t.body:R(e)&&C(e)?e:I(e)}function q(t,e,n){var o;void 0===e&&(e=[]),void 0===n&&(n=!0);const i=I(t),r=i===(null==(o=t.ownerDocument)?void 0:o.body),c=x(i);if(r){const t=X(c);return e.concat(c,c.visualViewport||[],C(i)?i:[],t&&n?q(t):[])}return e.concat(i,q(i,[],n))}function X(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Y(t){const e=A(t);let n=parseFloat(e.width)||0,o=parseFloat(e.height)||0;const i=R(t),r=i?t.offsetWidth:n,c=i?t.offsetHeight:o,l=p(n)!==r||p(o)!==c;return l&&(n=r,o=c),{width:n,height:o,$:l}}function $(t){return L(t)?t:t.contextElement}function _(t){const e=$(t);if(!R(e))return m(1);const n=e.getBoundingClientRect(),{width:o,height:i,$:r}=Y(e);let c=(r?p(n.width):n.width)/o,l=(r?p(n.height):n.height)/i;return c&&Number.isFinite(c)||(c=1),l&&Number.isFinite(l)||(l=1),{x:c,y:l}}const j=m(0);function G(t){const e=x(t);return z()&&e.visualViewport?{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}:j}function J(e,n,o,i){void 0===n&&(n=!1),void 0===o&&(o=!1);const r=e.getBoundingClientRect(),c=$(e);let l=m(1);n&&(i?L(i)&&(l=_(i)):l=_(e));const s=function(t,e,n){return void 0===e&&(e=!1),!(!n||e&&n!==x(t))&&e}(c,o,i)?G(c):m(0);let f=(r.left+s.x)/l.x,u=(r.top+s.y)/l.y,a=r.width/l.x,h=r.height/l.y;if(c){const t=x(c),e=i&&L(i)?x(i):i;let n=t,o=X(n);for(;o&&i&&e!==n;){const t=_(o),e=o.getBoundingClientRect(),i=A(o),r=e.left+(o.clientLeft+parseFloat(i.paddingLeft))*t.x,c=e.top+(o.clientTop+parseFloat(i.paddingTop))*t.y;f*=t.x,u*=t.y,a*=t.x,h*=t.y,f+=r,u+=c,n=x(o),o=X(n)}}return t({width:a,height:h,x:f,y:u})}function K(t,e){const n=N(t).scrollLeft;return e?e.left+n:J(v(t)).left+n}function Q(t,e){const n=t.getBoundingClientRect();return{x:n.left+e.scrollLeft-K(t,n),y:n.top+e.scrollTop}}const U=new Set(["absolute","fixed"]);function Z(e,n,o){let i;if("viewport"===n)i=function(t,e){const n=x(t),o=v(t),i=n.visualViewport;let r=o.clientWidth,c=o.clientHeight,l=0,s=0;if(i){r=i.width,c=i.height;const t=z();(!t||t&&"fixed"===e)&&(l=i.offsetLeft,s=i.offsetTop)}const f=K(o);if(f<=0){const t=o.ownerDocument,e=t.body,n=getComputedStyle(e),i="CSS1Compat"===t.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,c=Math.abs(o.clientWidth-e.clientWidth-i);c<=25&&(r-=c)}else f<=25&&(r+=f);return{width:r,height:c,x:l,y:s}}(e,o);else if("document"===n)i=function(t){const e=v(t),n=N(t),o=t.ownerDocument.body,i=d(e.scrollWidth,e.clientWidth,o.scrollWidth,o.clientWidth),r=d(e.scrollHeight,e.clientHeight,o.scrollHeight,o.clientHeight);let c=-n.scrollLeft+K(t);const l=-n.scrollTop;return"rtl"===A(o).direction&&(c+=d(e.clientWidth,o.clientWidth)-i),{width:i,height:r,x:c,y:l}}(v(e));else if(L(n))i=function(t,e){const n=J(t,!0,"fixed"===e),o=n.top+t.clientTop,i=n.left+t.clientLeft,r=R(t)?_(t):m(1);return{width:t.clientWidth*r.x,height:t.clientHeight*r.y,x:i*r.x,y:o*r.y}}(n,o);else{const t=G(e);i={x:n.x-t.x,y:n.y-t.y,width:n.width,height:n.height}}return t(i)}function tt(t,e){const n=k(t);return!(n===e||!L(n)||V(n))&&("fixed"===A(n).position||tt(n,e))}function et(t,e,n){const o=R(e),i=v(e),r="fixed"===n,c=J(t,!0,r,e);let l={scrollLeft:0,scrollTop:0};const s=m(0);function f(){s.x=K(i)}if(o||!o&&!r)if(("body"!==w(e)||C(i))&&(l=N(e)),o){const t=J(e,!0,r,e);s.x=t.x+e.clientLeft,s.y=t.y+e.clientTop}else i&&f();r&&!o&&i&&f();const u=!i||o||r?m(0):Q(i,l);return{x:c.left+l.scrollLeft-s.x-u.x,y:c.top+l.scrollTop-s.y-u.y,width:c.width,height:c.height}}function nt(t){return"static"===A(t).position}function ot(t,e){if(!R(t)||"fixed"===A(t).position)return null;if(e)return e(t);let n=t.offsetParent;return v(t)===n&&(n=n.ownerDocument.body),n}function it(t,e){const n=x(t);if(W(t))return n;if(!R(t)){let e=k(t);for(;e&&!V(e);){if(L(e)&&!nt(e))return e;e=k(e)}return n}let o=ot(t,e);for(;o&&F(o)&&nt(o);)o=ot(o,e);return o&&V(o)&&nt(o)&&!P(o)?n:o||function(t){let e=k(t);for(;R(e)&&!V(e);){if(P(e))return e;if(W(e))return null;e=k(e)}return null}(t)||n}const rt={convertOffsetParentRelativeRectToViewportRelativeRect:function(t){let{elements:e,rect:n,offsetParent:o,strategy:i}=t;const r="fixed"===i,c=v(o),l=!!e&&W(e.floating);if(o===c||l&&r)return n;let s={scrollLeft:0,scrollTop:0},f=m(1);const u=m(0),a=R(o);if((a||!a&&!r)&&(("body"!==w(o)||C(c))&&(s=N(o)),R(o))){const t=J(o);f=_(o),u.x=t.x+o.clientLeft,u.y=t.y+o.clientTop}const h=!c||a||r?m(0):Q(c,s);return{width:n.width*f.x,height:n.height*f.y,x:n.x*f.x-s.scrollLeft*f.x+u.x+h.x,y:n.y*f.y-s.scrollTop*f.y+u.y+h.y}},getDocumentElement:v,getClippingRect:function(t){let{element:e,boundary:n,rootBoundary:o,strategy:i}=t;const r=[..."clippingAncestors"===n?W(e)?[]:function(t,e){const n=e.get(t);if(n)return n;let o=q(t,[],!1).filter((t=>L(t)&&"body"!==w(t))),i=null;const r="fixed"===A(t).position;let c=r?k(t):t;for(;L(c)&&!V(c);){const e=A(c),n=P(c);n||"fixed"!==e.position||(i=null),(r?!n&&!i:!n&&"static"===e.position&&i&&U.has(i.position)||C(c)&&!n&&tt(t,c))?o=o.filter((t=>t!==c)):i=e,c=k(c)}return e.set(t,o),o}(e,this._c):[].concat(n),o],c=r[0],l=r.reduce(((t,n)=>{const o=Z(e,n,i);return t.top=d(o.top,t.top),t.right=h(o.right,t.right),t.bottom=h(o.bottom,t.bottom),t.left=d(o.left,t.left),t}),Z(e,c,i));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}},getOffsetParent:it,getElementRects:async function(t){const e=this.getOffsetParent||it,n=this.getDimensions,o=await n(t.floating);return{reference:et(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}},getClientRects:function(t){return Array.from(t.getClientRects())},getDimensions:function(t){const{width:e,height:n}=Y(t);return{width:e,height:n}},getScale:_,isElement:L,isRTL:function(t){return"rtl"===A(t).direction}};function ct(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function lt(t,e,n,o){void 0===o&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:c="function"==typeof ResizeObserver,layoutShift:l="function"==typeof IntersectionObserver,animationFrame:s=!1}=o,f=$(t),u=i||r?[...f?q(f):[],...q(e)]:[];u.forEach((t=>{i&&t.addEventListener("scroll",n,{passive:!0}),r&&t.addEventListener("resize",n)}));const a=f&&l?function(t,e){let n,o=null;const i=v(t);function r(){var t;clearTimeout(n),null==(t=o)||t.disconnect(),o=null}return function c(l,s){void 0===l&&(l=!1),void 0===s&&(s=1),r();const f=t.getBoundingClientRect(),{left:u,top:a,width:p,height:m}=f;if(l||e(),!p||!m)return;const y={rootMargin:-g(a)+"px "+-g(i.clientWidth-(u+p))+"px "+-g(i.clientHeight-(a+m))+"px "+-g(u)+"px",threshold:d(0,h(1,s))||1};let w=!0;function x(e){const o=e[0].intersectionRatio;if(o!==s){if(!w)return c();o?c(!1,o):n=setTimeout((()=>{c(!1,1e-7)}),1e3)}1!==o||ct(f,t.getBoundingClientRect())||c(),w=!1}try{o=new IntersectionObserver(x,{...y,root:i.ownerDocument})}catch(t){o=new IntersectionObserver(x,y)}o.observe(t)}(!0),r}(f,n):null;let p,m=-1,y=null;c&&(y=new ResizeObserver((t=>{let[o]=t;o&&o.target===f&&y&&(y.unobserve(e),cancelAnimationFrame(m),m=requestAnimationFrame((()=>{var t;null==(t=y)||t.observe(e)}))),n()})),f&&!s&&y.observe(f),y.observe(e));let w=s?J(t):null;return s&&function e(){const o=J(t);w&&!ct(w,o)&&n();w=o,p=requestAnimationFrame(e)}(),n(),()=>{var t;u.forEach((t=>{i&&t.removeEventListener("scroll",n),r&&t.removeEventListener("resize",n)})),null==a||a(),null==(t=y)||t.disconnect(),y=null,s&&cancelAnimationFrame(p)}}const st=o,ft=s,ut=n,at=f,ht=i,dt=u,pt=r,gt=e,mt=c,yt=l,wt=(t,e,n)=>{const o=new Map,i={platform:rt,...n},r={...i.platform,_c:o};return a(t,e,{...i,platform:r})};export{gt as arrow,ut as autoPlacement,lt as autoUpdate,wt as computePosition,st as detectOverflow,ht as flip,q as getOverflowAncestors,pt as hide,mt as inline,yt as limitShift,ft as offset,rt as platform,at as shift,dt as size}; diff --git a/frontend/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.mjs b/frontend/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.mjs new file mode 100644 index 00000000..94459791 --- /dev/null +++ b/frontend/node_modules/@floating-ui/dom/dist/floating-ui.dom.browser.mjs @@ -0,0 +1,948 @@ +import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core'; + +/** + * Custom positioning reference element. + * @see https://floating-ui.com/docs/virtual-elements + */ + +const min = Math.min; +const max = Math.max; +const round = Math.round; +const floor = Math.floor; +const createCoords = v => ({ + x: v, + y: v +}); + +function hasWindow() { + return typeof window !== 'undefined'; +} +function getNodeName(node) { + if (isNode(node)) { + return (node.nodeName || '').toLowerCase(); + } + // Mocked nodes in testing environments may not be instances of Node. By + // returning `#document` an infinite loop won't occur. + // https://github.com/floating-ui/floating-ui/issues/2317 + return '#document'; +} +function getWindow(node) { + var _node$ownerDocument; + return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; +} +function getDocumentElement(node) { + var _ref; + return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement; +} +function isNode(value) { + if (!hasWindow()) { + return false; + } + return value instanceof Node || value instanceof getWindow(value).Node; +} +function isElement(value) { + if (!hasWindow()) { + return false; + } + return value instanceof Element || value instanceof getWindow(value).Element; +} +function isHTMLElement(value) { + if (!hasWindow()) { + return false; + } + return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement; +} +function isShadowRoot(value) { + if (!hasWindow() || typeof ShadowRoot === 'undefined') { + return false; + } + return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot; +} +const invalidOverflowDisplayValues = /*#__PURE__*/new Set(['inline', 'contents']); +function isOverflowElement(element) { + const { + overflow, + overflowX, + overflowY, + display + } = getComputedStyle$1(element); + return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display); +} +const tableElements = /*#__PURE__*/new Set(['table', 'td', 'th']); +function isTableElement(element) { + return tableElements.has(getNodeName(element)); +} +const topLayerSelectors = [':popover-open', ':modal']; +function isTopLayer(element) { + return topLayerSelectors.some(selector => { + try { + return element.matches(selector); + } catch (_e) { + return false; + } + }); +} +const transformProperties = ['transform', 'translate', 'scale', 'rotate', 'perspective']; +const willChangeValues = ['transform', 'translate', 'scale', 'rotate', 'perspective', 'filter']; +const containValues = ['paint', 'layout', 'strict', 'content']; +function isContainingBlock(elementOrCss) { + const webkit = isWebKit(); + const css = isElement(elementOrCss) ? getComputedStyle$1(elementOrCss) : elementOrCss; + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + // https://drafts.csswg.org/css-transforms-2/#individual-transforms + return transformProperties.some(value => css[value] ? css[value] !== 'none' : false) || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || willChangeValues.some(value => (css.willChange || '').includes(value)) || containValues.some(value => (css.contain || '').includes(value)); +} +function getContainingBlock(element) { + let currentNode = getParentNode(element); + while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { + if (isContainingBlock(currentNode)) { + return currentNode; + } else if (isTopLayer(currentNode)) { + return null; + } + currentNode = getParentNode(currentNode); + } + return null; +} +function isWebKit() { + if (typeof CSS === 'undefined' || !CSS.supports) return false; + return CSS.supports('-webkit-backdrop-filter', 'none'); +} +const lastTraversableNodeNames = /*#__PURE__*/new Set(['html', 'body', '#document']); +function isLastTraversableNode(node) { + return lastTraversableNodeNames.has(getNodeName(node)); +} +function getComputedStyle$1(element) { + return getWindow(element).getComputedStyle(element); +} +function getNodeScroll(element) { + if (isElement(element)) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop + }; + } + return { + scrollLeft: element.scrollX, + scrollTop: element.scrollY + }; +} +function getParentNode(node) { + if (getNodeName(node) === 'html') { + return node; + } + const result = + // Step into the shadow DOM of the parent of a slotted node. + node.assignedSlot || + // DOM Element detected. + node.parentNode || + // ShadowRoot detected. + isShadowRoot(node) && node.host || + // Fallback. + getDocumentElement(node); + return isShadowRoot(result) ? result.host : result; +} +function getNearestOverflowAncestor(node) { + const parentNode = getParentNode(node); + if (isLastTraversableNode(parentNode)) { + return node.ownerDocument ? node.ownerDocument.body : node.body; + } + if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { + return parentNode; + } + return getNearestOverflowAncestor(parentNode); +} +function getOverflowAncestors(node, list, traverseIframes) { + var _node$ownerDocument2; + if (list === void 0) { + list = []; + } + if (traverseIframes === void 0) { + traverseIframes = true; + } + const scrollableAncestor = getNearestOverflowAncestor(node); + const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body); + const win = getWindow(scrollableAncestor); + if (isBody) { + const frameElement = getFrameElement(win); + return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []); + } + return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes)); +} +function getFrameElement(win) { + return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null; +} + +function getCssDimensions(element) { + const css = getComputedStyle$1(element); + // In testing environments, the `width` and `height` properties are empty + // strings for SVG elements, returning NaN. Fallback to `0` in this case. + let width = parseFloat(css.width) || 0; + let height = parseFloat(css.height) || 0; + const hasOffset = isHTMLElement(element); + const offsetWidth = hasOffset ? element.offsetWidth : width; + const offsetHeight = hasOffset ? element.offsetHeight : height; + const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; + if (shouldFallback) { + width = offsetWidth; + height = offsetHeight; + } + return { + width, + height, + $: shouldFallback + }; +} + +function unwrapElement(element) { + return !isElement(element) ? element.contextElement : element; +} + +function getScale(element) { + const domElement = unwrapElement(element); + if (!isHTMLElement(domElement)) { + return createCoords(1); + } + const rect = domElement.getBoundingClientRect(); + const { + width, + height, + $ + } = getCssDimensions(domElement); + let x = ($ ? round(rect.width) : rect.width) / width; + let y = ($ ? round(rect.height) : rect.height) / height; + + // 0, NaN, or Infinity should always fallback to 1. + + if (!x || !Number.isFinite(x)) { + x = 1; + } + if (!y || !Number.isFinite(y)) { + y = 1; + } + return { + x, + y + }; +} + +const noOffsets = /*#__PURE__*/createCoords(0); +function getVisualOffsets(element) { + const win = getWindow(element); + if (!isWebKit() || !win.visualViewport) { + return noOffsets; + } + return { + x: win.visualViewport.offsetLeft, + y: win.visualViewport.offsetTop + }; +} +function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) { + if (isFixed === void 0) { + isFixed = false; + } + if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) { + return false; + } + return isFixed; +} + +function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) { + if (includeScale === void 0) { + includeScale = false; + } + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + const clientRect = element.getBoundingClientRect(); + const domElement = unwrapElement(element); + let scale = createCoords(1); + if (includeScale) { + if (offsetParent) { + if (isElement(offsetParent)) { + scale = getScale(offsetParent); + } + } else { + scale = getScale(element); + } + } + const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0); + let x = (clientRect.left + visualOffsets.x) / scale.x; + let y = (clientRect.top + visualOffsets.y) / scale.y; + let width = clientRect.width / scale.x; + let height = clientRect.height / scale.y; + if (domElement) { + const win = getWindow(domElement); + const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent; + let currentWin = win; + let currentIFrame = getFrameElement(currentWin); + while (currentIFrame && offsetParent && offsetWin !== currentWin) { + const iframeScale = getScale(currentIFrame); + const iframeRect = currentIFrame.getBoundingClientRect(); + const css = getComputedStyle$1(currentIFrame); + const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; + const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; + x *= iframeScale.x; + y *= iframeScale.y; + width *= iframeScale.x; + height *= iframeScale.y; + x += left; + y += top; + currentWin = getWindow(currentIFrame); + currentIFrame = getFrameElement(currentWin); + } + } + return rectToClientRect({ + width, + height, + x, + y + }); +} + +// If has a CSS width greater than the viewport, then this will be +// incorrect for RTL. +function getWindowScrollBarX(element, rect) { + const leftScroll = getNodeScroll(element).scrollLeft; + if (!rect) { + return getBoundingClientRect(getDocumentElement(element)).left + leftScroll; + } + return rect.left + leftScroll; +} + +function getHTMLOffset(documentElement, scroll) { + const htmlRect = documentElement.getBoundingClientRect(); + const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect); + const y = htmlRect.top + scroll.scrollTop; + return { + x, + y + }; +} + +function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { + let { + elements, + rect, + offsetParent, + strategy + } = _ref; + const isFixed = strategy === 'fixed'; + const documentElement = getDocumentElement(offsetParent); + const topLayer = elements ? isTopLayer(elements.floating) : false; + if (offsetParent === documentElement || topLayer && isFixed) { + return rect; + } + let scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + let scale = createCoords(1); + const offsets = createCoords(0); + const isOffsetParentAnElement = isHTMLElement(offsetParent); + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isHTMLElement(offsetParent)) { + const offsetRect = getBoundingClientRect(offsetParent); + scale = getScale(offsetParent); + offsets.x = offsetRect.x + offsetParent.clientLeft; + offsets.y = offsetRect.y + offsetParent.clientTop; + } + } + const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0); + return { + width: rect.width * scale.x, + height: rect.height * scale.y, + x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x, + y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y + }; +} + +function getClientRects(element) { + return Array.from(element.getClientRects()); +} + +// Gets the entire size of the scrollable document area, even extending outside +// of the `` and `` rect bounds if horizontally scrollable. +function getDocumentRect(element) { + const html = getDocumentElement(element); + const scroll = getNodeScroll(element); + const body = element.ownerDocument.body; + const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); + const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); + let x = -scroll.scrollLeft + getWindowScrollBarX(element); + const y = -scroll.scrollTop; + if (getComputedStyle$1(body).direction === 'rtl') { + x += max(html.clientWidth, body.clientWidth) - width; + } + return { + width, + height, + x, + y + }; +} + +// Safety check: ensure the scrollbar space is reasonable in case this +// calculation is affected by unusual styles. +// Most scrollbars leave 15-18px of space. +const SCROLLBAR_MAX = 25; +function getViewportRect(element, strategy) { + const win = getWindow(element); + const html = getDocumentElement(element); + const visualViewport = win.visualViewport; + let width = html.clientWidth; + let height = html.clientHeight; + let x = 0; + let y = 0; + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + const visualViewportBased = isWebKit(); + if (!visualViewportBased || visualViewportBased && strategy === 'fixed') { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + const windowScrollbarX = getWindowScrollBarX(html); + // `overflow: hidden` + `scrollbar-gutter: stable` reduces the + // visual width of the but this is not considered in the size + // of `html.clientWidth`. + if (windowScrollbarX <= 0) { + const doc = html.ownerDocument; + const body = doc.body; + const bodyStyles = getComputedStyle(body); + const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0; + const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline); + if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) { + width -= clippingStableScrollbarWidth; + } + } else if (windowScrollbarX <= SCROLLBAR_MAX) { + // If the scrollbar is on the left, the width needs to be extended + // by the scrollbar amount so there isn't extra space on the right. + width += windowScrollbarX; + } + return { + width, + height, + x, + y + }; +} + +const absoluteOrFixed = /*#__PURE__*/new Set(['absolute', 'fixed']); +// Returns the inner client rect, subtracting scrollbars if present. +function getInnerBoundingClientRect(element, strategy) { + const clientRect = getBoundingClientRect(element, true, strategy === 'fixed'); + const top = clientRect.top + element.clientTop; + const left = clientRect.left + element.clientLeft; + const scale = isHTMLElement(element) ? getScale(element) : createCoords(1); + const width = element.clientWidth * scale.x; + const height = element.clientHeight * scale.y; + const x = left * scale.x; + const y = top * scale.y; + return { + width, + height, + x, + y + }; +} +function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { + let rect; + if (clippingAncestor === 'viewport') { + rect = getViewportRect(element, strategy); + } else if (clippingAncestor === 'document') { + rect = getDocumentRect(getDocumentElement(element)); + } else if (isElement(clippingAncestor)) { + rect = getInnerBoundingClientRect(clippingAncestor, strategy); + } else { + const visualOffsets = getVisualOffsets(element); + rect = { + x: clippingAncestor.x - visualOffsets.x, + y: clippingAncestor.y - visualOffsets.y, + width: clippingAncestor.width, + height: clippingAncestor.height + }; + } + return rectToClientRect(rect); +} +function hasFixedPositionAncestor(element, stopNode) { + const parentNode = getParentNode(element); + if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) { + return false; + } + return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode); +} + +// A "clipping ancestor" is an `overflow` element with the characteristic of +// clipping (or hiding) child elements. This returns all clipping ancestors +// of the given element up the tree. +function getClippingElementAncestors(element, cache) { + const cachedResult = cache.get(element); + if (cachedResult) { + return cachedResult; + } + let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body'); + let currentContainingBlockComputedStyle = null; + const elementIsFixed = getComputedStyle$1(element).position === 'fixed'; + let currentNode = elementIsFixed ? getParentNode(element) : element; + + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { + const computedStyle = getComputedStyle$1(currentNode); + const currentNodeIsContaining = isContainingBlock(currentNode); + if (!currentNodeIsContaining && computedStyle.position === 'fixed') { + currentContainingBlockComputedStyle = null; + } + const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode); + if (shouldDropCurrentNode) { + // Drop non-containing blocks. + result = result.filter(ancestor => ancestor !== currentNode); + } else { + // Record last containing block for next iteration. + currentContainingBlockComputedStyle = computedStyle; + } + currentNode = getParentNode(currentNode); + } + cache.set(element, result); + return result; +} + +// Gets the maximum area that the element is visible in due to any number of +// clipping ancestors. +function getClippingRect(_ref) { + let { + element, + boundary, + rootBoundary, + strategy + } = _ref; + const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary); + const clippingAncestors = [...elementClippingAncestors, rootBoundary]; + const firstClippingAncestor = clippingAncestors[0]; + const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => { + const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy)); + return { + width: clippingRect.right - clippingRect.left, + height: clippingRect.bottom - clippingRect.top, + x: clippingRect.left, + y: clippingRect.top + }; +} + +function getDimensions(element) { + const { + width, + height + } = getCssDimensions(element); + return { + width, + height + }; +} + +function getRectRelativeToOffsetParent(element, offsetParent, strategy) { + const isOffsetParentAnElement = isHTMLElement(offsetParent); + const documentElement = getDocumentElement(offsetParent); + const isFixed = strategy === 'fixed'; + const rect = getBoundingClientRect(element, true, isFixed, offsetParent); + let scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + const offsets = createCoords(0); + + // If the scrollbar appears on the left (e.g. RTL systems). Use + // Firefox with layout.scrollbar.side = 3 in about:config to test this. + function setLeftRTLScrollbarOffset() { + offsets.x = getWindowScrollBarX(documentElement); + } + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + if (isOffsetParentAnElement) { + const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent); + offsets.x = offsetRect.x + offsetParent.clientLeft; + offsets.y = offsetRect.y + offsetParent.clientTop; + } else if (documentElement) { + setLeftRTLScrollbarOffset(); + } + } + if (isFixed && !isOffsetParentAnElement && documentElement) { + setLeftRTLScrollbarOffset(); + } + const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0); + const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x; + const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y; + return { + x, + y, + width: rect.width, + height: rect.height + }; +} + +function isStaticPositioned(element) { + return getComputedStyle$1(element).position === 'static'; +} + +function getTrueOffsetParent(element, polyfill) { + if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') { + return null; + } + if (polyfill) { + return polyfill(element); + } + let rawOffsetParent = element.offsetParent; + + // Firefox returns the element as the offsetParent if it's non-static, + // while Chrome and Safari return the element. The element must + // be used to perform the correct calculations even if the element is + // non-static. + if (getDocumentElement(element) === rawOffsetParent) { + rawOffsetParent = rawOffsetParent.ownerDocument.body; + } + return rawOffsetParent; +} + +// Gets the closest ancestor positioned element. Handles some edge cases, +// such as table ancestors and cross browser bugs. +function getOffsetParent(element, polyfill) { + const win = getWindow(element); + if (isTopLayer(element)) { + return win; + } + if (!isHTMLElement(element)) { + let svgOffsetParent = getParentNode(element); + while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) { + if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) { + return svgOffsetParent; + } + svgOffsetParent = getParentNode(svgOffsetParent); + } + return win; + } + let offsetParent = getTrueOffsetParent(element, polyfill); + while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) { + offsetParent = getTrueOffsetParent(offsetParent, polyfill); + } + if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) { + return win; + } + return offsetParent || getContainingBlock(element) || win; +} + +const getElementRects = async function (data) { + const getOffsetParentFn = this.getOffsetParent || getOffsetParent; + const getDimensionsFn = this.getDimensions; + const floatingDimensions = await getDimensionsFn(data.floating); + return { + reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy), + floating: { + x: 0, + y: 0, + width: floatingDimensions.width, + height: floatingDimensions.height + } + }; +}; + +function isRTL(element) { + return getComputedStyle$1(element).direction === 'rtl'; +} + +const platform = { + convertOffsetParentRelativeRectToViewportRelativeRect, + getDocumentElement, + getClippingRect, + getOffsetParent, + getElementRects, + getClientRects, + getDimensions, + getScale, + isElement, + isRTL +}; + +function rectsAreEqual(a, b) { + return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height; +} + +// https://samthor.au/2021/observing-dom/ +function observeMove(element, onMove) { + let io = null; + let timeoutId; + const root = getDocumentElement(element); + function cleanup() { + var _io; + clearTimeout(timeoutId); + (_io = io) == null || _io.disconnect(); + io = null; + } + function refresh(skip, threshold) { + if (skip === void 0) { + skip = false; + } + if (threshold === void 0) { + threshold = 1; + } + cleanup(); + const elementRectForRootMargin = element.getBoundingClientRect(); + const { + left, + top, + width, + height + } = elementRectForRootMargin; + if (!skip) { + onMove(); + } + if (!width || !height) { + return; + } + const insetTop = floor(top); + const insetRight = floor(root.clientWidth - (left + width)); + const insetBottom = floor(root.clientHeight - (top + height)); + const insetLeft = floor(left); + const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px"; + const options = { + rootMargin, + threshold: max(0, min(1, threshold)) || 1 + }; + let isFirstUpdate = true; + function handleObserve(entries) { + const ratio = entries[0].intersectionRatio; + if (ratio !== threshold) { + if (!isFirstUpdate) { + return refresh(); + } + if (!ratio) { + // If the reference is clipped, the ratio is 0. Throttle the refresh + // to prevent an infinite loop of updates. + timeoutId = setTimeout(() => { + refresh(false, 1e-7); + }, 1000); + } else { + refresh(false, ratio); + } + } + if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) { + // It's possible that even though the ratio is reported as 1, the + // element is not actually fully within the IntersectionObserver's root + // area anymore. This can happen under performance constraints. This may + // be a bug in the browser's IntersectionObserver implementation. To + // work around this, we compare the element's bounding rect now with + // what it was at the time we created the IntersectionObserver. If they + // are not equal then the element moved, so we refresh. + refresh(); + } + isFirstUpdate = false; + } + + // Older browsers don't support a `document` as the root and will throw an + // error. + try { + io = new IntersectionObserver(handleObserve, { + ...options, + // Handle