Compare commits
52 Commits
codex/velu
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b845062824 | ||
|
|
b630093075 | ||
|
|
019f6b6d7c | ||
| 96d5f3f57d | |||
| e2df0cda33 | |||
| 1eba3f5921 | |||
| dd0ac92518 | |||
|
|
d2ed7130f0 | ||
|
|
11ddd6d70f | ||
|
|
d76e6f3375 | ||
|
|
a5e20a7e03 | ||
|
|
5200fcde70 | ||
|
|
41b935a145 | ||
|
|
731c449c33 | ||
|
|
f71e46f735 | ||
|
|
4aad9886fc | ||
|
|
031eaa978f | ||
|
|
19434c6c0b | ||
|
|
1442ed4740 | ||
|
|
e783c67af0 | ||
|
|
c50766a0ee | ||
|
|
a627d9147e | ||
|
|
03a793ad7c | ||
|
|
ebf78128c4 | ||
|
|
65134735f1 | ||
|
|
4801908faf | ||
|
|
1ac11988af | ||
|
|
8557a9b809 | ||
|
|
925890a156 | ||
|
|
818f9ed814 | ||
|
|
7db3949d66 | ||
|
|
8de3ce9326 | ||
|
|
0ec5b0745e | ||
|
|
43fbf46014 | ||
|
|
7bc0142f95 | ||
|
|
ec1f9a4e55 | ||
|
|
ec1e2d27e0 | ||
|
|
94806aa049 | ||
|
|
ec327a5220 | ||
|
|
23af4993db | ||
|
|
e9cda1c02f | ||
|
|
6cb5b0efc5 | ||
|
|
5877b7cf5f | ||
|
|
c3ef1a6aed | ||
|
|
d0d6a29ef6 | ||
|
|
e7e21e9281 | ||
|
|
392db8601a | ||
|
|
226d230b6d | ||
|
|
8b254eb87d | ||
|
|
8e928bc69f | ||
|
|
ae62c6f95c | ||
|
|
c1229e1d14 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -2,3 +2,6 @@ node_modules
|
|||||||
dist
|
dist
|
||||||
.DS_Store
|
.DS_Store
|
||||||
raycast-env.d.ts
|
raycast-env.d.ts
|
||||||
|
|
||||||
|
/assets/velum-docx/
|
||||||
|
/assets/velum-project-worker.cjs
|
||||||
|
|||||||
191
README.md
191
README.md
@@ -1,6 +1,128 @@
|
|||||||
# Velum Raycast Extension
|
# Velum Raycast Extension
|
||||||
|
|
||||||
Raycast-Extension für PII-sichere Text-Workflows mit Velum: Klarnamen werden lokal in Platzhalter überführt, bevor Text an externe KI-Modelle (Raycast AI), Übersetzer oder andere Tools weitergegeben wird. Originalwerte werden anschließend lokal anhand der Velum-Sitzungs-Zuordnung wiederhergestellt.
|
Raycast-Extension für PII-sichere Text- und Projekt-Workflows mit Velum: Inhalte werden über die konfigurierte Velum-API pseudonymisiert, bevor sie an externe KI-Modelle oder andere Tools weitergegeben werden. Die Velum-API sollte für vertrauliche Kundendaten in einer dafür geeigneten Umgebung betrieben werden.
|
||||||
|
|
||||||
|
## Projektdateien
|
||||||
|
|
||||||
|
### DOCX lokal verarbeiten
|
||||||
|
|
||||||
|
Velum öffnet Word-Dateien auf dem Mac und schickt Textsegmente zur Erkennung an
|
||||||
|
`POST /api/docx/segments`. Die Trefferprüfung verwendet dieselbe Zuordnung für
|
||||||
|
das ganze Projekt. Beim Anwenden setzt Velum die ausgewählten Treffer lokal in
|
||||||
|
das Word-Paket ein. Das gilt auch für Text und Autoren in Kommentaren und
|
||||||
|
nachverfolgten Änderungen, einschließlich gelöschter Texte und Feldcodes.
|
||||||
|
Kommentarverweise und Änderungsmarkierungen bleiben erhalten. Optionale
|
||||||
|
Microsoft-Kontoverknüpfungen in `word/people.xml` werden entfernt.
|
||||||
|
|
||||||
|
Die Erkennung bewertet jeden Absatz einzeln. Ein Name wird daher je nach Satz
|
||||||
|
erkannt oder nicht („Quastenberg prüft …“, aber nicht „bei Quastenberg
|
||||||
|
nachfragen“). Velum überträgt deshalb sicher erkannte Personennamen auf alle
|
||||||
|
weiteren Vorkommen in derselben Datei: vollständige Namen, deren Bestandteile
|
||||||
|
ab drei Zeichen und Namen nach einer Anrede wie `Frau` oder `Dr.`, auch mit
|
||||||
|
Genitiv-s. Diese Vorkommen erscheinen wie alle anderen in der Trefferprüfung und
|
||||||
|
lassen sich dort gemeinsam abwählen. Bleiben trotzdem Namen stehen, trage sie
|
||||||
|
als Projektbegriff ein, zum Beispiel `PERSON: Max Mustermann`.
|
||||||
|
|
||||||
|
Bei der Analyse und nach dem Bestätigen der Ausgabe kannst du Raycast
|
||||||
|
schließen. Öffne anschließend im selben Befehl denselben Projektordner, um
|
||||||
|
den Status oder die Trefferprüfung zu öffnen. Vor dem Anwenden prüft der
|
||||||
|
Hintergrundprozess den Datei-Hash.
|
||||||
|
|
||||||
|
Für die lokale DOCX-Verarbeitung muss `uv` installiert sein (zum Beispiel
|
||||||
|
`brew install uv`). Beim ersten Lauf lädt es Python 3.11 und `lxml` 6.2.1 in
|
||||||
|
seinen Paketcache; dafür ist einmalig Internetzugang nötig. Dokumentinhalte
|
||||||
|
werden dabei nicht übertragen. Das Velum-Backend muss den Segment-Endpunkt
|
||||||
|
bereitstellen, also mindestens Stand `2517637` („support local DOCX segment
|
||||||
|
analysis“). Beim Bauen der Erweiterung werden der Python-Codec und der
|
||||||
|
Hintergrundprozess aus dem Backend-Checkout mitgeliefert. Der Checkout sollte
|
||||||
|
deshalb denselben Stand haben wie das produktive Backend. Ohne Angabe sucht
|
||||||
|
der Build unter `../../velum/backend`, relativ zu diesem Repository. Liegt der
|
||||||
|
Backend-Checkout an einem anderen Ort, setze `VELUM_BACKEND_DIR` vor
|
||||||
|
`npm run build` oder `npm run dev` auf seinen `backend`-Ordner.
|
||||||
|
|
||||||
|
|
||||||
|
`Projektdateien pseudonymisieren` übernimmt zuerst den geöffneten Finder-Ordner; bei Bedarf kann er im Formular erneut übernommen oder manuell gewählt werden. Im Formular werden die zu erkennenden Kategorien ausgewählt (Orte sind wegen häufiger Fehlalarme zunächst abgewählt). Danach analysiert Velum alle geeigneten Text-, DOCX-, XLSX-, PPTX- und PDF-Dateien sowie ihre Namen. Unterstriche zwischen Namensbestandteilen werden bei der Erkennung als Worttrenner behandelt; bekannte Platzhalter und wörtliche Codebegriffe bleiben erhalten. Auch Namen unveränderter Dateien werden in einem Folgelauf erneut geprüft. Ältere Word-Projektstände werden einmalig auf Kommentatoren geprüft, sofern `PERSON` ausgewählt ist. Kleine Textdateien und Namen werden in Paketen analysiert, um die Anzahl der API-Aufrufe zu verringern. Die Prüfung zeigt jede eindeutige Zuordnung einmal, nach Kategorie gruppiert, mit der Anzahl ihrer Vorkommen. Eine Zuordnung an- oder abzuwählen gilt für alle betroffenen Dateien; einzelne Vorkommen lassen sich bei Bedarf ansehen. Nach der Auswahl lassen sich erkannte Personen optional zusammenfassen, sodass ihre Erwähnungen denselben Platzhalter erhalten. `Pseudonymisierte Kopien erstellen` schreibt Dateien in den Raycast-Support-Bereich außerhalb des Projektordners. Alternativ ersetzt `Originaldateien ersetzen` die Dateien und gegebenenfalls ihre Namen vor Ort; zuvor legt Velum eine private Sicherung der Originale im Raycast-Support-Bereich an. PDF wird dabei als DOCX ausgegeben.
|
||||||
|
|
||||||
|
Projektbegriffe werden zeilenweise als `BEGRIFF: KundenSuite` oder `PERSON: Max Mustermann` eingegeben, nur für dieses Projekt gespeichert und mit `force_masks` pro API-Aufruf übertragen. Die globale Velum-Regelliste bleibt unverändert. Beim Erstellen eines Projektstands werden abgewählte Treffer als typgebundene Projekt-Whitelist außerhalb des Quellordners gespeichert und bei späteren Läufen nicht erneut angeboten. Die Whitelist lässt sich im Startformular bearbeiten. Eine neue Projektbearbeitung übernimmt die bestätigten Zuordnungen des letzten Projektstands, sodass Platzhalter konsistent bleiben. Nach einem Lauf mit Kopien bleibt der Klartext-Quellordner erhalten und kann nach Dateiänderungen erneut bearbeitet werden. Nach dem Ersetzen vor Ort werden unveränderte bereits maskierte Dateien in den nächsten Stand übernommen; neue oder geänderte Dateien werden analysiert. Ein neuer Projektstand enthält auch die übernommenen Dateien für die Rückübersetzung.
|
||||||
|
|
||||||
|
`Projektdateien nachbearbeiten` bietet für den aktuellen Projektstand zwei Wege: Zuordnungen nachträglich in Klartext zurückwandeln und als Projekt-Ausnahme speichern sowie Personenplatzhalter nachträglich zusammenführen. Beide Änderungen betreffen Inhalte und Dateinamen; der vorige Stand bleibt als Sicherung erhalten. Bei zuvor direkt ersetzten Projektdateien wird der Ordner nach einer Bestätigung ebenfalls aktualisiert, sofern keine Datei seit dem letzten Stand verändert wurde. Für Projekte mit Kopien entsteht ein neuer Stand außerhalb des Quellordners. Ältere Stände können weiterhin dateiweise als Klartext-Kopien unter `~/Downloads/Velum` exportiert werden. Die Projektfunktion benötigt eine Velum-API mit `/api/project-capabilities`, Trefferprüfung für Dokumente, projektbezogenen `force_masks` und `/api/depseudonymize-document`.
|
||||||
|
|
||||||
|
Über `Projektdateien wiederherstellen` → Projekt öffnen → `Einzelnen Ordner wiederherstellen`
|
||||||
|
lässt sich ein Ordner samt Unterordnern direkt als Klartext exportieren. Die Ordnerliste
|
||||||
|
zeigt die Anzahl der Text- und Office-Dateien. `Ordner inklusive Office wiederherstellen`
|
||||||
|
exportiert alle unterstützten Dateien dieses Ordners; alternativ können nur Textdateien
|
||||||
|
wiederhergestellt oder die Dateien zunächst zur weiteren Auswahl übernommen werden.
|
||||||
|
Andere Ordner werden nicht mit exportiert. Die Ordnerstruktur bleibt unter
|
||||||
|
`~/Downloads/Velum` erhalten. Das gilt auch bei der Wiederherstellung früherer Projektstände.
|
||||||
|
|
||||||
|
### Bilder in Office/PDF
|
||||||
|
|
||||||
|
Der Projektdateien-Befehl bietet `placeholder` (Standard bei jedem neuen Aufruf),
|
||||||
|
`remove` und `keep`. Die Auswahl gilt unverändert für Analyse, Trefferprüfung,
|
||||||
|
Wiederholung und endgültige Ausgabe. `keep` zeigt deutliche Warnungen vor der
|
||||||
|
Analyse, vor dem Anwenden und im Ergebnis. Bildinhalte werden nicht analysiert.
|
||||||
|
Der Platzhaltertext lautet: „Bild aus Datenschutzgründen entfernt. Das ursprüngliche
|
||||||
|
Bild wurde im Zuge der Pseudonymisierung entfernt.“ Die Bereinigung übernimmt das
|
||||||
|
Velum-Backend; es sind keine zusätzlichen KI-Modelle erforderlich.
|
||||||
|
|
||||||
|
Der Backend-Fähigkeitsnachweis `document_image_policy` und die bestätigte Bildoption
|
||||||
|
mit Bildzählern sind für Dokumente erforderlich. Ohne diese Bestätigung wird kein
|
||||||
|
Dokument als erfolgreich verarbeitet ausgegeben. Die Wahl wird im Projektstand
|
||||||
|
festgehalten; ältere Office-Stände ohne Bildnachweis oder mit anderer Auswahl
|
||||||
|
werden erneut verarbeitet. Geänderte Bildoptionen stellen bereits entfernte Bilder
|
||||||
|
nicht wieder her. Im Projektstand stehen je Datei die Zähler und Warnungen;
|
||||||
|
der Abschluss zeigt die Summen für den erzeugten Stand einschließlich übernommener Dateien.
|
||||||
|
|
||||||
|
### Einmalige Übernahme aus KI Datenschutz
|
||||||
|
|
||||||
|
Velum enthält **keinen** Laufzeit-Zugriff auf die frühere Extension. Das eigenständige Skript `tools/migrate-ki-datenschutz.mjs` wandelt einen bereits anonymisierten KI-Datenschutz-Projektordner samt seiner eingefrorenen Variante-Tabelle in einen Velum-Projektstand um. Es verändert weder den alten Ordner noch die alte Tabelle. Der neue Stand erscheint anschließend unter `Projektdateien nachbearbeiten`; Begriffe nur für dieses Projekt werden als Velum-Projektregeln übernommen. Alle Inhalte bleiben während der Migration lokal und werden nicht an eine API gesendet. Im Terminal protokolliert das Skript nur Zahlen, keine Werte oder Dateinamen.
|
||||||
|
|
||||||
|
1. In Raycast `Migrationsziel anzeigen` öffnen und den Velum-Datenordner kopieren.
|
||||||
|
2. Den alten Projektordner und die zugehörige Datei `projects/<Projekt-ID>.json` aus dem Datenordner von KI Datenschutz angeben. Mit `--preview-file` eine prüfbare Vorschau erstellen:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node tools/migrate-ki-datenschutz.mjs --project "/Pfad/zum/Projekt" --manifest "/Pfad/zu/projects/abcdef0123456789.json" --target-support "/kopierter/Velum-Datenordner" --preview-file "$HOME/Downloads/Migrationsvorschau.md"
|
||||||
|
```
|
||||||
|
|
||||||
|
Die Datei zeigt Quell- und Zielnamen, alte und neue Platzhalter samt Häufigkeit pro Datei sowie übersprungene Pfade mit Grund. Sie enthält keine Klartextwerte aus der Zuordnungstabelle. Da Dateinamen trotzdem vertraulich sein können, wird sie nur lokal mit eingeschränkten Dateirechten erstellt und eine vorhandene Datei nie überschrieben. Der Vorschaupfad muss außerhalb des Projekts liegen. Ohne `--preview-file` bleibt es bei der Zahlenausgabe im Terminal.
|
||||||
|
|
||||||
|
3. Nach Prüfung denselben Befehl **ohne** `--preview-file`, dafür mit `--apply` ausführen. Danach den neuen Stand in Velum öffnen und den Klartext-Export mit einem Testdokument prüfen.
|
||||||
|
|
||||||
|
Das Skript übernimmt Text- und Codedateien. Binäre Dateien und bisher nicht anonymisierte Office/PDF-Dateien werden gezählt und ausgelassen; sie müssen im neuen Projektdateien-Befehl geprüft werden. Platzhalter, die in technischen Bezeichnern kleben, behalten ein eigenes Rückübersetzungsverhalten. Wenn die alte Variante-Tabelle mehrere Klartext-Schreibweisen für denselben Platzhalter enthält, ist die exakte frühere Schreibweise nicht mehr rekonstruierbar; das Skript verwendet dieselbe kontextabhängige Kanonisierung wie der alte Klartext-Export. Die alte Extension kann nach erfolgreicher Prüfung entfernt werden.
|
||||||
|
|
||||||
|
## Verschobene oder umbenannte Projektordner
|
||||||
|
|
||||||
|
Den Raycast-Befehl **Projektordner ändern** öffnen, das gespeicherte Projekt anhand
|
||||||
|
des bisherigen Pfads wählen und den neuen Ordner zuordnen. Dieselbe Aktion ist in
|
||||||
|
**Text pseudonymisieren** (auch Zwischenablage und markierter Text),
|
||||||
|
**Übersetzungstabellen anzeigen** und **Projektdateien wiederherstellen** verfügbar.
|
||||||
|
Nach der Änderung im Textformular das Projekt erneut auswählen.
|
||||||
|
|
||||||
|
Alle gespeicherten Stände, Zuordnungen, Projektbegriffe, Ausnahmen und Kategorien
|
||||||
|
bleiben erhalten. Die Dateien im neuen Ordner werden dabei nicht verändert.
|
||||||
|
Ein bereits einem anderen Velum-Projekt zugeordneter Zielordner wird abgewiesen.
|
||||||
|
Bestehende Projekte können für Text und Zwischenablage auch verwendet werden,
|
||||||
|
wenn ihr Quellordner gerade nicht erreichbar ist.
|
||||||
|
|
||||||
|
## Übersetzungstabellen exportieren
|
||||||
|
|
||||||
|
In „Übersetzungstabellen anzeigen“ eine Projekt- oder Sitzungstabelle öffnen und
|
||||||
|
„Übersetzungstabelle exportieren“ auswählen. Beide Exporte sind auch im Aktionsmenü
|
||||||
|
der Tabellenzeilen verfügbar:
|
||||||
|
|
||||||
|
- **Begriffe als Textdatei**: alle Originalbegriffe einschließlich Gruppenvarianten,
|
||||||
|
alphabetisch sortiert, ein Begriff pro Zeile. Identische Begriffe erscheinen einmal.
|
||||||
|
- **Ersetzungen als Textdatei**: `Original → Platzhalter`, ebenfalls alphabetisch.
|
||||||
|
Zusammengefasste Varianten zeigen auf den wirksamen Hauptplatzhalter. Unterschiedliche
|
||||||
|
Ersetzungen desselben Originals bleiben getrennt erhalten.
|
||||||
|
|
||||||
|
Exportiert wird immer die gesamte aktuell geöffnete Tabelle, einschließlich gerade
|
||||||
|
hinzugefügter oder geänderter Einträge; eine Suchfilterung schränkt den Export nicht ein.
|
||||||
|
Die UTF-8-Dateien liegen unter `~/Downloads/Velum` und werden im Finder markiert.
|
||||||
|
Vorhandene Exporte werden nicht überschrieben. Die Dateien enthalten Klartext;
|
||||||
|
sie werden lokal mit Dateirechten `0600` gespeichert und an keinen Dienst übertragen.
|
||||||
|
Zeilenumbrüche, Tabs und Backslashes innerhalb eines Werts werden als `\n`, `\r`,
|
||||||
|
`\t` bzw. `\\` dargestellt, damit jeder Eintrag in einer Zeile bleibt.
|
||||||
|
|
||||||
## Konfiguration
|
## Konfiguration
|
||||||
|
|
||||||
@@ -19,7 +141,7 @@ Alle Werte sind in den Raycast-Einstellungen pro Extension einstellbar.
|
|||||||
- `Ausgabe der Schnellbefehle` — `In die Zwischenablage kopieren` (Default) oder `Am Cursor einfügen`
|
- `Ausgabe der Schnellbefehle` — `In die Zwischenablage kopieren` (Default) oder `Am Cursor einfügen`
|
||||||
- `Eigener Name` — Default-Signatur für AI-generierte Email-Antworten, im Antwort-Befehl pro Aufruf überschreibbar
|
- `Eigener Name` — Default-Signatur für AI-generierte Email-Antworten, im Antwort-Befehl pro Aufruf überschreibbar
|
||||||
|
|
||||||
Das KI-Modell ist keine Preference: jeder AI-Befehl zeigt ein `KI-Modell`-Dropdown mit dem aktuellen Modell-Katalog aus `src/ai.ts`. Die Auswahl wird in `LocalStorage` (`velum.ai.last-model`) persistiert und ist beim nächsten Aufruf in jedem AI-Befehl vorausgewählt.
|
Jeder KI-Befehl bezieht die Auswahl im Feld **KI-Modell** aus `AI.Model` der installierten Raycast-Version. Mit **Raycast-Standard** verwendet Velum das Standardmodell der Raycast-API. Velum merkt sich die letzte Auswahl für alle KI-Befehle. Fehlt das gespeicherte Modell im API-Katalog, ist beim nächsten Aufruf **Raycast-Standard** ausgewählt.
|
||||||
- `Maximale Anzahl gespeicherter Sitzungen` — älteste werden geprunt (Default 20)
|
- `Maximale Anzahl gespeicherter Sitzungen` — älteste werden geprunt (Default 20)
|
||||||
- `Raycast nach Kopieren/Einfügen schließen` — Auto-Close und Pop-To-Root nach AI-Workflow-Abschluss (Default an)
|
- `Raycast nach Kopieren/Einfügen schließen` — Auto-Close und Pop-To-Root nach AI-Workflow-Abschluss (Default an)
|
||||||
|
|
||||||
@@ -52,7 +174,7 @@ Jeder AI-Befehl pseudonymisiert die Eingabe via Velum, zeigt einen Confirm-Schri
|
|||||||
|
|
||||||
### Sitzungen
|
### Sitzungen
|
||||||
|
|
||||||
- `Sitzungen verwalten` — Sitzungen anlegen, aktivieren, ansehen, leeren oder löschen. Zeigt das Mapping je Sitzung als Markdown-Tabelle.
|
- **Übersetzungstabellen anzeigen → Sitzungen** — Sitzungen anlegen, umbenennen, aktivieren oder löschen. Die Übersetzungstabelle jeder Sitzung zeigt ihre Zuordnungen und bietet die Personenzusammenführung.
|
||||||
|
|
||||||
## Sitzungen
|
## Sitzungen
|
||||||
|
|
||||||
@@ -82,3 +204,66 @@ npm run build # ray build -e dist
|
|||||||
```
|
```
|
||||||
|
|
||||||
Voraussetzungen: macOS, Node 22+, Raycast (Pro für die AI-Befehle).
|
Voraussetzungen: macOS, Node 22+, Raycast (Pro für die AI-Befehle).
|
||||||
|
|
||||||
|
### Diagnose und Speicherbedarf der Projektanalyse
|
||||||
|
|
||||||
|
Die Fähigkeitsprüfung richtet sich nach den ausgewählten Dateien. Textprojekte
|
||||||
|
benötigen `request_force_masks`; Office/PDF zusätzlich die Dokumentprüfung,
|
||||||
|
Wiederherstellung, Autorenprüfung und `document_image_policy`. Fehlt eine
|
||||||
|
Fähigkeit, zeigt Raycast ihren Namen und die angesprochene API-URL. Fehlende
|
||||||
|
Endpunkte (404/405), Anmeldung/Proxy (HTTP-Status oder HTML) und Zeitlimits werden
|
||||||
|
getrennt gemeldet. Die Prüfung hat 15 Sekunden, jede Textanalyse-Anfrage 60 Sekunden Zeit.
|
||||||
|
|
||||||
|
Am 8. November 2026 meldete `https://velum.elycon.solutions/api/project-capabilities`
|
||||||
|
alle bisherigen Projektfähigkeiten, aber kein `document_image_policy`. Die lokale
|
||||||
|
API enthält diese Bildbehandlung bereits. Für Office/PDF muss das Backend daher
|
||||||
|
auf diesen Stand aktualisiert werden; ein höheres Upload-Limit löst den
|
||||||
|
Versionskonflikt nicht. Die Bildprüfung wird nicht umgangen.
|
||||||
|
|
||||||
|
Textdateien werden unabhängig von ihrer Gesamtgröße als UTF-8-Datenstrom gelesen.
|
||||||
|
Analysepakete bestehen aus vollständigen Zeilen und enthalten höchstens 24.000
|
||||||
|
UTF-16-Einheiten samt Wortkontext an den Grenzen. Kleine Dateien teilen sich
|
||||||
|
weiterhin API-Pakete. Zuordnungen gelten über alle Pakete und Dateien hinweg;
|
||||||
|
Unicode-Positionen und die bisherige Auswahl einzelner Vorkommen bleiben erhalten.
|
||||||
|
Eine einzelne Zeile mit mehr als 20.000 UTF-16-Einheiten wird mit Dateiname und
|
||||||
|
Zeilennummer abgelehnt, statt ein Wort zu zerschneiden.
|
||||||
|
|
||||||
|
Die Ausgabe wird aus dem ursprünglichen Datenstrom und ausschließlich den
|
||||||
|
bestätigten Trefferpositionen zusammengesetzt. Zeilenreihenfolge, CRLF/LF/CR,
|
||||||
|
UTF-8-BOM und die letzte Zeile ohne Umbruch bleiben erhalten. Auch Hashprüfungen,
|
||||||
|
das Übernehmen unveränderter Dateien und Prüfungen vor dem Ersetzen lesen große
|
||||||
|
Dateien abschnittsweise. HTTP 413 und Serverfehler werden bei mehrteiligen
|
||||||
|
Paketen durch begrenztes Aufteilen eingegrenzt; Authentifizierungs- und
|
||||||
|
Validierungsfehler werden nicht wiederholt.
|
||||||
|
|
||||||
|
Die 20-MiB-Uploadgrenze gilt für XLSX, PPTX und PDF. Bei DOCX gelten lokal
|
||||||
|
128 MiB für die Datei und 128 MiB für die entpackten Paketdaten. Auch mehr als 50.000 Vorkommen werden verarbeitet. Treffergruppen
|
||||||
|
und Vorkommen erscheinen in Seiten mit höchstens 200 Einträgen; die Suche und
|
||||||
|
Kategorieauswahl gelten für den gesamten Bestand. Die Projektzuordnung bleibt
|
||||||
|
lokal konsistent. An die Text-API gehen nur für das aktuelle Paket relevante
|
||||||
|
Begriffs- und Aliasregeln, statt die gesamte wachsende Zuordnung erneut zu senden.
|
||||||
|
Fehler bleiben in der Dateiauswahl sichtbar und lassen sich kopieren. Originale werden
|
||||||
|
erst nach der bestehenden Bestätigung und mit den bestehenden Änderungsprüfungen
|
||||||
|
und Backups ersetzt. Bei ungültigem UTF-8, Quelländerungen oder Schreibfehlern
|
||||||
|
wird keine unvollständige Ausgabe veröffentlicht.
|
||||||
|
|
||||||
|
|
||||||
|
### Große Excel-Dateien wiederherstellen
|
||||||
|
|
||||||
|
XLSX-Dateien werden lokal aus dem ZIP-Datenstrom nach Downloads/Velum zurückübersetzt.
|
||||||
|
Die Wiederherstellung lädt weder die gesamte Arbeitsmappe noch ein vollständiges
|
||||||
|
Tabellenblatt in den Speicher. Sie benötigt keinen API-Upload und unterliegt daher
|
||||||
|
nicht der 20-MiB-Uploadgrenze. Auch die Dateiauswahl bietet größere XLSX-Dateien an.
|
||||||
|
Die Uploadgrenze für die Pseudonymisierung bleibt bestehen.
|
||||||
|
|
||||||
|
Geteilte Platzhalter in formatierten Zelltexten, Inline-Strings, Formeln, Kommentare,
|
||||||
|
Hyperlinks und XML-Attribute werden berücksichtigt; andere Paketdaten bleiben erhalten.
|
||||||
|
Jeder entpackte Bestandteil wird gegen Größe und CRC aus dem ZIP-Inhaltsverzeichnis
|
||||||
|
geprüft. Bei Fehlern oder Quelländerungen wird die unvollständige Ausgabe entfernt;
|
||||||
|
Originaldateien und vorhandene Ausgaben werden nicht überschrieben. Mehrteilige ZIPs,
|
||||||
|
ZIP64-Zentralverzeichnisse, verschlüsselte Archive, DTDs und Pakete über 2 GiB entpackter
|
||||||
|
Größe werden mit einer sichtbaren Meldung abgewiesen. Einzelne Textknoten bzw. gepufferte
|
||||||
|
Rich-Text-Zellen sind auf 4 MiB begrenzt.
|
||||||
|
|
||||||
|
Fehler im Klartext-Export bleiben in der Dateiauswahl sichtbar, einschließlich Dateiname
|
||||||
|
und kopierbarer Fehlermeldung. DOCX/PPTX verwenden weiterhin die vorhandene API.
|
||||||
|
|||||||
29
package-lock.json
generated
29
package-lock.json
generated
@@ -9,12 +9,15 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@raycast/api": "^1.104.17",
|
"@raycast/api": "^1.104.17",
|
||||||
"@raycast/utils": "^2.2.5",
|
"@raycast/utils": "^2.2.5",
|
||||||
"marked": "^18.0.3"
|
"fflate": "0.8.3",
|
||||||
|
"marked": "^18.0.3",
|
||||||
|
"saxes": "6.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@raycast/eslint-config": "^2.0.4",
|
"@raycast/eslint-config": "^2.0.4",
|
||||||
"@types/node": "^22.15.3",
|
"@types/node": "^22.15.3",
|
||||||
"@types/react": "^19.1.2",
|
"@types/react": "^19.1.2",
|
||||||
|
"esbuild": "0.27.7",
|
||||||
"eslint": "^9.26.0",
|
"eslint": "^9.26.0",
|
||||||
"prettier": "^3.5.3",
|
"prettier": "^3.5.3",
|
||||||
"typescript": "^5.8.3"
|
"typescript": "^5.8.3"
|
||||||
@@ -2133,6 +2136,12 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fflate": {
|
||||||
|
"version": "0.8.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||||
|
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/file-entry-cache": {
|
"node_modules/file-entry-cache": {
|
||||||
"version": "8.0.0",
|
"version": "8.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
|
||||||
@@ -2720,6 +2729,18 @@
|
|||||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/saxes": {
|
||||||
|
"version": "6.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||||
|
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"xmlchars": "^2.2.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=v12.22.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/semver": {
|
"node_modules/semver": {
|
||||||
"version": "7.7.4",
|
"version": "7.7.4",
|
||||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
|
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
|
||||||
@@ -2990,6 +3011,12 @@
|
|||||||
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/xmlchars": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/yocto-queue": {
|
"node_modules/yocto-queue": {
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||||
|
|||||||
102
package.json
102
package.json
@@ -2,7 +2,7 @@
|
|||||||
"$schema": "https://www.raycast.com/schemas/extension.json",
|
"$schema": "https://www.raycast.com/schemas/extension.json",
|
||||||
"name": "velum",
|
"name": "velum",
|
||||||
"title": "Velum",
|
"title": "Velum",
|
||||||
"description": "Text per Velum-API pseudonymisieren und wiederherstellen.",
|
"description": "Pseudonymisierung von Texten und Projektdateien mit Velum",
|
||||||
"icon": "extension-icon.png",
|
"icon": "extension-icon.png",
|
||||||
"author": "raphael",
|
"author": "raphael",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@@ -29,6 +29,12 @@
|
|||||||
"description": "Aus Notizen, Stichpunkten oder einem Transkript ein strukturiertes Briefing per Raycast-KI erstellen — pseudonymisiert.",
|
"description": "Aus Notizen, Stichpunkten oder einem Transkript ein strukturiertes Briefing per Raycast-KI erstellen — pseudonymisiert.",
|
||||||
"mode": "view"
|
"mode": "view"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"name": "summarize-meeting-notes",
|
||||||
|
"title": "Meeting Notes strukturieren",
|
||||||
|
"description": "Aus Meeting-Notizen in Prosa eine sauber strukturierte Zusammenfassung (Kontext, Teilnehmer, Themen, Entscheidungen, Action Items) per Raycast-KI erstellen — pseudonymisiert.",
|
||||||
|
"mode": "view"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "extract-action-items",
|
"name": "extract-action-items",
|
||||||
"title": "Action Items extrahieren",
|
"title": "Action Items extrahieren",
|
||||||
@@ -56,14 +62,20 @@
|
|||||||
{
|
{
|
||||||
"name": "pseudonymize-selected-text",
|
"name": "pseudonymize-selected-text",
|
||||||
"title": "Markierten Text pseudonymisieren",
|
"title": "Markierten Text pseudonymisieren",
|
||||||
"description": "Aktuell markierten Text pseudonymisieren und das Ergebnis kopieren oder einfügen.",
|
"description": "Markierten Text mit gewähltem Projekt oder Sitzung pseudonymisieren und kopieren oder einfügen.",
|
||||||
"mode": "no-view"
|
"mode": "view"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "pseudonymize-clipboard",
|
"name": "pseudonymize-clipboard",
|
||||||
"title": "Zwischenablage pseudonymisieren",
|
"title": "Zwischenablage pseudonymisieren",
|
||||||
"description": "Aktuellen Zwischenablage-Text pseudonymisieren und das Ergebnis kopieren oder einfügen.",
|
"description": "Zwischenablage mit gewähltem Projekt oder Sitzung pseudonymisieren und kopieren oder einfügen.",
|
||||||
"mode": "no-view"
|
"mode": "view"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "paste-pseudonymized-clipboard",
|
||||||
|
"title": "Zwischenablage pseudonymisiert einfügen",
|
||||||
|
"description": "Text aus der Zwischenablage nach Projekt- und Trefferprüfung an der Cursorposition pseudonymisiert einfügen.",
|
||||||
|
"mode": "view"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "depseudonymize-text",
|
"name": "depseudonymize-text",
|
||||||
@@ -74,20 +86,53 @@
|
|||||||
{
|
{
|
||||||
"name": "depseudonymize-selected-text",
|
"name": "depseudonymize-selected-text",
|
||||||
"title": "Markierten Text wiederherstellen",
|
"title": "Markierten Text wiederherstellen",
|
||||||
"description": "Aktuell markierten Text mit der aktiven Sitzung wiederherstellen und das Ergebnis kopieren oder einfügen.",
|
"description": "Markierten Text übernehmen, Projekt oder Sitzung wählen und wiederherstellen.",
|
||||||
"mode": "no-view"
|
"mode": "view"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "depseudonymize-clipboard",
|
"name": "depseudonymize-clipboard",
|
||||||
"title": "Zwischenablage wiederherstellen",
|
"title": "Zwischenablage wiederherstellen",
|
||||||
"description": "Aktuellen Zwischenablage-Text mit der aktiven Sitzung wiederherstellen und das Ergebnis kopieren oder einfügen.",
|
"description": "Zwischenablage übernehmen, Projekt oder Sitzung wählen und wiederherstellen.",
|
||||||
"mode": "no-view"
|
"mode": "view"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "manage-sessions",
|
"name": "paste-restored-clipboard",
|
||||||
"title": "Sitzungen verwalten",
|
"title": "Zwischenablage wiederhergestellt einfügen",
|
||||||
"description": "Velum-Sitzungen mit Zuordnungen anlegen, aktivieren, ansehen und löschen.",
|
"description": "Velum-Platzhalter aus der Zwischenablage mit gewähltem Projekt oder Sitzung wiederherstellen und an der Cursorposition einfügen.",
|
||||||
"mode": "view"
|
"mode": "view"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "show-translation-tables",
|
||||||
|
"title": "Übersetzungstabellen anzeigen",
|
||||||
|
"description": "Projekt- und Sitzungszuordnungen bearbeiten, Personen zusammenfassen und Sitzungen verwalten.",
|
||||||
|
"mode": "view"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pseudonymize-project-files",
|
||||||
|
"title": "Projektdateien pseudonymisieren",
|
||||||
|
"description": "Finder-Projektordner und Kategorien wählen, Zuordnungen prüfen und Dateien pseudonymisieren.",
|
||||||
|
"mode": "view",
|
||||||
|
"icon": "extension-icon.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "relocate-project",
|
||||||
|
"title": "Projektordner ändern",
|
||||||
|
"description": "Ein gespeichertes Projekt nach Verschieben oder Umbenennen seinem neuen Ordner zuordnen.",
|
||||||
|
"mode": "view"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "restore-project-files",
|
||||||
|
"title": "Projektdateien wiederherstellen",
|
||||||
|
"description": "Aktuelle Dateien aus dem Kopienordner als Klartext exportieren, Zuordnungen nachbearbeiten und frühere Stände wiederherstellen.",
|
||||||
|
"mode": "view",
|
||||||
|
"icon": "extension-icon.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "migration-location",
|
||||||
|
"title": "Migrationsziel anzeigen",
|
||||||
|
"description": "Velum-Datenordner für das einmalige Migrationstool kopieren.",
|
||||||
|
"mode": "view",
|
||||||
|
"icon": "extension-icon.png"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"preferences": [
|
"preferences": [
|
||||||
@@ -136,28 +181,6 @@
|
|||||||
"required": false,
|
"required": false,
|
||||||
"default": "profile"
|
"default": "profile"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "sessionMode",
|
|
||||||
"title": "Standard-Sitzungsmodus",
|
|
||||||
"description": "Bestimmt, wie Schnellbefehle eine Zuordnungs-Sitzung wählen.",
|
|
||||||
"type": "dropdown",
|
|
||||||
"required": true,
|
|
||||||
"default": "reuse-active",
|
|
||||||
"data": [
|
|
||||||
{
|
|
||||||
"title": "Aktive Sitzung wiederverwenden",
|
|
||||||
"value": "reuse-active"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"title": "Neue Sitzung pro Anfrage",
|
|
||||||
"value": "new-each-request"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"title": "Tagessitzung",
|
|
||||||
"value": "daily"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "quickOutput",
|
"name": "quickOutput",
|
||||||
"title": "Ausgabe der Schnellbefehle",
|
"title": "Ausgabe der Schnellbefehle",
|
||||||
@@ -203,21 +226,28 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"build:project-worker": "node scripts/build-project-worker.mjs",
|
||||||
|
"prebuild": "npm run build:project-worker",
|
||||||
"build": "ray build -e dist",
|
"build": "ray build -e dist",
|
||||||
|
"predev": "npm run build:project-worker",
|
||||||
"dev": "ray develop",
|
"dev": "ray develop",
|
||||||
"fix-lint": "ray lint --fix",
|
"fix-lint": "ray lint --fix",
|
||||||
"lint": "ray lint",
|
"lint": "ray lint",
|
||||||
"publish": "ray publish"
|
"publish": "npm run build:project-worker && ray publish",
|
||||||
|
"test": "bun test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@raycast/api": "^1.104.17",
|
"@raycast/api": "^1.104.17",
|
||||||
"@raycast/utils": "^2.2.5",
|
"@raycast/utils": "^2.2.5",
|
||||||
"marked": "^18.0.3"
|
"fflate": "0.8.3",
|
||||||
|
"marked": "^18.0.3",
|
||||||
|
"saxes": "6.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@raycast/eslint-config": "^2.0.4",
|
"@raycast/eslint-config": "^2.0.4",
|
||||||
"@types/node": "^22.15.3",
|
"@types/node": "^22.15.3",
|
||||||
"@types/react": "^19.1.2",
|
"@types/react": "^19.1.2",
|
||||||
|
"esbuild": "0.27.7",
|
||||||
"eslint": "^9.26.0",
|
"eslint": "^9.26.0",
|
||||||
"prettier": "^3.5.3",
|
"prettier": "^3.5.3",
|
||||||
"typescript": "^5.8.3"
|
"typescript": "^5.8.3"
|
||||||
|
|||||||
26
scripts/build-project-worker.mjs
Normal file
26
scripts/build-project-worker.mjs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { copyFile, mkdir } from "node:fs/promises";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { join, resolve } from "node:path";
|
||||||
|
import { build } from "esbuild";
|
||||||
|
|
||||||
|
const root = fileURLToPath(new URL("..", import.meta.url));
|
||||||
|
const server = process.env.VELUM_BACKEND_DIR ?? join(root, "../../velum/backend");
|
||||||
|
const assets = join(root, "assets");
|
||||||
|
const python = join(assets, "velum-docx", "velum");
|
||||||
|
await mkdir(join(python, "assets"), { recursive: true });
|
||||||
|
const files = ["documents.py", "docx_local.py", "office_images.py", "contexts.py", "assets/image-placeholder.png"];
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
await copyFile(join(server, "velum", file), join(python, file));
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Velum-Backend-Quellen fehlen unter ${server}. Setze VELUM_BACKEND_DIR auf das backend-Verzeichnis des Velum-Checkouts.`, { cause: error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await build({
|
||||||
|
entryPoints: [join(root, "src/project-worker.ts")],
|
||||||
|
outfile: join(assets, "velum-project-worker.cjs"),
|
||||||
|
platform: "node",
|
||||||
|
target: "node22",
|
||||||
|
bundle: true,
|
||||||
|
alias: { "@raycast/api": resolve(root, "src/lib/worker-runtime.ts") },
|
||||||
|
});
|
||||||
@@ -13,15 +13,14 @@ import {
|
|||||||
Toast,
|
Toast,
|
||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { execFile } from "node:child_process";
|
|
||||||
import { promisify } from "node:util";
|
|
||||||
import { marked } from "marked";
|
import { marked } from "marked";
|
||||||
import { type ReactNode, useEffect, useRef, useState } from "react";
|
import { type ReactNode, useEffect, useRef, useState } from "react";
|
||||||
import type { Creativity } from "./ai";
|
import { resolveRaycastModel, type Creativity } from "./ai";
|
||||||
import { getPreferences } from "./preferences";
|
import { getPreferences } from "./preferences";
|
||||||
import type { VelumSession } from "./types";
|
import type { VelumSession } from "./types";
|
||||||
import { markdownCodeBlock, mappingDetailTable, sessionSubtitle } from "./ui";
|
import { markdownCodeBlock, mappingDetailTable, sessionSubtitle } from "./ui";
|
||||||
import { localDepseudonymize } from "./velum";
|
import { localDepseudonymize } from "./velum";
|
||||||
|
import { copyRichText } from "./rich-clipboard";
|
||||||
|
|
||||||
export async function maybeCloseRaycast(): Promise<void> {
|
export async function maybeCloseRaycast(): Promise<void> {
|
||||||
if (getPreferences().closeAfterAction) {
|
if (getPreferences().closeAfterAction) {
|
||||||
@@ -29,33 +28,6 @@ export async function maybeCloseRaycast(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile);
|
|
||||||
|
|
||||||
// Raycast 2.0 Beta's Clipboard.copy with { html, text } only writes plain text
|
|
||||||
// to the system pasteboard. We bypass it via osascript / JXA, which sets both
|
|
||||||
// the HTML and plain-text pasteboard types directly on NSPasteboard. Content
|
|
||||||
// is passed via environment variables to avoid shell-quoting hazards.
|
|
||||||
const RICH_COPY_SCRIPT = [
|
|
||||||
"ObjC.import('AppKit');",
|
|
||||||
"const env = $.NSProcessInfo.processInfo.environment;",
|
|
||||||
"const html = env.objectForKey('VELUM_HTML');",
|
|
||||||
"const text = env.objectForKey('VELUM_TEXT');",
|
|
||||||
"const pb = $.NSPasteboard.generalPasteboard;",
|
|
||||||
"pb.clearContents;",
|
|
||||||
"pb.setStringForType(html, 'public.html');",
|
|
||||||
"pb.setStringForType(text, 'public.utf8-plain-text');",
|
|
||||||
].join("\n");
|
|
||||||
|
|
||||||
export async function copyRichText(html: string, text: string): Promise<void> {
|
|
||||||
await execFileAsync(
|
|
||||||
"osascript",
|
|
||||||
["-l", "JavaScript", "-e", RICH_COPY_SCRIPT],
|
|
||||||
{
|
|
||||||
env: { ...process.env, VELUM_HTML: html, VELUM_TEXT: text },
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export type AiCommandLabels = {
|
export type AiCommandLabels = {
|
||||||
pageHeading: string;
|
pageHeading: string;
|
||||||
runningLabel: string;
|
runningLabel: string;
|
||||||
@@ -118,7 +90,7 @@ export function PseudonymizationConfirm(props: PseudoStageProps) {
|
|||||||
>
|
>
|
||||||
<Form.Description
|
<Form.Description
|
||||||
title="Bestätigen"
|
title="Bestätigen"
|
||||||
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Sitzung: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
|
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Kontext: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
|
||||||
/>
|
/>
|
||||||
<Form.TextArea
|
<Form.TextArea
|
||||||
id="pseudonymizedText"
|
id="pseudonymizedText"
|
||||||
@@ -171,7 +143,7 @@ export function AiStreamResult(props: PseudoStageProps) {
|
|||||||
try {
|
try {
|
||||||
const prompt = buildPrompt(pseudonymizedText, instructions);
|
const prompt = buildPrompt(pseudonymizedText, instructions);
|
||||||
const stream = AI.ask(prompt, {
|
const stream = AI.ask(prompt, {
|
||||||
model: model as AI.Model,
|
model: resolveRaycastModel(model),
|
||||||
creativity,
|
creativity,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
|
|||||||
95
src/ai.ts
95
src/ai.ts
@@ -1,4 +1,4 @@
|
|||||||
import { LocalStorage } from "@raycast/api";
|
import { AI, LocalStorage } from "@raycast/api";
|
||||||
|
|
||||||
export type Creativity = "none" | "low" | "medium" | "high";
|
export type Creativity = "none" | "low" | "medium" | "high";
|
||||||
|
|
||||||
@@ -9,86 +9,29 @@ export const CREATIVITY_OPTIONS: Creativity[] = [
|
|||||||
"high",
|
"high",
|
||||||
];
|
];
|
||||||
|
|
||||||
export type ModelOption = { value: string; title: string };
|
export const DEFAULT_MODEL = "__raycast_default__";
|
||||||
|
|
||||||
export const MODEL_OPTIONS: ModelOption[] = [
|
|
||||||
{ value: "anthropic-claude-opus-4-7", title: "Claude 4.7 Opus" },
|
|
||||||
{ value: "anthropic-claude-sonnet-4-6", title: "Claude 4.6 Sonnet" },
|
|
||||||
{ value: "anthropic-claude-opus-4-6", title: "Claude 4.6 Opus" },
|
|
||||||
{ value: "anthropic-claude-sonnet-4-5", title: "Claude 4.5 Sonnet" },
|
|
||||||
{ value: "anthropic-claude-opus-4-5", title: "Claude 4.5 Opus" },
|
|
||||||
{ value: "anthropic-claude-4-5-haiku", title: "Claude 4.5 Haiku" },
|
|
||||||
{ value: "anthropic-claude-sonnet-4", title: "Claude 4 Sonnet" },
|
|
||||||
{ value: "openai-gpt-5.4", title: "OpenAI GPT-5.4" },
|
|
||||||
{ value: "openai-gpt-5.4-mini", title: "OpenAI GPT-5.4 Mini" },
|
|
||||||
{ value: "openai-gpt-5.4-nano", title: "OpenAI GPT-5.4 Nano" },
|
|
||||||
{ value: "openai-gpt-5.3-instant", title: "OpenAI GPT-5.3 Instant" },
|
|
||||||
{ value: "openai-gpt-5.3-codex", title: "OpenAI GPT-5.3 Codex" },
|
|
||||||
{ value: "openai-gpt-5.2", title: "OpenAI GPT-5.2" },
|
|
||||||
{ value: "openai-gpt-5.2-instant", title: "OpenAI GPT-5.2 Instant" },
|
|
||||||
{ value: "openai-gpt-5.1", title: "OpenAI GPT-5.1" },
|
|
||||||
{ value: "openai-gpt-5.1-instant", title: "OpenAI GPT-5.1 Instant" },
|
|
||||||
{ value: "openai-gpt-5.1-codex", title: "OpenAI GPT-5.1 Codex" },
|
|
||||||
{ value: "openai_o1-gpt-5", title: "OpenAI GPT-5" },
|
|
||||||
{ value: "openai-gpt-5-mini", title: "OpenAI GPT-5 Mini" },
|
|
||||||
{ value: "openai-gpt-5-nano", title: "OpenAI GPT-5 Nano" },
|
|
||||||
{ value: "openai-gpt-4.1", title: "OpenAI GPT-4.1" },
|
|
||||||
{ value: "openai-gpt-4.1-mini", title: "OpenAI GPT-4.1 Mini" },
|
|
||||||
{ value: "openai-gpt-4.1-nano", title: "OpenAI GPT-4.1 Nano" },
|
|
||||||
{ value: "openai-gpt-4o", title: "OpenAI GPT-4o" },
|
|
||||||
{ value: "openai-gpt-4o-mini", title: "OpenAI GPT-4o mini" },
|
|
||||||
{ value: "openai_o1-o3", title: "OpenAI o3" },
|
|
||||||
{ value: "openai_o1-o3-mini", title: "OpenAI o3-mini" },
|
|
||||||
{ value: "openai_o1-o4-mini", title: "OpenAI o4-mini" },
|
|
||||||
{ value: "openai_o1-o1", title: "OpenAI o1" },
|
|
||||||
{ value: "google-gemini-3.1-pro", title: "Google Gemini 3.1 Pro" },
|
|
||||||
{ value: "google-gemini-3-flash", title: "Google Gemini 3 Flash" },
|
|
||||||
{
|
|
||||||
value: "google-gemini-3.1-flash-lite",
|
|
||||||
title: "Google Gemini 3.1 Flash Lite",
|
|
||||||
},
|
|
||||||
{ value: "google-gemini-2.5-pro", title: "Google Gemini 2.5 Pro" },
|
|
||||||
{ value: "google-gemini-2.5-flash", title: "Google Gemini 2.5 Flash" },
|
|
||||||
{
|
|
||||||
value: "google-gemini-2.5-flash-lite",
|
|
||||||
title: "Google Gemini 2.5 Flash Lite",
|
|
||||||
},
|
|
||||||
{ value: "xai-grok-4.20", title: "xAI Grok 4.20" },
|
|
||||||
{ value: "xai-grok-4", title: "xAI Grok 4" },
|
|
||||||
{ value: "xai-grok-4-fast", title: "xAI Grok 4 Fast" },
|
|
||||||
{ value: "xai-grok-4-1-fast", title: "xAI Grok 4.1 Fast" },
|
|
||||||
{ value: "xai-grok-code-fast", title: "xAI Grok Code Fast" },
|
|
||||||
{ value: "perplexity-sonar-pro", title: "Perplexity Sonar Pro" },
|
|
||||||
{ value: "perplexity-sonar", title: "Perplexity Sonar" },
|
|
||||||
{ value: "mistral-mistral-large-latest", title: "Mistral Large" },
|
|
||||||
{ value: "mistral-mistral-medium-latest", title: "Mistral Medium" },
|
|
||||||
{ value: "mistral-mistral-small-latest", title: "Mistral Small" },
|
|
||||||
{ value: "mistral-codestral-latest", title: "Mistral Codestral" },
|
|
||||||
{ value: "mistral-open-mistral-nemo", title: "Mistral Nemo" },
|
|
||||||
{ value: "groq-llama-3.3-70b-versatile", title: "Groq Llama 3.3 70B" },
|
|
||||||
{
|
|
||||||
value: "groq-meta-llama/llama-4-scout-17b-16e-instruct",
|
|
||||||
title: "Groq Llama 4 Scout",
|
|
||||||
},
|
|
||||||
{ value: "groq-llama-3.1-8b-instant", title: "Groq Llama 3.1 8B" },
|
|
||||||
{ value: "groq-qwen/qwen3-32b", title: "Groq Qwen3 32B" },
|
|
||||||
{ value: "groq-openai/gpt-oss-120b", title: "Groq GPT-OSS 120B" },
|
|
||||||
{ value: "groq-openai/gpt-oss-20b", title: "Groq GPT-OSS 20B" },
|
|
||||||
{ value: "together-deepseek-ai/DeepSeek-R1", title: "DeepSeek R1" },
|
|
||||||
{ value: "together-deepseek-ai/DeepSeek-V3", title: "DeepSeek V3" },
|
|
||||||
{ value: "together-moonshotai/Kimi-K2.5", title: "Kimi K2.5" },
|
|
||||||
];
|
|
||||||
|
|
||||||
const LAST_MODEL_STORAGE_KEY = "velum.ai.last-model";
|
const LAST_MODEL_STORAGE_KEY = "velum.ai.last-model";
|
||||||
|
|
||||||
export const DEFAULT_MODEL: string = MODEL_OPTIONS[0].value;
|
// Raycast lists current names before compatibility aliases for the same model ID.
|
||||||
|
const raycastModels = new Map<string, { value: AI.Model; title: string }>();
|
||||||
|
for (const [name, value] of Object.entries(AI.Model)) {
|
||||||
|
if (!raycastModels.has(value)) {
|
||||||
|
raycastModels.set(value, { value, title: name.replaceAll("_", " ") });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MODEL_OPTIONS = [
|
||||||
|
{ value: DEFAULT_MODEL, title: "Raycast-Standard" },
|
||||||
|
...raycastModels.values(),
|
||||||
|
];
|
||||||
|
|
||||||
|
export function resolveRaycastModel(selection: string): AI.Model | undefined {
|
||||||
|
return raycastModels.get(selection)?.value;
|
||||||
|
}
|
||||||
|
|
||||||
export async function getLastUsedModel(): Promise<string> {
|
export async function getLastUsedModel(): Promise<string> {
|
||||||
const stored = await LocalStorage.getItem<string>(LAST_MODEL_STORAGE_KEY);
|
const stored = await LocalStorage.getItem<string>(LAST_MODEL_STORAGE_KEY);
|
||||||
if (stored && MODEL_OPTIONS.some((option) => option.value === stored)) {
|
return stored && raycastModels.has(stored) ? stored : DEFAULT_MODEL;
|
||||||
return stored;
|
|
||||||
}
|
|
||||||
return DEFAULT_MODEL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setLastUsedModel(model: string): Promise<void> {
|
export async function setLastUsedModel(model: string): Promise<void> {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
Toast,
|
Toast,
|
||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import {
|
||||||
type Creativity,
|
type Creativity,
|
||||||
CREATIVITY_OPTIONS,
|
CREATIVITY_OPTIONS,
|
||||||
@@ -20,20 +20,16 @@ import {
|
|||||||
} from "./ai";
|
} from "./ai";
|
||||||
import { PseudonymizationConfirm } from "./ai-views";
|
import { PseudonymizationConfirm } from "./ai-views";
|
||||||
import { getSelectedTextSafely } from "./selection";
|
import { getSelectedTextSafely } from "./selection";
|
||||||
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
import {
|
import {
|
||||||
createSession,
|
|
||||||
getActiveSessionId,
|
getActiveSessionId,
|
||||||
getSession,
|
|
||||||
listSessions,
|
listSessions,
|
||||||
setActiveSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
} from "./sessions";
|
||||||
import type { EntityType, VelumSession } from "./types";
|
import type { EntityType, VelumSession } from "./types";
|
||||||
import { NEW_SESSION_ID } from "./ui";
|
|
||||||
import {
|
import {
|
||||||
getEntityTypes,
|
getEntityTypes,
|
||||||
normalizePseudonymizeResponse,
|
|
||||||
pseudonymize,
|
|
||||||
} from "./velum";
|
} from "./velum";
|
||||||
|
|
||||||
function buildBriefingPrompt(
|
function buildBriefingPrompt(
|
||||||
@@ -67,9 +63,8 @@ function buildBriefingPrompt(
|
|||||||
].join("\n");
|
].join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = ContextFormValues & {
|
||||||
text: string;
|
text: string;
|
||||||
sessionId: string;
|
|
||||||
entityTypes: string[];
|
entityTypes: string[];
|
||||||
model: string;
|
model: string;
|
||||||
creativity: Creativity;
|
creativity: Creativity;
|
||||||
@@ -81,6 +76,7 @@ export default function Command() {
|
|||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@@ -104,8 +100,9 @@ export default function Command() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const loadedEntityTypes = await getEntityTypes();
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
setEntityTypes(loadedEntityTypes);
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
setSelectedEntityTypes(loadedEntityTypes);
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
} catch {
|
} catch {
|
||||||
setEntityTypes([]);
|
setEntityTypes([]);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -115,11 +112,6 @@ export default function Command() {
|
|||||||
load();
|
load();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadSelectedText() {
|
async function loadSelectedText() {
|
||||||
const selected = await getSelectedTextSafely();
|
const selected = await getSelectedTextSafely();
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@@ -162,45 +154,29 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const session =
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
values.sessionId === NEW_SESSION_ID
|
|
||||||
? await createSession()
|
|
||||||
: ((await getSession(values.sessionId)) ?? (await createSession()));
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
|
|
||||||
const rawResult = await pseudonymize(
|
|
||||||
input,
|
|
||||||
session.mapping,
|
|
||||||
values.entityTypes,
|
|
||||||
);
|
|
||||||
const pseudoResult = normalizePseudonymizeResponse(rawResult);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
pseudoResult.mapping,
|
|
||||||
pseudoResult.selected_entity_types,
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Pseudonymisiert";
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
toast.message = `${pseudoResult.entity_count} Zuordnungen`;
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
|
||||||
push(
|
push(
|
||||||
<PseudonymizationConfirm
|
<PseudonymizationConfirm
|
||||||
session={updatedSession}
|
session={updatedSession}
|
||||||
pseudonymizedText={pseudoResult.pseudonymized_text}
|
pseudonymizedText={pseudoResult.pseudonymized_text}
|
||||||
model={values.model}
|
model={values.model}
|
||||||
creativity={values.creativity}
|
creativity={values.creativity}
|
||||||
instructions={values.instructions}
|
instructions={values.instructions}
|
||||||
buildPrompt={buildBriefingPrompt}
|
buildPrompt={buildBriefingPrompt}
|
||||||
labels={{
|
labels={{
|
||||||
pageHeading: "Briefing",
|
pageHeading: "Briefing",
|
||||||
runningLabel: "KI erstellt Briefing …",
|
runningLabel: "KI erstellt Briefing …",
|
||||||
failureTitle: "Briefing fehlgeschlagen",
|
failureTitle: "Briefing fehlgeschlagen",
|
||||||
copyTitle: "Briefing kopieren",
|
copyTitle: "Briefing kopieren",
|
||||||
pasteTitle: "Briefing einfügen",
|
pasteTitle: "Briefing einfügen",
|
||||||
}}
|
}}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
}} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
@@ -238,27 +214,9 @@ export default function Command() {
|
|||||||
onChange={setText}
|
onChange={setText}
|
||||||
placeholder="Meeting-Notizen, Stichpunkte, Transkript …"
|
placeholder="Meeting-Notizen, Stichpunkte, Transkript …"
|
||||||
/>
|
/>
|
||||||
<Form.Dropdown
|
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||||
id="sessionId"
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
title="Sitzung"
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
defaultValue={defaultSessionId}
|
|
||||||
>
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
value={NEW_SESSION_ID}
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
key={session.id}
|
|
||||||
value={session.id}
|
|
||||||
title={session.name}
|
|
||||||
icon={
|
|
||||||
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Form.Dropdown>
|
|
||||||
{entityTypes.length > 0 ? (
|
{entityTypes.length > 0 ? (
|
||||||
<Form.TagPicker
|
<Form.TagPicker
|
||||||
id="entityTypes"
|
id="entityTypes"
|
||||||
|
|||||||
60
src/context-picker.tsx
Normal file
60
src/context-picker.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { Form, Icon, showToast, Toast } from "@raycast/api";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { canonicalProjectPath, listAllRuns, loadProjectEntityTypes } from "./lib/velum-project";
|
||||||
|
import type { EntityType, VelumSession } from "./types";
|
||||||
|
import { NEW_SESSION_ID } from "./ui";
|
||||||
|
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID } from "./context-values";
|
||||||
|
|
||||||
|
export type { ContextFormValues } from "./context-values";
|
||||||
|
|
||||||
|
export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId?: string;
|
||||||
|
availableEntityTypes: EntityType[]; defaultEntityTypes: EntityType[];
|
||||||
|
onEntityTypesChange: (types: EntityType[]) => void }) {
|
||||||
|
const [projects, setProjects] = useState<Array<{ path: string; name: string }>>([]);
|
||||||
|
const [selected, setSelected] = useState(CHOOSE_CONTEXT_ID);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
listAllRuns().then((runs) => {
|
||||||
|
if (!active) return;
|
||||||
|
const unique = new Map<string, string>();
|
||||||
|
for (const { run } of runs) {
|
||||||
|
const path = canonicalProjectPath(run.projectPath);
|
||||||
|
if (!unique.has(path)) unique.set(path, run.projectName);
|
||||||
|
}
|
||||||
|
setProjects([...unique].map(([path, name]) => ({ path, name })));
|
||||||
|
}).catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Projekte nicht lesbar", message: error.message }));
|
||||||
|
return () => { active = false; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function chooseContext(id: string) {
|
||||||
|
setSelected(CHOOSE_CONTEXT_ID);
|
||||||
|
try {
|
||||||
|
const saved = id.startsWith("project:")
|
||||||
|
? await loadProjectEntityTypes(id.slice("project:".length)) : null;
|
||||||
|
props.onEntityTypesChange(saved ?? props.defaultEntityTypes);
|
||||||
|
setSelected(id);
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Projektkategorien nicht lesbar", message: (error as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<Form.Dropdown id="sessionId" title="Projekt oder Sitzung" value={selected} onChange={chooseContext}>
|
||||||
|
<Form.Dropdown.Item value={CHOOSE_CONTEXT_ID} title="Bitte Kontext wählen" icon={Icon.Circle} />
|
||||||
|
{projects.map((project) => <Form.Dropdown.Item key={project.path}
|
||||||
|
value={`project:${project.path}`} title={`Projekt: ${project.name} · ${project.path}`} icon={Icon.Folder} />)}
|
||||||
|
<Form.Dropdown.Item value={NEW_PROJECT_ID} title="Neues Projekt aus Ordner" icon={Icon.Plus} />
|
||||||
|
{props.sessions.map((session) => <Form.Dropdown.Item key={session.id} value={session.id}
|
||||||
|
title={`Sitzung: ${session.name}`}
|
||||||
|
icon={session.id === props.activeSessionId ? Icon.CheckCircle : Icon.Circle} />)}
|
||||||
|
<Form.Dropdown.Item value={NEW_SESSION_ID} title="Neue Sitzung" icon={Icon.Plus} />
|
||||||
|
</Form.Dropdown>
|
||||||
|
{selected === NEW_SESSION_ID && <Form.TextField id="newSessionName" title="Sitzungsname"
|
||||||
|
placeholder="Leer lassen für einen automatisch vergebenen Namen" />}
|
||||||
|
{selected === NEW_PROJECT_ID && <Form.FilePicker id="newProjectPath" title="Projektordner"
|
||||||
|
allowMultipleSelection={false} canChooseDirectories canChooseFiles={false} />}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
8
src/context-values.ts
Normal file
8
src/context-values.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
export const CHOOSE_CONTEXT_ID = "__choose_context__";
|
||||||
|
export const NEW_PROJECT_ID = "__new_project__";
|
||||||
|
|
||||||
|
export type ContextFormValues = {
|
||||||
|
sessionId: string;
|
||||||
|
newSessionName?: string;
|
||||||
|
newProjectPath?: string[];
|
||||||
|
};
|
||||||
75
src/custom-term-form.tsx
Normal file
75
src/custom-term-form.tsx
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import {
|
||||||
|
Action,
|
||||||
|
ActionPanel,
|
||||||
|
Form,
|
||||||
|
showToast,
|
||||||
|
Toast,
|
||||||
|
useNavigation,
|
||||||
|
} from "@raycast/api";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { validCustomTerm } from "./lib/velum-project";
|
||||||
|
import type { CustomTerm, EntityType } from "./types";
|
||||||
|
|
||||||
|
export function CustomTermForm(props: {
|
||||||
|
entityTypes: EntityType[];
|
||||||
|
onAdd: (term: CustomTerm) => void | Promise<void>;
|
||||||
|
}) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string>();
|
||||||
|
|
||||||
|
async function submit({ type, value }: CustomTerm) {
|
||||||
|
if (busy) return;
|
||||||
|
const term = value.trim().replace(/\s+/gu, " ");
|
||||||
|
if (!validCustomTerm(term)) {
|
||||||
|
setError("Bitte einen Begriff mit 2 bis 200 Zeichen eingeben.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!props.entityTypes.includes(type)) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await props.onAdd({ type, value: term });
|
||||||
|
pop();
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title: "Begriff konnte nicht hinzugefügt werden",
|
||||||
|
message: error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form
|
||||||
|
navigationTitle="Eigenen Begriff hinzufügen"
|
||||||
|
isLoading={busy}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
<Action.SubmitForm title="Begriff hinzufügen" onSubmit={submit} />
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Form.TextField
|
||||||
|
id="value"
|
||||||
|
title="Begriff"
|
||||||
|
error={error}
|
||||||
|
onChange={() => setError(undefined)}
|
||||||
|
/>
|
||||||
|
<Form.Dropdown
|
||||||
|
id="type"
|
||||||
|
title="Kategorie"
|
||||||
|
defaultValue={
|
||||||
|
props.entityTypes.includes("BEGRIFF")
|
||||||
|
? "BEGRIFF"
|
||||||
|
: props.entityTypes[0]
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{props.entityTypes.map((type) => (
|
||||||
|
<Form.Dropdown.Item key={type} value={type} title={type} />
|
||||||
|
))}
|
||||||
|
</Form.Dropdown>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { Clipboard } from "@raycast/api";
|
|
||||||
import { depseudonymizeQuickText } from "./quick";
|
|
||||||
|
|
||||||
export default async function Command() {
|
|
||||||
const clipboardText = await Clipboard.readText();
|
|
||||||
await depseudonymizeQuickText(clipboardText ?? "", "Zwischenablage");
|
|
||||||
}
|
|
||||||
5
src/depseudonymize-clipboard.tsx
Normal file
5
src/depseudonymize-clipboard.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import RestoreTextForm from "./depseudonymize-text";
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
return <RestoreTextForm initialSource="clipboard" />;
|
||||||
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { showToast, Toast } from "@raycast/api";
|
|
||||||
import { depseudonymizeQuickText } from "./quick";
|
|
||||||
import { getSelectedTextSafely } from "./selection";
|
|
||||||
|
|
||||||
export default async function Command() {
|
|
||||||
const selectedText = await getSelectedTextSafely();
|
|
||||||
if (!selectedText) {
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Failure,
|
|
||||||
title: "Kein markierter Text gefunden",
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await depseudonymizeQuickText(selectedText, "Selektion");
|
|
||||||
}
|
|
||||||
5
src/depseudonymize-selected-text.tsx
Normal file
5
src/depseudonymize-selected-text.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import RestoreTextForm from "./depseudonymize-text";
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
return <RestoreTextForm initialSource="selection" />;
|
||||||
|
}
|
||||||
@@ -5,48 +5,117 @@ import {
|
|||||||
Detail,
|
Detail,
|
||||||
Form,
|
Form,
|
||||||
Icon,
|
Icon,
|
||||||
|
showHUD,
|
||||||
showToast,
|
showToast,
|
||||||
Toast,
|
Toast,
|
||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { getSelectedTextSafely } from "./selection";
|
||||||
|
import {
|
||||||
|
canonicalProjectPath,
|
||||||
|
listAllRuns,
|
||||||
|
listRuns,
|
||||||
|
restoreTextWithCount,
|
||||||
|
} from "./lib/velum-project";
|
||||||
import { depseudonymize } from "./velum";
|
import { depseudonymize } from "./velum";
|
||||||
import { getActiveSessionId, getSession, listSessions } from "./sessions";
|
import { getActiveSessionId, getSession, listSessions } from "./sessions";
|
||||||
import type { DepseudonymizeResponse, VelumSession } from "./types";
|
import type { DepseudonymizeResponse, VelumSession } from "./types";
|
||||||
import { markdownCodeBlock, sessionSubtitle } from "./ui";
|
import { markdownCodeBlock, sessionSubtitle } from "./ui";
|
||||||
|
import { restoreRichHtml } from "./lib/rich-text";
|
||||||
|
import { copyRichText, pasteRichText, readRichClipboardHtml } from "./rich-clipboard";
|
||||||
|
import { mappingForRestoration } from "./lib/mapping-groups";
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = {
|
||||||
text: string;
|
text: string;
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function Command() {
|
const CHOOSE_TARGET = "choose-target";
|
||||||
|
type RichSource = { text: string; html: string };
|
||||||
|
|
||||||
|
export default function Command(
|
||||||
|
props: { initialSource?: "selection" | "clipboard"; autoPaste?: boolean } = {},
|
||||||
|
) {
|
||||||
const [text, setText] = useState("");
|
const [text, setText] = useState("");
|
||||||
|
const [richSource, setRichSource] = useState<RichSource>();
|
||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
|
const [projects, setProjects] = useState<
|
||||||
|
Array<{ path: string; name: string }>
|
||||||
|
>([]);
|
||||||
|
const [targetId, setTargetId] = useState(CHOOSE_TARGET);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const { push } = useNavigation();
|
const { push } = useNavigation();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function load() {
|
async function load() {
|
||||||
const [loadedSessions, activeId] = await Promise.all([
|
const initialText = (async (): Promise<{
|
||||||
listSessions(),
|
text?: string | null;
|
||||||
getActiveSessionId(),
|
rich?: RichSource;
|
||||||
]);
|
}> => {
|
||||||
|
if (props.initialSource === "selection") {
|
||||||
|
const selected = await getSelectedTextSafely();
|
||||||
|
let html: string | undefined;
|
||||||
|
if (selected) {
|
||||||
|
for (const delay of [0, 150, 300]) {
|
||||||
|
if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
|
||||||
|
html = await readRichClipboardHtml();
|
||||||
|
if (html) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
text: selected,
|
||||||
|
rich: selected && html ? { text: selected, html } : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (props.initialSource === "clipboard") {
|
||||||
|
const clipboard = await Clipboard.read();
|
||||||
|
const html = clipboard.html ?? await readRichClipboardHtml();
|
||||||
|
return {
|
||||||
|
text: clipboard.text,
|
||||||
|
rich: html && clipboard.text ? { text: clipboard.text, html } : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
})();
|
||||||
|
const [loadedSessions, activeId, savedRuns, selected] = await Promise.all(
|
||||||
|
[listSessions(), getActiveSessionId(), listAllRuns(), initialText],
|
||||||
|
);
|
||||||
setSessions(loadedSessions);
|
setSessions(loadedSessions);
|
||||||
setActiveSessionId(activeId);
|
setActiveSessionId(activeId);
|
||||||
|
const unique = new Map<string, string>();
|
||||||
|
for (const { run } of savedRuns) {
|
||||||
|
const path = canonicalProjectPath(run.projectPath);
|
||||||
|
if (!unique.has(path)) unique.set(path, run.projectName);
|
||||||
|
}
|
||||||
|
setProjects([...unique].map(([path, name]) => ({ path, name })));
|
||||||
|
if (selected.text) {
|
||||||
|
setText(selected.text);
|
||||||
|
setRichSource(selected.rich);
|
||||||
|
} else if (props.initialSource)
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title:
|
||||||
|
props.initialSource === "selection"
|
||||||
|
? "Kein markierter Text gefunden"
|
||||||
|
: "Zwischenablage enthält keinen Text",
|
||||||
|
});
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
load();
|
load().catch(async (error: Error) => {
|
||||||
|
setIsLoading(false);
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title: "Zuordnungen nicht lesbar",
|
||||||
|
message: error.message,
|
||||||
|
});
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadClipboardText() {
|
async function loadClipboardText() {
|
||||||
const clipboardText = await Clipboard.readText();
|
const clipboard = await Clipboard.read();
|
||||||
|
const clipboardText = clipboard.text;
|
||||||
if (!clipboardText) {
|
if (!clipboardText) {
|
||||||
await showToast({
|
await showToast({
|
||||||
style: Toast.Style.Failure,
|
style: Toast.Style.Failure,
|
||||||
@@ -55,23 +124,24 @@ export default function Command() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setText(clipboardText);
|
setText(clipboardText);
|
||||||
|
const html = clipboard.html ?? await readRichClipboardHtml();
|
||||||
|
setRichSource(
|
||||||
|
html
|
||||||
|
? { text: clipboardText, html }
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleSubmit(values: FormValues) {
|
async function handleSubmit(values: FormValues) {
|
||||||
const input = values.text.trim();
|
const input = values.text;
|
||||||
if (!input || !values.sessionId) {
|
if (
|
||||||
|
!input.trim() ||
|
||||||
|
!values.sessionId ||
|
||||||
|
values.sessionId === CHOOSE_TARGET
|
||||||
|
) {
|
||||||
await showToast({
|
await showToast({
|
||||||
style: Toast.Style.Failure,
|
style: Toast.Style.Failure,
|
||||||
title: "Sitzung wählen und Text eingeben",
|
title: "Projekt oder Sitzung wählen und Text eingeben",
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = await getSession(values.sessionId);
|
|
||||||
if (!session) {
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Failure,
|
|
||||||
title: "Sitzung nicht gefunden",
|
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -81,11 +151,86 @@ export default function Command() {
|
|||||||
title: "Stelle wieder her…",
|
title: "Stelle wieder her…",
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
const result = await depseudonymize(input, session.mapping);
|
let result: DepseudonymizeResponse;
|
||||||
|
let richHtml: string | undefined;
|
||||||
|
let targetName: string;
|
||||||
|
let targetSubtitle: string;
|
||||||
|
if (values.sessionId.startsWith("project:")) {
|
||||||
|
const projectPath = values.sessionId.slice("project:".length);
|
||||||
|
const saved = (await listRuns(projectPath))[0];
|
||||||
|
if (!saved) throw new Error("Projektstand nicht gefunden.");
|
||||||
|
const restorationMapping = mappingForRestoration(saved.run.mapping);
|
||||||
|
const restored = restoreTextWithCount(
|
||||||
|
input,
|
||||||
|
restorationMapping,
|
||||||
|
saved.run.matchModes,
|
||||||
|
);
|
||||||
|
result = {
|
||||||
|
original_text: restored.text,
|
||||||
|
replacements_made: restored.replacements,
|
||||||
|
};
|
||||||
|
if (richSource?.text === input) {
|
||||||
|
richHtml = restoreRichHtml(
|
||||||
|
richSource.html,
|
||||||
|
input,
|
||||||
|
result.original_text,
|
||||||
|
restorationMapping,
|
||||||
|
saved.run.matchModes,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
targetName = `Projekt ${saved.run.projectName}`;
|
||||||
|
targetSubtitle = saved.run.projectPath;
|
||||||
|
} else {
|
||||||
|
const session = await getSession(values.sessionId);
|
||||||
|
if (!session) throw new Error("Sitzung nicht gefunden.");
|
||||||
|
const restorationMapping = mappingForRestoration(session.mapping);
|
||||||
|
result = await depseudonymize(input, restorationMapping);
|
||||||
|
if (richSource?.text === input) {
|
||||||
|
richHtml = restoreRichHtml(
|
||||||
|
richSource.html,
|
||||||
|
input,
|
||||||
|
result.original_text,
|
||||||
|
restorationMapping,
|
||||||
|
undefined,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
targetName = session.name;
|
||||||
|
targetSubtitle = sessionSubtitle(session);
|
||||||
|
}
|
||||||
|
const preview = <DepseudonymizeResult
|
||||||
|
result={result}
|
||||||
|
targetName={targetName}
|
||||||
|
targetSubtitle={targetSubtitle}
|
||||||
|
richHtml={richHtml}
|
||||||
|
showFormatStatus={Boolean(props.initialSource || richSource)}
|
||||||
|
formatUnavailableReason={!richHtml && richSource?.text === input
|
||||||
|
? "Die Formatierung der Auswahl konnte nicht eindeutig mit dem wiederhergestellten Text abgeglichen werden."
|
||||||
|
: "Die Quellanwendung hat für diese Auswahl keine HTML- oder RTF-Formatierung bereitgestellt."}
|
||||||
|
/>;
|
||||||
|
if (props.autoPaste) {
|
||||||
|
if (!result.replacements_made) throw new Error("Keine passenden Platzhalter gefunden. Bitte Projekt oder Sitzung prüfen.");
|
||||||
|
try {
|
||||||
|
if (richHtml) await pasteRichText(richHtml, result.original_text);
|
||||||
|
else await Clipboard.paste(result.original_text);
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = "Wiederhergestellt und eingefügt";
|
||||||
|
toast.message = `${result.replacements_made} Ersetzungen`;
|
||||||
|
await showHUD(richHtml ? "Wiederhergestellten Text formatiert eingefügt"
|
||||||
|
: "Wiederhergestellten Text eingefügt").catch(() => undefined);
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Einfügen fehlgeschlagen";
|
||||||
|
toast.message = `${error instanceof Error ? error.message : String(error)} · Das Ergebnis bleibt zum manuellen Einfügen geöffnet.`;
|
||||||
|
push(preview);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Wiederhergestellt";
|
toast.title = "Wiederhergestellt";
|
||||||
toast.message = `${result.replacements_made} Ersetzungen`;
|
toast.message = `${result.replacements_made} Ersetzungen`;
|
||||||
push(<DepseudonymizeResult result={result} session={session} />);
|
push(preview);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Wiederherstellung fehlgeschlagen";
|
toast.title = "Wiederherstellung fehlgeschlagen";
|
||||||
@@ -120,9 +265,23 @@ export default function Command() {
|
|||||||
/>
|
/>
|
||||||
<Form.Dropdown
|
<Form.Dropdown
|
||||||
id="sessionId"
|
id="sessionId"
|
||||||
title="Sitzung"
|
title="Projekt oder Sitzung"
|
||||||
defaultValue={defaultSessionId}
|
value={targetId}
|
||||||
|
onChange={setTargetId}
|
||||||
>
|
>
|
||||||
|
<Form.Dropdown.Item
|
||||||
|
value={CHOOSE_TARGET}
|
||||||
|
title="Bitte Projekt oder Sitzung wählen"
|
||||||
|
icon={Icon.Circle}
|
||||||
|
/>
|
||||||
|
{projects.map((project) => (
|
||||||
|
<Form.Dropdown.Item
|
||||||
|
key={project.path}
|
||||||
|
value={`project:${project.path}`}
|
||||||
|
title={`Projekt: ${project.name} · ${project.path}`}
|
||||||
|
icon={Icon.Folder}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
{sessions.map((session) => (
|
{sessions.map((session) => (
|
||||||
<Form.Dropdown.Item
|
<Form.Dropdown.Item
|
||||||
key={session.id}
|
key={session.id}
|
||||||
@@ -140,19 +299,32 @@ export default function Command() {
|
|||||||
|
|
||||||
function DepseudonymizeResult({
|
function DepseudonymizeResult({
|
||||||
result,
|
result,
|
||||||
session,
|
targetName,
|
||||||
|
targetSubtitle,
|
||||||
|
richHtml,
|
||||||
|
showFormatStatus,
|
||||||
|
formatUnavailableReason,
|
||||||
}: {
|
}: {
|
||||||
result: DepseudonymizeResponse;
|
result: DepseudonymizeResponse;
|
||||||
session: VelumSession;
|
targetName: string;
|
||||||
|
targetSubtitle: string;
|
||||||
|
richHtml?: string;
|
||||||
|
showFormatStatus: boolean;
|
||||||
|
formatUnavailableReason: string;
|
||||||
}) {
|
}) {
|
||||||
const markdown = [
|
const markdown = [
|
||||||
`# ${session.name}`,
|
`# ${targetName}`,
|
||||||
sessionSubtitle(session),
|
targetSubtitle,
|
||||||
"",
|
"",
|
||||||
"## Wiederhergestellter Text",
|
"## Wiederhergestellter Text",
|
||||||
markdownCodeBlock(result.original_text),
|
markdownCodeBlock(result.original_text),
|
||||||
"",
|
"",
|
||||||
`Ersetzungen: ${result.replacements_made}`,
|
`Ersetzungen: ${result.replacements_made}`,
|
||||||
|
richHtml
|
||||||
|
? "Formatierung kann beim Kopieren oder Einfügen übernommen werden."
|
||||||
|
: showFormatStatus
|
||||||
|
? `${formatUnavailableReason} Klartext kann weiterhin kopiert werden.`
|
||||||
|
: "",
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -160,12 +332,51 @@ function DepseudonymizeResult({
|
|||||||
markdown={markdown}
|
markdown={markdown}
|
||||||
actions={
|
actions={
|
||||||
<ActionPanel>
|
<ActionPanel>
|
||||||
|
{richHtml && (
|
||||||
|
<>
|
||||||
|
<Action
|
||||||
|
title="Mit Formatierung kopieren"
|
||||||
|
icon={Icon.Clipboard}
|
||||||
|
onAction={async () => {
|
||||||
|
try {
|
||||||
|
await copyRichText(richHtml, result.original_text);
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Success,
|
||||||
|
title: "Mit Formatierung kopiert",
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title: "Formatierter Text konnte nicht kopiert werden",
|
||||||
|
message:
|
||||||
|
error instanceof Error ? error.message : String(error),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Action
|
||||||
|
title="Mit Formatierung einfügen"
|
||||||
|
icon={Icon.TextCursor}
|
||||||
|
onAction={async () => {
|
||||||
|
try {
|
||||||
|
await pasteRichText(richHtml, result.original_text);
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title: "Formatierter Text konnte nicht eingefügt werden",
|
||||||
|
message: `${error instanceof Error ? error.message : String(error)} · Der Text liegt formatiert in der Zwischenablage.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<Action.CopyToClipboard
|
<Action.CopyToClipboard
|
||||||
title="Wiederhergestellten Text kopieren"
|
title="Als Klartext kopieren"
|
||||||
content={result.original_text}
|
content={result.original_text}
|
||||||
/>
|
/>
|
||||||
<Action
|
<Action
|
||||||
title="Wiederhergestellten Text einfügen"
|
title="Als Klartext einfügen"
|
||||||
icon={Icon.TextCursor}
|
icon={Icon.TextCursor}
|
||||||
onAction={() => Clipboard.paste(result.original_text)}
|
onAction={() => Clipboard.paste(result.original_text)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
Toast,
|
Toast,
|
||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import {
|
||||||
type Creativity,
|
type Creativity,
|
||||||
CREATIVITY_OPTIONS,
|
CREATIVITY_OPTIONS,
|
||||||
@@ -20,20 +20,16 @@ import {
|
|||||||
} from "./ai";
|
} from "./ai";
|
||||||
import { PseudonymizationConfirm } from "./ai-views";
|
import { PseudonymizationConfirm } from "./ai-views";
|
||||||
import { getSelectedTextSafely } from "./selection";
|
import { getSelectedTextSafely } from "./selection";
|
||||||
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
import {
|
import {
|
||||||
createSession,
|
|
||||||
getActiveSessionId,
|
getActiveSessionId,
|
||||||
getSession,
|
|
||||||
listSessions,
|
listSessions,
|
||||||
setActiveSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
} from "./sessions";
|
||||||
import type { EntityType, VelumSession } from "./types";
|
import type { EntityType, VelumSession } from "./types";
|
||||||
import { NEW_SESSION_ID } from "./ui";
|
|
||||||
import {
|
import {
|
||||||
getEntityTypes,
|
getEntityTypes,
|
||||||
normalizePseudonymizeResponse,
|
|
||||||
pseudonymize,
|
|
||||||
} from "./velum";
|
} from "./velum";
|
||||||
|
|
||||||
function buildActionItemsPrompt(
|
function buildActionItemsPrompt(
|
||||||
@@ -72,9 +68,8 @@ function buildActionItemsPrompt(
|
|||||||
].join("\n");
|
].join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = ContextFormValues & {
|
||||||
text: string;
|
text: string;
|
||||||
sessionId: string;
|
|
||||||
entityTypes: string[];
|
entityTypes: string[];
|
||||||
model: string;
|
model: string;
|
||||||
creativity: Creativity;
|
creativity: Creativity;
|
||||||
@@ -86,6 +81,7 @@ export default function Command() {
|
|||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@@ -109,8 +105,9 @@ export default function Command() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const loadedEntityTypes = await getEntityTypes();
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
setEntityTypes(loadedEntityTypes);
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
setSelectedEntityTypes(loadedEntityTypes);
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
} catch {
|
} catch {
|
||||||
setEntityTypes([]);
|
setEntityTypes([]);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -120,11 +117,6 @@ export default function Command() {
|
|||||||
load();
|
load();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadSelectedText() {
|
async function loadSelectedText() {
|
||||||
const selected = await getSelectedTextSafely();
|
const selected = await getSelectedTextSafely();
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@@ -167,45 +159,29 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const session =
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
values.sessionId === NEW_SESSION_ID
|
|
||||||
? await createSession()
|
|
||||||
: ((await getSession(values.sessionId)) ?? (await createSession()));
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
|
|
||||||
const rawResult = await pseudonymize(
|
|
||||||
input,
|
|
||||||
session.mapping,
|
|
||||||
values.entityTypes,
|
|
||||||
);
|
|
||||||
const pseudoResult = normalizePseudonymizeResponse(rawResult);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
pseudoResult.mapping,
|
|
||||||
pseudoResult.selected_entity_types,
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Pseudonymisiert";
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
toast.message = `${pseudoResult.entity_count} Zuordnungen`;
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
|
||||||
push(
|
push(
|
||||||
<PseudonymizationConfirm
|
<PseudonymizationConfirm
|
||||||
session={updatedSession}
|
session={updatedSession}
|
||||||
pseudonymizedText={pseudoResult.pseudonymized_text}
|
pseudonymizedText={pseudoResult.pseudonymized_text}
|
||||||
model={values.model}
|
model={values.model}
|
||||||
creativity={values.creativity}
|
creativity={values.creativity}
|
||||||
instructions={values.instructions}
|
instructions={values.instructions}
|
||||||
buildPrompt={buildActionItemsPrompt}
|
buildPrompt={buildActionItemsPrompt}
|
||||||
labels={{
|
labels={{
|
||||||
pageHeading: "Action Items",
|
pageHeading: "Action Items",
|
||||||
runningLabel: "KI extrahiert Action Items …",
|
runningLabel: "KI extrahiert Action Items …",
|
||||||
failureTitle: "Extraktion fehlgeschlagen",
|
failureTitle: "Extraktion fehlgeschlagen",
|
||||||
copyTitle: "Action Items kopieren",
|
copyTitle: "Action Items kopieren",
|
||||||
pasteTitle: "Action Items einfügen",
|
pasteTitle: "Action Items einfügen",
|
||||||
}}
|
}}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
}} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
@@ -243,27 +219,9 @@ export default function Command() {
|
|||||||
onChange={setText}
|
onChange={setText}
|
||||||
placeholder="Meeting-Notizen, Email-Thread, Transkript …"
|
placeholder="Meeting-Notizen, Email-Thread, Transkript …"
|
||||||
/>
|
/>
|
||||||
<Form.Dropdown
|
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||||
id="sessionId"
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
title="Sitzung"
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
defaultValue={defaultSessionId}
|
|
||||||
>
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
value={NEW_SESSION_ID}
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
key={session.id}
|
|
||||||
value={session.id}
|
|
||||||
title={session.name}
|
|
||||||
icon={
|
|
||||||
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Form.Dropdown>
|
|
||||||
{entityTypes.length > 0 ? (
|
{entityTypes.length > 0 ? (
|
||||||
<Form.TagPicker
|
<Form.TagPicker
|
||||||
id="entityTypes"
|
id="entityTypes"
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
Toast,
|
Toast,
|
||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import {
|
||||||
type Creativity,
|
type Creativity,
|
||||||
CREATIVITY_OPTIONS,
|
CREATIVITY_OPTIONS,
|
||||||
@@ -20,20 +20,16 @@ import {
|
|||||||
} from "./ai";
|
} from "./ai";
|
||||||
import { PseudonymizationConfirm } from "./ai-views";
|
import { PseudonymizationConfirm } from "./ai-views";
|
||||||
import { getSelectedTextSafely } from "./selection";
|
import { getSelectedTextSafely } from "./selection";
|
||||||
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
import {
|
import {
|
||||||
createSession,
|
|
||||||
getActiveSessionId,
|
getActiveSessionId,
|
||||||
getSession,
|
|
||||||
listSessions,
|
listSessions,
|
||||||
setActiveSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
} from "./sessions";
|
||||||
import type { EntityType, VelumSession } from "./types";
|
import type { EntityType, VelumSession } from "./types";
|
||||||
import { NEW_SESSION_ID } from "./ui";
|
|
||||||
import {
|
import {
|
||||||
getEntityTypes,
|
getEntityTypes,
|
||||||
normalizePseudonymizeResponse,
|
|
||||||
pseudonymize,
|
|
||||||
} from "./velum";
|
} from "./velum";
|
||||||
|
|
||||||
type OutputFormat = "json" | "markdown-table";
|
type OutputFormat = "json" | "markdown-table";
|
||||||
@@ -91,11 +87,10 @@ function buildStructuredDataPrompt(args: {
|
|||||||
].join("\n");
|
].join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = ContextFormValues & {
|
||||||
text: string;
|
text: string;
|
||||||
schema: string;
|
schema: string;
|
||||||
format: OutputFormat;
|
format: OutputFormat;
|
||||||
sessionId: string;
|
|
||||||
entityTypes: string[];
|
entityTypes: string[];
|
||||||
model: string;
|
model: string;
|
||||||
creativity: Creativity;
|
creativity: Creativity;
|
||||||
@@ -107,6 +102,7 @@ export default function Command() {
|
|||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@@ -130,8 +126,9 @@ export default function Command() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const loadedEntityTypes = await getEntityTypes();
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
setEntityTypes(loadedEntityTypes);
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
setSelectedEntityTypes(loadedEntityTypes);
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
} catch {
|
} catch {
|
||||||
setEntityTypes([]);
|
setEntityTypes([]);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -141,11 +138,6 @@ export default function Command() {
|
|||||||
load();
|
load();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadSelectedText() {
|
async function loadSelectedText() {
|
||||||
const selected = await getSelectedTextSafely();
|
const selected = await getSelectedTextSafely();
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@@ -195,61 +187,45 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const session =
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
values.sessionId === NEW_SESSION_ID
|
|
||||||
? await createSession()
|
|
||||||
: ((await getSession(values.sessionId)) ?? (await createSession()));
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
|
|
||||||
const rawResult = await pseudonymize(
|
|
||||||
input,
|
|
||||||
session.mapping,
|
|
||||||
values.entityTypes,
|
|
||||||
);
|
|
||||||
const pseudoResult = normalizePseudonymizeResponse(rawResult);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
pseudoResult.mapping,
|
|
||||||
pseudoResult.selected_entity_types,
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Pseudonymisiert";
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
toast.message = `${pseudoResult.entity_count} Zuordnungen`;
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
|
||||||
|
const schema = values.schema;
|
||||||
|
const format = values.format;
|
||||||
|
const buildPrompt = (pseudonymizedText: string, instructions: string) =>
|
||||||
|
buildStructuredDataPrompt({
|
||||||
|
pseudonymizedText,
|
||||||
|
instructions,
|
||||||
|
schema,
|
||||||
|
format,
|
||||||
|
});
|
||||||
|
|
||||||
const schema = values.schema;
|
push(
|
||||||
const format = values.format;
|
<PseudonymizationConfirm
|
||||||
const buildPrompt = (pseudonymizedText: string, instructions: string) =>
|
session={updatedSession}
|
||||||
buildStructuredDataPrompt({
|
pseudonymizedText={pseudoResult.pseudonymized_text}
|
||||||
pseudonymizedText,
|
model={values.model}
|
||||||
instructions,
|
creativity={values.creativity}
|
||||||
schema,
|
instructions={values.instructions}
|
||||||
format,
|
buildPrompt={buildPrompt}
|
||||||
});
|
labels={{
|
||||||
|
pageHeading:
|
||||||
push(
|
format === "json" ? "Strukturierte Daten (JSON)" : "Tabelle",
|
||||||
<PseudonymizationConfirm
|
runningLabel:
|
||||||
session={updatedSession}
|
format === "json"
|
||||||
pseudonymizedText={pseudoResult.pseudonymized_text}
|
? "KI extrahiert Daten (JSON) …"
|
||||||
model={values.model}
|
: "KI extrahiert Tabelle …",
|
||||||
creativity={values.creativity}
|
failureTitle: "Extraktion fehlgeschlagen",
|
||||||
instructions={values.instructions}
|
copyTitle:
|
||||||
buildPrompt={buildPrompt}
|
format === "json" ? "JSON kopieren" : "Markdown-Tabelle kopieren",
|
||||||
labels={{
|
pasteTitle:
|
||||||
pageHeading:
|
format === "json" ? "JSON einfügen" : "Tabelle einfügen",
|
||||||
format === "json" ? "Strukturierte Daten (JSON)" : "Tabelle",
|
}}
|
||||||
runningLabel:
|
/>,
|
||||||
format === "json"
|
);
|
||||||
? "KI extrahiert Daten (JSON) …"
|
}} />);
|
||||||
: "KI extrahiert Tabelle …",
|
|
||||||
failureTitle: "Extraktion fehlgeschlagen",
|
|
||||||
copyTitle:
|
|
||||||
format === "json" ? "JSON kopieren" : "Markdown-Tabelle kopieren",
|
|
||||||
pasteTitle:
|
|
||||||
format === "json" ? "JSON einfügen" : "Tabelle einfügen",
|
|
||||||
}}
|
|
||||||
/>,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
@@ -303,27 +279,9 @@ export default function Command() {
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Form.Dropdown>
|
</Form.Dropdown>
|
||||||
<Form.Dropdown
|
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||||
id="sessionId"
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
title="Sitzung"
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
defaultValue={defaultSessionId}
|
|
||||||
>
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
value={NEW_SESSION_ID}
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
key={session.id}
|
|
||||||
value={session.id}
|
|
||||||
title={session.name}
|
|
||||||
icon={
|
|
||||||
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Form.Dropdown>
|
|
||||||
{entityTypes.length > 0 ? (
|
{entityTypes.length > 0 ? (
|
||||||
<Form.TagPicker
|
<Form.TagPicker
|
||||||
id="entityTypes"
|
id="entityTypes"
|
||||||
|
|||||||
22
src/lib/entity-types.ts
Normal file
22
src/lib/entity-types.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import type { EntityType } from "../types";
|
||||||
|
|
||||||
|
/** Fallback for Velum backends that do not report `default_entity_types` yet. */
|
||||||
|
export const DEFAULT_DISABLED_ENTITY_TYPES: readonly EntityType[] = [
|
||||||
|
"IP",
|
||||||
|
"DATUM",
|
||||||
|
"REFERENZ",
|
||||||
|
];
|
||||||
|
|
||||||
|
export type EntityTypeCatalog = { all: EntityType[]; defaults: EntityType[] };
|
||||||
|
|
||||||
|
/** Preselection for unconfigured contexts; the backend default wins when it is available. */
|
||||||
|
export function entityTypeCatalog(payload: {
|
||||||
|
entity_types: EntityType[];
|
||||||
|
default_entity_types?: EntityType[];
|
||||||
|
}): EntityTypeCatalog {
|
||||||
|
const all = payload.entity_types;
|
||||||
|
const defaults = payload.default_entity_types
|
||||||
|
? payload.default_entity_types.filter((type) => all.includes(type))
|
||||||
|
: all.filter((type) => !DEFAULT_DISABLED_ENTITY_TYPES.includes(type));
|
||||||
|
return { all, defaults };
|
||||||
|
}
|
||||||
57
src/lib/image-policy.ts
Normal file
57
src/lib/image-policy.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
export type ImagePolicy = "placeholder" | "remove" | "keep";
|
||||||
|
export type DocumentImageReport = {
|
||||||
|
image_policy: ImagePolicy;
|
||||||
|
images_replaced: number;
|
||||||
|
images_removed: number;
|
||||||
|
media_parts_removed: number;
|
||||||
|
warnings: string[];
|
||||||
|
};
|
||||||
|
export const DEFAULT_IMAGE_POLICY: ImagePolicy = "placeholder";
|
||||||
|
export const IMAGE_POLICY_LABELS: Record<ImagePolicy, string> = {
|
||||||
|
placeholder: "Datenschutz-Platzhalter (Standard)",
|
||||||
|
remove: "Bilder vollständig entfernen",
|
||||||
|
keep: "Bilder behalten — Datenschutzrisiko",
|
||||||
|
};
|
||||||
|
export const KEEP_IMAGE_WARNING = "Achtung: Bilder können sensible Informationen enthalten. Sie werden unverändert übernommen und nicht auf personenbezogene Daten geprüft.";
|
||||||
|
|
||||||
|
export function checkedImagePolicy(policy: string): ImagePolicy {
|
||||||
|
if (policy !== "placeholder" && policy !== "remove" && policy !== "keep") {
|
||||||
|
throw new Error("Ungültige Bildbehandlung.");
|
||||||
|
}
|
||||||
|
return policy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sameImagePolicyCoverage(previous: { imagePolicy?: ImagePolicy } | undefined, policy: ImagePolicy): boolean {
|
||||||
|
return previous?.imagePolicy === policy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function checkedImageReport(value: unknown, policy: ImagePolicy): DocumentImageReport {
|
||||||
|
const report = value as Partial<DocumentImageReport> | null;
|
||||||
|
if (!report || report.image_policy !== policy) {
|
||||||
|
throw new Error("Die Velum-API bestätigt die gewählte Bildbehandlung nicht. Bitte das Backend aktualisieren.");
|
||||||
|
}
|
||||||
|
for (const count of [report.images_replaced, report.images_removed, report.media_parts_removed]) {
|
||||||
|
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) {
|
||||||
|
throw new Error("Die Velum-API liefert keine gültigen Bildzähler.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Array.isArray(report.warnings) || report.warnings.some((warning) => typeof warning !== "string")) {
|
||||||
|
throw new Error("Die Velum-API liefert keine gültigen Bildwarnungen.");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
image_policy: policy,
|
||||||
|
images_replaced: report.images_replaced!, images_removed: report.images_removed!,
|
||||||
|
media_parts_removed: report.media_parts_removed!,
|
||||||
|
warnings: policy === "keep" && !report.warnings.includes(KEEP_IMAGE_WARNING) ? [KEEP_IMAGE_WARNING, ...report.warnings] : [...report.warnings],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function summarizeImages(files: readonly { imageReport?: DocumentImageReport }[]): {
|
||||||
|
replaced: number; removed: number; warnings: string[];
|
||||||
|
} {
|
||||||
|
return {
|
||||||
|
replaced: files.reduce((total, file) => total + (file.imageReport?.images_replaced ?? 0), 0),
|
||||||
|
removed: files.reduce((total, file) => total + (file.imageReport?.images_removed ?? 0), 0),
|
||||||
|
warnings: [...new Set(files.flatMap((file) => file.imageReport?.warnings ?? []))],
|
||||||
|
};
|
||||||
|
}
|
||||||
140
src/lib/local-docx.ts
Normal file
140
src/lib/local-docx.ts
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
import { execFile } from "node:child_process";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { constants, promises as fs } from "node:fs";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { delimiter, dirname, join } from "node:path";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
import { analyzeDocxSegments } from "../velum";
|
||||||
|
import type { EntityType, PlaceholderMapping } from "../types";
|
||||||
|
import { checkedImageReport } from "./image-policy";
|
||||||
|
import type { ImagePolicy } from "./image-policy";
|
||||||
|
import { propagateDocxPersons } from "./person-propagation";
|
||||||
|
import { MAX_BATCH_CODEPOINTS } from "./project-review";
|
||||||
|
import { projectTextAnalyzer } from "./project-text-mapping";
|
||||||
|
import type { Hit } from "./project-work";
|
||||||
|
|
||||||
|
type Segment = { text: string; source: string; kind: "text" | "author" | "link" | "email" };
|
||||||
|
const exec = promisify(execFile);
|
||||||
|
|
||||||
|
async function docxCodec(assets: string, args: string[]): Promise<unknown> {
|
||||||
|
const paths = [
|
||||||
|
...(process.env.PATH ?? "").split(delimiter).filter(Boolean),
|
||||||
|
"/opt/homebrew/bin", "/usr/local/bin", join(homedir(), ".local/bin"),
|
||||||
|
];
|
||||||
|
let uv: string | undefined;
|
||||||
|
for (const directory of new Set(paths)) {
|
||||||
|
const candidate = join(directory, "uv");
|
||||||
|
try {
|
||||||
|
await fs.access(candidate, constants.X_OK);
|
||||||
|
uv = candidate;
|
||||||
|
break;
|
||||||
|
} catch { /* check the next executable directory */ }
|
||||||
|
}
|
||||||
|
if (!uv) throw new Error("Für lokale DOCX-Aufträge wird uv benötigt. Bitte uv installieren und Raycast erneut öffnen.");
|
||||||
|
try {
|
||||||
|
const { stdout } = await exec(uv, [
|
||||||
|
"run", "--no-project", "--isolated", "--with", "lxml==6.2.1",
|
||||||
|
"--python", "3.11", "python", "-m", "velum.docx_local", ...args,
|
||||||
|
], { cwd: join(assets, "velum-docx"), maxBuffer: 192 * 1024 * 1024, env: { ...process.env, PYTHONUTF8: "1" } });
|
||||||
|
return JSON.parse(stdout);
|
||||||
|
} catch (error) {
|
||||||
|
const stderr = (error as { stderr?: string }).stderr?.trim();
|
||||||
|
throw new Error(stderr || "Lokaler DOCX-Schritt fehlgeschlagen.", { cause: error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function inspectDocx(
|
||||||
|
assets: string, path: string, relative: string, hash: string, policy: ImagePolicy,
|
||||||
|
mapping: PlaceholderMapping, types: EntityType[], masks: Record<string, string[]>,
|
||||||
|
progress: (message: string) => void,
|
||||||
|
): Promise<{ hits: Hit[]; mapping: PlaceholderMapping; segmentCount: number }> {
|
||||||
|
const segments = await docxCodec(assets, ["extract", path, policy, hash]) as Segment[];
|
||||||
|
const hits: Hit[] = [];
|
||||||
|
let batch: Segment[] = [];
|
||||||
|
let offset = 0;
|
||||||
|
let size = 0;
|
||||||
|
let part = 0;
|
||||||
|
let current = mapping;
|
||||||
|
const analyze = projectTextAnalyzer(mapping, async (_text, window) => {
|
||||||
|
const response = await analyzeDocxSegments(batch.map(({ text, kind }) => ({ text, kind })), window, types, masks);
|
||||||
|
if (response.spans.length !== batch.length) throw new Error("Velum liefert eine ungültige Zahl von DOCX-Segmenten.");
|
||||||
|
let start = 0;
|
||||||
|
const spans = response.spans.flatMap((matches, index) => {
|
||||||
|
const segment = Array.from(batch[index].text);
|
||||||
|
const result = matches.map((span) => {
|
||||||
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|
||||||
|
|| span.start < 0 || span.start >= span.end || span.end > segment.length) {
|
||||||
|
throw new Error("Ungültige Trefferposition der Velum-DOCX-API.");
|
||||||
|
}
|
||||||
|
return { ...span, start: start + span.start, end: start + span.end };
|
||||||
|
});
|
||||||
|
start += segment.length + 2;
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
return { spans, mapping: response.mapping, selected_entity_types: types, pseudonymized_text: "", entity_count: 0 };
|
||||||
|
});
|
||||||
|
async function flush() {
|
||||||
|
if (batch.length === 0) return;
|
||||||
|
progress(`DOCX analysieren: ${relative} · Paket ${++part}`);
|
||||||
|
const text = batch.map((segment) => segment.text).join("\n\n");
|
||||||
|
const analyzed = await analyze(text, current, types, masks);
|
||||||
|
current = analyzed.mapping;
|
||||||
|
let start = 0;
|
||||||
|
let hit = 0;
|
||||||
|
const ordered = [...analyzed.spans].sort((a, b) => a.start - b.start);
|
||||||
|
for (const [index, segment] of batch.entries()) {
|
||||||
|
const characters = Array.from(segment.text);
|
||||||
|
const segmentIndex = offset + index;
|
||||||
|
while (hit < ordered.length && ordered[hit].start < start + characters.length) {
|
||||||
|
const span = ordered[hit++];
|
||||||
|
const begin = span.start - start;
|
||||||
|
const end = span.end - start;
|
||||||
|
if (begin < 0 || end > characters.length) throw new Error("DOCX-Treffer überschreitet sein Segment.");
|
||||||
|
const snippetStart = Math.max(0, begin - 60);
|
||||||
|
hits.push({ ...span, start: begin, end, segment: segmentIndex,
|
||||||
|
id: `${relative}:local-docx:${segmentIndex}:${begin}:${end}`, file: relative, source: segment.source,
|
||||||
|
context: characters.slice(snippetStart, end + 60).join(""),
|
||||||
|
contextOffset: characters.slice(snippetStart, begin).join("").length, kind: "content" });
|
||||||
|
}
|
||||||
|
start += characters.length + 2;
|
||||||
|
}
|
||||||
|
if (hit !== ordered.length) throw new Error("DOCX-Treffer konnte keinem Segment zugeordnet werden.");
|
||||||
|
offset += batch.length;
|
||||||
|
batch = [];
|
||||||
|
size = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const segment of segments) {
|
||||||
|
if (segment.text.length > 250_000) throw new Error("Ein einzelnes DOCX-Textfeld überschreitet 250.000 Zeichen.");
|
||||||
|
if (batch.length && (size + segment.text.length + 2 > MAX_BATCH_CODEPOINTS || batch.length === 256)) await flush();
|
||||||
|
batch.push(segment);
|
||||||
|
size += segment.text.length + 2;
|
||||||
|
}
|
||||||
|
await flush();
|
||||||
|
const propagated = types.includes("PERSON") ? propagateDocxPersons(segments, hits, current, relative)
|
||||||
|
: { hits, mapping: current };
|
||||||
|
return { ...propagated, segmentCount: segments.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function writeDocx(
|
||||||
|
assets: string, path: string, target: string, hash: string, policy: ImagePolicy, segmentCount: number,
|
||||||
|
hits: Hit[], accepted: Set<string>,
|
||||||
|
) {
|
||||||
|
const replacements: Record<string, { start: number; end: number; original: string; placeholder: string }[]> = {};
|
||||||
|
for (const hit of hits) {
|
||||||
|
if (!accepted.has(hit.id)) continue;
|
||||||
|
if (!Number.isSafeInteger(hit.segment) || hit.segment! < 0 || hit.segment! >= segmentCount) {
|
||||||
|
throw new Error("DOCX-Treffer hat kein gültiges Segment.");
|
||||||
|
}
|
||||||
|
const { start, end, original, placeholder } = hit;
|
||||||
|
(replacements[hit.segment!] ??= []).push({ start, end, original, placeholder });
|
||||||
|
}
|
||||||
|
for (const spans of Object.values(replacements)) spans.sort((a, b) => a.start - b.start);
|
||||||
|
const instructions = join(dirname(target), ".velum-replacements-" + randomUUID());
|
||||||
|
await fs.writeFile(instructions, JSON.stringify({ replacements, segmentCount }), { flag: "wx", mode: 0o600 });
|
||||||
|
try {
|
||||||
|
return checkedImageReport(await docxCodec(assets, ["apply", path, policy, hash, instructions, target]), policy);
|
||||||
|
} finally {
|
||||||
|
await fs.rm(instructions, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/lib/mapping-created-at.ts
Normal file
34
src/lib/mapping-created-at.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import type { ProjectRun } from "./velum-project";
|
||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
|
||||||
|
/** Project snapshots are immutable: the first snapshot containing a matching entry dates its first Velum record. */
|
||||||
|
export function projectMappingCreatedAt(runs: ProjectRun[], current: PlaceholderMapping): Record<string, string> {
|
||||||
|
const createdAt: Record<string, string> = {};
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const run of [...runs].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))) {
|
||||||
|
for (const [key, entry] of Object.entries(run.mapping)) {
|
||||||
|
const active = current[key];
|
||||||
|
if (active && active.type === entry.type && active.original === entry.original && !seen.has(key)) {
|
||||||
|
seen.add(key);
|
||||||
|
// An imported snapshot records the migration time, not when its terms were first created.
|
||||||
|
if (run.origin !== "imported" || run.revisedFrom) createdAt[key] = run.createdAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return createdAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dated entries lead; legacy entries fall back to descending IDs within each category. */
|
||||||
|
export function sortMappingRowsByCreatedAt<T extends { placeholder: string; type: string }>(
|
||||||
|
rows: T[], createdAt: Record<string, string>,
|
||||||
|
): T[] {
|
||||||
|
const timestamp = (key: string) => {
|
||||||
|
const value = Date.parse(createdAt[key] ?? "");
|
||||||
|
return Number.isFinite(value) ? value : Number.NEGATIVE_INFINITY;
|
||||||
|
};
|
||||||
|
const number = (key: string) => Number(/_(\d+)>?$/u.exec(key)?.[1] ?? -1);
|
||||||
|
return [...rows].sort((a, b) => timestamp(b.placeholder) - timestamp(a.placeholder)
|
||||||
|
|| a.type.localeCompare(b.type)
|
||||||
|
|| number(b.placeholder) - number(a.placeholder)
|
||||||
|
|| a.placeholder.localeCompare(b.placeholder));
|
||||||
|
}
|
||||||
60
src/lib/mapping-export.ts
Normal file
60
src/lib/mapping-export.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
import { mappingRoot } from "./mapping-groups";
|
||||||
|
|
||||||
|
export type MappingExportKind = "terms" | "replacements";
|
||||||
|
|
||||||
|
/** One record per line; literal backslashes and line breaks remain distinguishable. */
|
||||||
|
function singleLine(value: string): string {
|
||||||
|
return value.replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/\t/g, "\\t");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mappingExport(mapping: PlaceholderMapping, kind: MappingExportKind): { text: string; count: number } {
|
||||||
|
const compare = (left: string, right: string) => left.localeCompare(right, "de", { numeric: true });
|
||||||
|
if (kind === "terms") {
|
||||||
|
const terms = [...new Set(Object.values(mapping).map((entry) => entry.original))].sort(compare);
|
||||||
|
return { text: terms.map(singleLine).join("\n") + (terms.length ? "\n" : ""), count: terms.length };
|
||||||
|
}
|
||||||
|
if (kind !== "replacements") throw new Error("Unbekanntes Exportformat.");
|
||||||
|
const pairs = new Map<string, { original: string; replacement: string }>();
|
||||||
|
for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
const replacement = mappingRoot(key, mapping);
|
||||||
|
pairs.set(JSON.stringify([entry.original, replacement]), { original: entry.original, replacement });
|
||||||
|
}
|
||||||
|
const rows = [...pairs.values()].sort((left, right) => compare(left.original, right.original)
|
||||||
|
|| compare(left.replacement, right.replacement));
|
||||||
|
return {
|
||||||
|
text: rows.map(({ original, replacement }) => `${singleLine(original)} → ${singleLine(replacement)}`).join("\n") + (rows.length ? "\n" : ""),
|
||||||
|
count: rows.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Save a private, complete UTF-8 copy, without replacing earlier exports. */
|
||||||
|
export async function writeMappingExport(title: string, mapping: PlaceholderMapping, kind: MappingExportKind,
|
||||||
|
directory = join(homedir(), "Downloads", "Velum")): Promise<{ path: string; count: number }> {
|
||||||
|
const { text, count } = mappingExport(mapping, kind);
|
||||||
|
if (!count) throw new Error("Diese Übersetzungstabelle enthält noch keine Begriffe.");
|
||||||
|
const name = [...title.normalize("NFC").replace(/[^\p{L}\p{N}_. -]/gu, "-")].slice(0, 40).join("")
|
||||||
|
.replace(/^[.\s-]+|[.\s-]+$/g, "") || "Velum";
|
||||||
|
const suffix = kind === "terms" ? "begriffe" : "ersetzungen";
|
||||||
|
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
||||||
|
const temporary = await fs.mkdtemp(join(directory, ".velum-export-"));
|
||||||
|
try {
|
||||||
|
const file = join(temporary, "export.txt");
|
||||||
|
await fs.writeFile(file, text, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
||||||
|
for (let index = 0; index < 1000; index++) {
|
||||||
|
const path = join(directory, `${name}-${suffix}${index ? ` (${index + 1})` : ""}.txt`);
|
||||||
|
try {
|
||||||
|
await fs.link(file, path);
|
||||||
|
return { path, count };
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error("Zu viele gleichnamige Exportdateien. Bitte ältere Exporte umbenennen.");
|
||||||
|
} finally {
|
||||||
|
await fs.rm(temporary, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
46
src/lib/mapping-groups.ts
Normal file
46
src/lib/mapping-groups.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
|
||||||
|
export function mappingRoot(key: string, mapping: PlaceholderMapping): string {
|
||||||
|
const initial = mapping[key];
|
||||||
|
if (!initial) throw new Error(`Unbekannte Zuordnung: ${key}`);
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let current = key;
|
||||||
|
while (mapping[current].merged_into) {
|
||||||
|
if (seen.has(current)) throw new Error(`Zyklische Zuordnung: ${key}`);
|
||||||
|
seen.add(current);
|
||||||
|
const reference = mapping[current].merged_into!;
|
||||||
|
const target = mapping[reference] ? reference
|
||||||
|
: mapping[`<${reference.replace(/^<|>$/g, "")}>`] ? `<${reference.replace(/^<|>$/g, "")}>`
|
||||||
|
: reference.replace(/^<|>$/g, "");
|
||||||
|
if (!mapping[target] || mapping[target].type !== initial.type) {
|
||||||
|
throw new Error(`Ungültiger Hauptbegriff für ${key}: ${reference}`);
|
||||||
|
}
|
||||||
|
current = target;
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reverse lookups use the group's main term, while the saved variants remain intact. */
|
||||||
|
export function mappingForRestoration(mapping: PlaceholderMapping): PlaceholderMapping {
|
||||||
|
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key, {
|
||||||
|
type: entry.type,
|
||||||
|
original: mapping[mappingRoot(key, mapping)].original,
|
||||||
|
}]));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mergeMappingGroups(mapping: PlaceholderMapping, source: string, target: string): PlaceholderMapping {
|
||||||
|
const from = mappingRoot(source, mapping);
|
||||||
|
const into = mappingRoot(target, mapping);
|
||||||
|
if (from === into) throw new Error("Diese Zuordnungen sind bereits zusammengefasst.");
|
||||||
|
if (mapping[from].type !== mapping[into].type) {
|
||||||
|
throw new Error("Nur Zuordnungen derselben Kategorie können zusammengefasst werden.");
|
||||||
|
}
|
||||||
|
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key,
|
||||||
|
mappingRoot(key, mapping) === from ? { ...entry, merged_into: into } : { ...entry },
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detachMappingGroup(mapping: PlaceholderMapping, key: string): PlaceholderMapping {
|
||||||
|
if (!mapping[key]?.merged_into) throw new Error("Diese Zuordnung ist kein Verweis.");
|
||||||
|
return { ...mapping, [key]: { ...mapping[key], merged_into: undefined } };
|
||||||
|
}
|
||||||
107
src/lib/person-propagation.ts
Normal file
107
src/lib/person-propagation.ts
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
import type { Hit } from "./project-work";
|
||||||
|
|
||||||
|
// Seeds follow the backend's per-text person propagation: only confident
|
||||||
|
// PERSON hits that look like capitalized names. Unlike the backend, the parts of
|
||||||
|
// a detected full name are propagated even if the model never recognized them
|
||||||
|
// alone, because lone surnames are what it misses most in running text.
|
||||||
|
// Common words stay out of reach unless the model put them into a name.
|
||||||
|
const NAME = /^[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+(?:[ \t]+[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+)*$/u;
|
||||||
|
const MIN_SEED_SCORE = 0.85;
|
||||||
|
// The backend's salutation recognizer ("Frau Müller", "Dr. Schmidt") scores
|
||||||
|
// 0.7, but its structure reliably marks the following words as a name.
|
||||||
|
const SALUTATION = /^(?:Frau|Herr|Dr\.|Prof\.|Mag\.|Ing\.|DI)\s+/u;
|
||||||
|
const MIN_SALUTATION_SCORE = 0.7;
|
||||||
|
|
||||||
|
function escape(value: string): string {
|
||||||
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Velum analyzes every DOCX segment separately, so a name recognized in one
|
||||||
|
* paragraph is not propagated to paragraphs where the model misses it (for
|
||||||
|
* example "bei Quastenberg nachfragen"). Add those occurrences as reviewable
|
||||||
|
* hits for the whole file.
|
||||||
|
*/
|
||||||
|
export function propagateDocxPersons(
|
||||||
|
segments: Array<{ text: string; source: string; kind: string }>, hits: Hit[], mapping: PlaceholderMapping,
|
||||||
|
relative: string,
|
||||||
|
): { hits: Hit[]; mapping: PlaceholderMapping } {
|
||||||
|
const candidates = new Map<string, number>();
|
||||||
|
const add = (name: string, score: number) => candidates.set(name, Math.max(candidates.get(name) ?? 0, score));
|
||||||
|
for (const hit of hits) {
|
||||||
|
if (hit.kind !== "content" || hit.type !== "PERSON") continue;
|
||||||
|
const salutation = hit.original.trim().match(SALUTATION);
|
||||||
|
const name = hit.original.trim().slice(salutation?.[0].length ?? 0);
|
||||||
|
if (hit.score < (salutation ? MIN_SALUTATION_SCORE : MIN_SEED_SCORE) || !NAME.test(name)) continue;
|
||||||
|
const parts = name.split(/[ \t]+/);
|
||||||
|
if (parts.length < 2 && !salutation) continue;
|
||||||
|
add(name, hit.score);
|
||||||
|
for (const part of parts) if (parts.length > 1 && Array.from(part).length >= 3) add(part, hit.score);
|
||||||
|
}
|
||||||
|
if (!candidates.size) return { hits, mapping };
|
||||||
|
|
||||||
|
const next: PlaceholderMapping = { ...mapping };
|
||||||
|
const identities = new Map<string, string>();
|
||||||
|
let counter = 0;
|
||||||
|
for (const [key, entry] of Object.entries(next)) {
|
||||||
|
if (entry.type !== "PERSON") continue;
|
||||||
|
identities.set(entry.original.trim().toLowerCase(), key);
|
||||||
|
counter = Math.max(counter, Number(key.match(/_(\d+)$/)?.[1] ?? 0));
|
||||||
|
}
|
||||||
|
const canonical = (key: string): string => {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
while (next[key]?.merged_into && !seen.has(key)) {
|
||||||
|
seen.add(key);
|
||||||
|
key = next[key].merged_into!;
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
};
|
||||||
|
const placeholderFor = (name: string): string => {
|
||||||
|
let key = identities.get(name.toLowerCase());
|
||||||
|
if (!key) {
|
||||||
|
key = `PERSON_${String(++counter).padStart(2, "0")}`;
|
||||||
|
if (next[key]) throw new Error("Doppelte Platzhalternummer in der Projektzuordnung.");
|
||||||
|
next[key] = { original: name, type: "PERSON" };
|
||||||
|
identities.set(name.toLowerCase(), key);
|
||||||
|
}
|
||||||
|
return canonical(key);
|
||||||
|
};
|
||||||
|
|
||||||
|
const occupied = new Map<number, Array<[number, number]>>();
|
||||||
|
for (const hit of hits) {
|
||||||
|
if (hit.segment === undefined) continue;
|
||||||
|
const ranges = occupied.get(hit.segment) ?? [];
|
||||||
|
ranges.push([hit.start, hit.end]);
|
||||||
|
occupied.set(hit.segment, ranges);
|
||||||
|
}
|
||||||
|
// Longest names first, so a full name is masked as a unit before its parts.
|
||||||
|
// A German genitive "s" stays outside the masked span.
|
||||||
|
const patterns = [...candidates.keys()].sort((a, b) => b.length - a.length || a.localeCompare(b))
|
||||||
|
.map((name) => [name, new RegExp(`(?<![\\p{L}\\p{N}_])${escape(name)}(?=s?(?![\\p{L}\\p{N}_]))`, "gu")] as const);
|
||||||
|
const added: Hit[] = [];
|
||||||
|
for (const [index, segment] of segments.entries()) {
|
||||||
|
if (segment.kind !== "text") continue;
|
||||||
|
const ranges = occupied.get(index) ?? [];
|
||||||
|
for (const [name, pattern] of patterns) {
|
||||||
|
for (const match of segment.text.matchAll(pattern)) {
|
||||||
|
// Hit offsets count code points, matching the Python codec.
|
||||||
|
const start = Array.from(segment.text.slice(0, match.index)).length;
|
||||||
|
const end = start + Array.from(name).length;
|
||||||
|
if (ranges.some(([s, e]) => start < e && s < end)) continue;
|
||||||
|
ranges.push([start, end]);
|
||||||
|
const characters = Array.from(segment.text);
|
||||||
|
added.push({
|
||||||
|
id: `${relative}:local-docx:${index}:${start}:${end}`, file: relative, source: segment.source,
|
||||||
|
original: name, placeholder: placeholderFor(name), type: "PERSON", score: candidates.get(name)!,
|
||||||
|
context: characters.slice(Math.max(0, start - 60), end + 60).join(""),
|
||||||
|
start, end, kind: "content", segment: index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
occupied.set(index, ranges);
|
||||||
|
}
|
||||||
|
if (!added.length) return { hits, mapping };
|
||||||
|
const merged = [...hits, ...added].sort((a, b) => (a.segment ?? 0) - (b.segment ?? 0) || a.start - b.start);
|
||||||
|
return { hits: merged, mapping: next };
|
||||||
|
}
|
||||||
316
src/lib/project-analysis.ts
Normal file
316
src/lib/project-analysis.ts
Normal file
@@ -0,0 +1,316 @@
|
|||||||
|
import { fileTextParts } from "./project-text-stream";
|
||||||
|
import type { TextAnalysisPart } from "./project-text-stream";
|
||||||
|
import type {
|
||||||
|
EntityType,
|
||||||
|
PlaceholderMapping,
|
||||||
|
PseudonymizeResponse,
|
||||||
|
} from "../types";
|
||||||
|
import { makeTextBatches, MAX_BATCH_CODEPOINTS, spansBySegment } from "./project-review";
|
||||||
|
import type { TextBatch } from "./project-review";
|
||||||
|
|
||||||
|
type Analyze = (
|
||||||
|
text: string,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
entityTypes: EntityType[],
|
||||||
|
forceMasks: Record<string, string[]>,
|
||||||
|
) => Promise<PseudonymizeResponse>;
|
||||||
|
|
||||||
|
/** Retry a failing server batch in smaller groups, without losing file boundaries. */
|
||||||
|
export async function analyzeProjectBatch(
|
||||||
|
batch: TextBatch,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
entityTypes: EntityType[],
|
||||||
|
forceMasks: Record<string, string[]>,
|
||||||
|
analyze: Analyze,
|
||||||
|
phase: string,
|
||||||
|
labelForKey: (key: string) => string = (key) => key,
|
||||||
|
): Promise<{
|
||||||
|
mapping: PlaceholderMapping;
|
||||||
|
results: Array<{ batch: TextBatch; result: PseudonymizeResponse }>;
|
||||||
|
}> {
|
||||||
|
try {
|
||||||
|
const result = await analyze(batch.text, mapping, entityTypes, forceMasks);
|
||||||
|
return { mapping: result.mapping, results: [{ batch, result }] };
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
if (!/request failed: (?:413|5\d\d)\b/i.test(message)) {
|
||||||
|
throw new Error(`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`, { cause: error });
|
||||||
|
}
|
||||||
|
if (batch.segments.length < 2) {
|
||||||
|
throw new Error(
|
||||||
|
`${phase}: ${labelForKey(batch.segments[0]?.key ?? "unbekannte Datei")}: ${message}`,
|
||||||
|
{ cause: error },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const middle = Math.floor(batch.segments.length / 2);
|
||||||
|
const halves = [
|
||||||
|
batch.segments.slice(0, middle),
|
||||||
|
batch.segments.slice(middle),
|
||||||
|
];
|
||||||
|
let current = mapping;
|
||||||
|
const results: Array<{ batch: TextBatch; result: PseudonymizeResponse }> =
|
||||||
|
[];
|
||||||
|
for (const segments of halves) {
|
||||||
|
const [part] = makeTextBatches(
|
||||||
|
segments.map(({ key, text }) => ({ key, text })),
|
||||||
|
Number.POSITIVE_INFINITY,
|
||||||
|
);
|
||||||
|
const analyzed = await analyzeProjectBatch(
|
||||||
|
part,
|
||||||
|
current,
|
||||||
|
entityTypes,
|
||||||
|
forceMasks,
|
||||||
|
analyze,
|
||||||
|
phase,
|
||||||
|
labelForKey,
|
||||||
|
);
|
||||||
|
current = analyzed.mapping;
|
||||||
|
results.push(...analyzed.results);
|
||||||
|
}
|
||||||
|
return { mapping: current, results };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type TextSpan = PseudonymizeResponse["spans"][number];
|
||||||
|
type TextChunk = {
|
||||||
|
key: string;
|
||||||
|
file: string;
|
||||||
|
index: number;
|
||||||
|
total: number;
|
||||||
|
text: string;
|
||||||
|
scanStart: number;
|
||||||
|
coreStart: number;
|
||||||
|
coreEnd: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TEXT_CORE_LENGTH = 10_000;
|
||||||
|
const TEXT_CONTEXT_OVERLAP = 384;
|
||||||
|
|
||||||
|
/** Split only at whitespace, retaining context on both sides of every boundary. */
|
||||||
|
function* iterateTextForAnalysis(
|
||||||
|
text: string,
|
||||||
|
coreLength = TEXT_CORE_LENGTH,
|
||||||
|
overlap = TEXT_CONTEXT_OVERLAP,
|
||||||
|
): Generator<{
|
||||||
|
text: string;
|
||||||
|
scanStart: number;
|
||||||
|
coreStart: number;
|
||||||
|
coreEnd: number;
|
||||||
|
}> {
|
||||||
|
if (coreLength < 2 || overlap < 0)
|
||||||
|
throw new Error("Ungültige Abschnittsgröße.");
|
||||||
|
let coreStart = 0;
|
||||||
|
while (coreStart < text.length) {
|
||||||
|
let coreEnd = Math.min(text.length, coreStart + coreLength);
|
||||||
|
if (coreEnd < text.length) {
|
||||||
|
const minimum = coreStart + Math.floor(coreLength / 2);
|
||||||
|
let boundary = text.lastIndexOf("\n", coreEnd - 1);
|
||||||
|
if (boundary < minimum) {
|
||||||
|
boundary = -1;
|
||||||
|
for (let index = coreEnd - 1; index >= minimum; index--) {
|
||||||
|
if (/\s/u.test(text[index])) {
|
||||||
|
boundary = index;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (boundary < minimum) {
|
||||||
|
throw new Error(
|
||||||
|
"Textdatei enthält einen sehr langen Abschnitt ohne Trennstelle. Bitte die Datei aufteilen.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
coreEnd = boundary + 1;
|
||||||
|
}
|
||||||
|
let scanStart = Math.max(0, coreStart - overlap);
|
||||||
|
let scanEnd = Math.min(text.length, coreEnd + overlap);
|
||||||
|
if (scanStart > 0 && /[\uDC00-\uDFFF]/u.test(text[scanStart])) scanStart--;
|
||||||
|
if (scanEnd < text.length && /[\uD800-\uDBFF]/u.test(text[scanEnd - 1]))
|
||||||
|
scanEnd++;
|
||||||
|
yield {
|
||||||
|
text: text.slice(scanStart, scanEnd),
|
||||||
|
scanStart,
|
||||||
|
coreStart,
|
||||||
|
coreEnd,
|
||||||
|
};
|
||||||
|
coreStart = coreEnd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function splitTextForAnalysis(text: string, coreLength = TEXT_CORE_LENGTH, overlap = TEXT_CONTEXT_OVERLAP) {
|
||||||
|
return [...iterateTextForAnalysis(text, coreLength, overlap)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function utf16Positions(text: string): number[] {
|
||||||
|
const positions = [0];
|
||||||
|
let offset = 0;
|
||||||
|
for (const character of text) {
|
||||||
|
offset += character.length;
|
||||||
|
positions.push(offset);
|
||||||
|
}
|
||||||
|
return positions;
|
||||||
|
}
|
||||||
|
|
||||||
|
function reconcileSpans<T extends TextSpan>(spans: T[], file: string): T[] {
|
||||||
|
const sorted = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
|
||||||
|
const result: T[] = [];
|
||||||
|
for (const span of sorted) {
|
||||||
|
const last = result.at(-1);
|
||||||
|
if (!last || span.start >= last.end) {
|
||||||
|
result.push(span);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (span.end <= last.end) continue;
|
||||||
|
throw new Error(
|
||||||
|
`Überlappende Treffer an einer Abschnittsgrenze: ${file}. Bitte Datei abschnittsweise prüfen.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Analyze arbitrarily large UTF-8 text files without sending a whole file to Velum. */
|
||||||
|
export async function analyzeProjectTexts(
|
||||||
|
files: Array<{ key: string; text: string }>,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
entityTypes: EntityType[],
|
||||||
|
forceMasks: Record<string, string[]>,
|
||||||
|
analyze: Analyze,
|
||||||
|
onProgress: (index: number, total: number) => void,
|
||||||
|
): Promise<{
|
||||||
|
mapping: PlaceholderMapping;
|
||||||
|
spansByFile: Map<string, TextSpan[]>;
|
||||||
|
}> {
|
||||||
|
const spansByFile = new Map(files.map(({ key }) => [key, [] as TextSpan[]]));
|
||||||
|
// Only the current request and its offset metadata stay alive. Do not build
|
||||||
|
// arrays of every chunk and every concatenated request for a large file.
|
||||||
|
function* batches(): Generator<{ batch: TextBatch; byKey: Map<string, TextChunk> }> {
|
||||||
|
let chunks: TextChunk[] = [];
|
||||||
|
let length = 0;
|
||||||
|
for (const file of files) {
|
||||||
|
let total = 0;
|
||||||
|
try {
|
||||||
|
for (const part of iterateTextForAnalysis(file.text)) if (part.coreEnd > part.coreStart) total++;
|
||||||
|
let index = 0;
|
||||||
|
for (const part of iterateTextForAnalysis(file.text)) {
|
||||||
|
if (chunks.length && length + 4 + part.text.length > MAX_BATCH_CODEPOINTS) {
|
||||||
|
yield { batch: makeTextBatches(chunks)[0], byKey: new Map(chunks.map((chunk) => [chunk.key, chunk])) };
|
||||||
|
chunks = [];
|
||||||
|
length = 0;
|
||||||
|
}
|
||||||
|
length += (chunks.length ? 4 : 0) + part.text.length;
|
||||||
|
chunks.push({ ...part, key: String(chunks.length), file: file.key, index: index++, total });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`${file.key}: ${(error as Error).message}`, { cause: error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (chunks.length) yield { batch: makeTextBatches(chunks)[0], byKey: new Map(chunks.map((chunk) => [chunk.key, chunk])) };
|
||||||
|
}
|
||||||
|
let total = 0;
|
||||||
|
for (const entry of batches()) if (entry.batch.segments.length) total++;
|
||||||
|
let current = mapping;
|
||||||
|
let index = 0;
|
||||||
|
for (const { batch, byKey } of batches()) {
|
||||||
|
onProgress(++index, total);
|
||||||
|
const analyzed = await analyzeProjectBatch(
|
||||||
|
batch,
|
||||||
|
current,
|
||||||
|
entityTypes,
|
||||||
|
forceMasks,
|
||||||
|
analyze,
|
||||||
|
"Textdateien analysieren",
|
||||||
|
(key) => {
|
||||||
|
const chunk = byKey.get(key);
|
||||||
|
return chunk
|
||||||
|
? `${chunk.file} (Abschnitt ${chunk.index + 1}/${chunk.total})`
|
||||||
|
: key;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
current = analyzed.mapping;
|
||||||
|
for (const { batch: part, result } of analyzed.results) {
|
||||||
|
const bySegment = spansBySegment(part, result.spans);
|
||||||
|
for (const segment of part.segments) {
|
||||||
|
const chunk = byKey.get(segment.key)!;
|
||||||
|
const chunkSpans = bySegment.get(segment.key) ?? [];
|
||||||
|
if (!chunkSpans.length) continue;
|
||||||
|
const positions = utf16Positions(chunk.text);
|
||||||
|
for (const span of chunkSpans) {
|
||||||
|
if (
|
||||||
|
span.start < 0 ||
|
||||||
|
span.end >= positions.length ||
|
||||||
|
span.start >= span.end
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
`Ungültige Trefferposition der Velum-API: ${chunk.file}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const start = chunk.scanStart + positions[span.start];
|
||||||
|
const end = chunk.scanStart + positions[span.end];
|
||||||
|
if (start >= chunk.coreStart && start < chunk.coreEnd) {
|
||||||
|
spansByFile.get(chunk.file)!.push({ ...span, start, end });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [file, spans] of spansByFile)
|
||||||
|
spansByFile.set(file, reconcileSpans(spans, file));
|
||||||
|
return { mapping: current, spansByFile };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type StreamTextSpan = TextSpan & { context: string; contextOffset: number };
|
||||||
|
|
||||||
|
/** Analyze complete-line parts lazily, sharing small requests across file boundaries. */
|
||||||
|
export async function analyzeProjectTextFiles(
|
||||||
|
files: Array<{ key: string; path: string }>, mapping: PlaceholderMapping,
|
||||||
|
entityTypes: EntityType[], forceMasks: Record<string, string[]>, analyze: Analyze,
|
||||||
|
onProgress: (file: string, batch: number) => void,
|
||||||
|
): Promise<{ mapping: PlaceholderMapping; spansByFile: Map<string, StreamTextSpan[]> }> {
|
||||||
|
const spansByFile = new Map(files.map((file) => [file.key, [] as StreamTextSpan[]]));
|
||||||
|
type Part = TextAnalysisPart & { key: string; file: string };
|
||||||
|
let parts: Part[] = [];
|
||||||
|
let size = 0;
|
||||||
|
let current = mapping;
|
||||||
|
let batchIndex = 0;
|
||||||
|
const flush = async () => {
|
||||||
|
if (!parts.length) return;
|
||||||
|
const batch = makeTextBatches(parts)[0];
|
||||||
|
const byKey = new Map(parts.map((part) => [part.key, part]));
|
||||||
|
onProgress(parts[0].file, ++batchIndex);
|
||||||
|
const analyzed = await analyzeProjectBatch(batch, current, entityTypes, forceMasks, analyze,
|
||||||
|
"Textdateien analysieren", (key) => byKey.get(key)?.file ?? key);
|
||||||
|
current = analyzed.mapping;
|
||||||
|
for (const { batch: subBatch, result } of analyzed.results) {
|
||||||
|
for (const [key, spans] of spansBySegment(subBatch, result.spans)) {
|
||||||
|
const part = byKey.get(key)!;
|
||||||
|
const positions = utf16Positions(part.text);
|
||||||
|
for (const span of spans) {
|
||||||
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0
|
||||||
|
|| span.start >= span.end || span.end >= positions.length) throw new Error(`Ungültige Trefferposition der Velum-API: ${part.file}`);
|
||||||
|
const start = part.scanStart + positions[span.start];
|
||||||
|
const end = part.scanStart + positions[span.end];
|
||||||
|
if (start < part.coreStart || start >= part.coreEnd) continue;
|
||||||
|
// Copy the short snippet, allowing the request's source string to be freed.
|
||||||
|
const snippetStart = Math.max(0, positions[span.start] - 70);
|
||||||
|
const context = Buffer.from(part.text.slice(snippetStart, positions[span.end] + 70), "utf8").toString("utf8");
|
||||||
|
spansByFile.get(part.file)!.push({ ...span, start, end, context, contextOffset: positions[span.start] - snippetStart });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parts = [];
|
||||||
|
size = 0;
|
||||||
|
};
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
for await (const part of fileTextParts(file.path)) {
|
||||||
|
if (parts.length && size + 4 + part.text.length > MAX_BATCH_CODEPOINTS) await flush();
|
||||||
|
size += (parts.length ? 4 : 0) + part.text.length;
|
||||||
|
parts.push({ ...part, file: file.key, key: String(parts.length) });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`${file.key}: ${(error as Error).message}`, { cause: error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await flush();
|
||||||
|
for (const [file, spans] of spansByFile) spansByFile.set(file, reconcileSpans(spans, file));
|
||||||
|
return { mapping: current, spansByFile };
|
||||||
|
}
|
||||||
38
src/lib/project-capabilities.ts
Normal file
38
src/lib/project-capabilities.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
/** Requirements follow the files that will actually use the API. */
|
||||||
|
export function requiredProjectCapabilities(documents: boolean): string[] {
|
||||||
|
return ["request_force_masks", ...(documents ? [
|
||||||
|
"document_hit_review", "document_review_mapping", "document_restoration",
|
||||||
|
"comment_author_review", "revision_author_review", "document_image_policy",
|
||||||
|
] : [])];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkProjectCapabilities(
|
||||||
|
url: string, documents: boolean,
|
||||||
|
fetcher: (url: string, init: RequestInit) => Promise<Response>,
|
||||||
|
): Promise<void> {
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetcher(url, { signal: AbortSignal.timeout(15_000) });
|
||||||
|
} catch (error) {
|
||||||
|
const timeout = error instanceof Error && /timeout|abort/i.test(error.name);
|
||||||
|
throw new Error(`Velum: ${timeout ? "Zeitlimit bei der Prüfung der Projektfähigkeiten" : "Projekt-API nicht erreichbar"}: ${url}.`, { cause: error });
|
||||||
|
}
|
||||||
|
if (response.status === 404 || response.status === 405) {
|
||||||
|
throw new Error(`Velum: Projekt-API-Endpunkt fehlt (HTTP ${response.status}): ${url}. Backend aktualisieren oder Basis-URL prüfen.`);
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Velum: Projektfähigkeiten nicht abrufbar (HTTP ${response.status}): ${url}. Anmeldung, Proxy und Backend prüfen.`);
|
||||||
|
}
|
||||||
|
if (!(response.headers.get("content-type") ?? "").includes("application/json")) {
|
||||||
|
throw new Error(`Velum: Keine JSON-Antwort für ${url}. Anmeldung oder API-Weiterleitung prüfen.`);
|
||||||
|
}
|
||||||
|
const capabilities: unknown = await response.json();
|
||||||
|
if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) {
|
||||||
|
throw new Error(`Velum: Ungültige Projektfähigkeiten von ${url}.`);
|
||||||
|
}
|
||||||
|
const missing = requiredProjectCapabilities(documents)
|
||||||
|
.filter((key) => (capabilities as Record<string, unknown>)[key] !== true);
|
||||||
|
if (missing.length) {
|
||||||
|
throw new Error(`Velum: Backend unterstützt die ausgewählten ${documents ? "Office-/PDF-Dateien" : "Textdateien"} noch nicht vollständig. Fehlende API-Fähigkeiten: ${missing.join(", ")}. API: ${url}. Backend aktualisieren.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
164
src/lib/project-jobs.ts
Normal file
164
src/lib/project-jobs.ts
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { environment } from "@raycast/api";
|
||||||
|
import { getPreferences } from "../preferences";
|
||||||
|
import { canonicalProjectPath, projectDataRoot } from "./velum-project";
|
||||||
|
import type { applyProject, prepareProject, Preview, ProjectOutput } from "./project-work";
|
||||||
|
|
||||||
|
export type AnalysisInput = {
|
||||||
|
root: string;
|
||||||
|
files: Parameters<typeof prepareProject>[2];
|
||||||
|
rules: Parameters<typeof prepareProject>[3];
|
||||||
|
whitelist: Parameters<typeof prepareProject>[4];
|
||||||
|
entityTypes: Parameters<typeof prepareProject>[5];
|
||||||
|
skipped: Parameters<typeof prepareProject>[6];
|
||||||
|
reanalyzeUnchanged: boolean;
|
||||||
|
imagePolicy: Parameters<typeof prepareProject>[9];
|
||||||
|
fileSelectionChanged: boolean;
|
||||||
|
};
|
||||||
|
export type Decision = Parameters<typeof applyProject>[5];
|
||||||
|
export type JobPhase = "analysis" | "apply";
|
||||||
|
export type ProjectJobState =
|
||||||
|
| { phase: JobPhase; pid: number; message: string }
|
||||||
|
| { phase: "review" }
|
||||||
|
| { phase: "complete"; output?: ProjectOutput; reused?: number }
|
||||||
|
| { phase: "error"; message: string };
|
||||||
|
|
||||||
|
export function projectJobDirectory(root: string, support = environment.supportPath): string {
|
||||||
|
return join(projectDataRoot(root, support), "active-job");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function writeJobJson(directory: string, file: string, value: unknown): Promise<void> {
|
||||||
|
const target = join(directory, file);
|
||||||
|
const temporary = target + "." + randomUUID();
|
||||||
|
try {
|
||||||
|
await fs.writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 });
|
||||||
|
await fs.rename(temporary, target);
|
||||||
|
} finally {
|
||||||
|
await fs.rm(temporary, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readJobJson<T>(directory: string, file: string): Promise<T> {
|
||||||
|
return JSON.parse(await fs.readFile(join(directory, file), "utf8")) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readProjectJob(root: string): Promise<ProjectJobState | undefined> {
|
||||||
|
const directory = projectJobDirectory(root);
|
||||||
|
let state: ProjectJobState;
|
||||||
|
try {
|
||||||
|
state = await readJobJson<ProjectJobState>(directory, "state.json");
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||||
|
const info = await fs.stat(directory).catch((statError: NodeJS.ErrnoException) => {
|
||||||
|
if (statError.code !== "ENOENT") throw statError;
|
||||||
|
});
|
||||||
|
if (info && Date.now() - info.mtimeMs > 10_000) {
|
||||||
|
return { phase: "error", message: "Der Projektauftrag wurde beim Start unterbrochen." };
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (state.phase === "analysis" || state.phase === "apply") {
|
||||||
|
try {
|
||||||
|
process.kill(state.pid, 0);
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
|
||||||
|
// The worker writes its terminal state before exiting.
|
||||||
|
const last = await readJobJson<ProjectJobState>(directory, "state.json");
|
||||||
|
if (last.phase !== "analysis" && last.phase !== "apply") return last;
|
||||||
|
return { phase: "error", message: "Der lokale Hintergrundprozess wurde beendet." };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadProjectReview(root: string): Promise<{ input: AnalysisInput; preview: Preview }> {
|
||||||
|
const directory = projectJobDirectory(root);
|
||||||
|
const [input, preview] = await Promise.all([
|
||||||
|
readJobJson<AnalysisInput>(directory, "input.json"),
|
||||||
|
readJobJson<Preview>(directory, "preview.json"),
|
||||||
|
]);
|
||||||
|
return { input, preview };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function launch(directory: string, phase: JobPhase): Promise<void> {
|
||||||
|
const config = JSON.stringify({
|
||||||
|
assets: environment.assetsPath,
|
||||||
|
support: environment.supportPath,
|
||||||
|
preferences: getPreferences(),
|
||||||
|
});
|
||||||
|
const child = spawn(process.execPath, [join(environment.assetsPath, "velum-project-worker.cjs"), directory, phase], {
|
||||||
|
detached: true,
|
||||||
|
stdio: ["pipe", "ignore", "ignore"],
|
||||||
|
cwd: directory,
|
||||||
|
});
|
||||||
|
// Register a handler immediately, before doing any asynchronous filesystem IO.
|
||||||
|
const started = new Promise<void>((resolve, reject) => {
|
||||||
|
child.once("error", reject);
|
||||||
|
child.once("spawn", resolve);
|
||||||
|
});
|
||||||
|
child.stdin.on("error", () => undefined);
|
||||||
|
try {
|
||||||
|
await started;
|
||||||
|
await writeJobJson(directory, "state.json", { phase, pid: child.pid,
|
||||||
|
message: phase === "analysis" ? "Analyse startet" : "Ausgabe wird vorbereitet" });
|
||||||
|
// Only the pipe receives credentials. Job metadata, logs and arguments are
|
||||||
|
// safe to retain even after the window or worker closes.
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
child.stdin.once("error", reject);
|
||||||
|
child.stdin.end(config, resolve);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
child.stdin.destroy();
|
||||||
|
child.kill();
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
child.unref();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startProjectAnalysis(input: AnalysisInput): Promise<void> {
|
||||||
|
const root = canonicalProjectPath(input.root);
|
||||||
|
const directory = projectJobDirectory(root);
|
||||||
|
await fs.mkdir(projectDataRoot(root), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.mkdir(directory, { mode: 0o700 });
|
||||||
|
try {
|
||||||
|
await writeJobJson(directory, "input.json", { ...input, root });
|
||||||
|
await launch(directory, "analysis");
|
||||||
|
} catch (error) {
|
||||||
|
await writeJobJson(directory, "state.json", { phase: "error",
|
||||||
|
message: "Der lokale Hintergrundprozess konnte nicht gestartet werden." });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startProjectApply(root: string, decision: Decision): Promise<void> {
|
||||||
|
const directory = projectJobDirectory(root);
|
||||||
|
if ((await readProjectJob(root))?.phase !== "review") {
|
||||||
|
throw new Error("Dieser Projektauftrag steht nicht mehr zur Prüfung bereit.");
|
||||||
|
}
|
||||||
|
// Exclusive creation prevents two windows from publishing the same review.
|
||||||
|
await fs.writeFile(join(directory, "decision.json"), JSON.stringify(decision), { flag: "wx", mode: 0o600 });
|
||||||
|
try {
|
||||||
|
await launch(directory, "apply");
|
||||||
|
} catch (error) {
|
||||||
|
await fs.rm(join(directory, "decision.json"), { force: true });
|
||||||
|
await writeJobJson(directory, "state.json", { phase: "review" });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function discardProjectJob(root: string): Promise<void> {
|
||||||
|
const state = await readProjectJob(root);
|
||||||
|
if (!state || state.phase === "analysis" || state.phase === "apply") {
|
||||||
|
throw new Error("Der Hintergrundauftrag läuft noch.");
|
||||||
|
}
|
||||||
|
const directory = projectJobDirectory(root);
|
||||||
|
if (state.phase === "review") {
|
||||||
|
// Mutual exclusion with the review's Apply action.
|
||||||
|
await fs.writeFile(join(directory, "decision.json"), "", { flag: "wx", mode: 0o600 });
|
||||||
|
}
|
||||||
|
await fs.rm(directory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
83
src/lib/project-relocation.ts
Normal file
83
src/lib/project-relocation.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { basename, dirname, join } from "node:path";
|
||||||
|
import { environment } from "@raycast/api";
|
||||||
|
import { canonicalProjectPath, listRuns, projectDataRoot, saveRun } from "./velum-project";
|
||||||
|
import type { ProjectRun } from "./velum-project";
|
||||||
|
|
||||||
|
export type RelocationResult = { runsMoved: number; copiesRelinked: number; copiesMissing: number };
|
||||||
|
|
||||||
|
async function isDirectory(path: string): Promise<boolean> {
|
||||||
|
try { return (await fs.stat(path)).isDirectory(); }
|
||||||
|
catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exists(path: string): Promise<boolean> {
|
||||||
|
try { await fs.lstat(path); return true; }
|
||||||
|
catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function relocatedCopyPath(run: ProjectRun, newProjectPath: string): Promise<string | undefined> {
|
||||||
|
if (!run.copyPath || await isDirectory(run.copyPath)) return run.copyPath;
|
||||||
|
const parent = dirname(newProjectPath);
|
||||||
|
const candidates = [
|
||||||
|
join(parent, basename(run.copyPath)),
|
||||||
|
join(parent, `${basename(newProjectPath)}-Velum-${run.id}`),
|
||||||
|
];
|
||||||
|
for (const candidate of candidates) if (await isDirectory(candidate)) return candidate;
|
||||||
|
return run.copyPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Change the path identity of a project, preserving every saved run and its private rules. */
|
||||||
|
export async function relocateProject(oldPath: string, chosenPath: string,
|
||||||
|
support = environment.supportPath): Promise<RelocationResult> {
|
||||||
|
const previous = canonicalProjectPath(oldPath);
|
||||||
|
const next = canonicalProjectPath(chosenPath);
|
||||||
|
if (previous === next) throw new Error("Der neue Ordner ist bereits der Projektordner.");
|
||||||
|
if (!await isDirectory(next)) throw new Error("Der neue Projektordner ist nicht vorhanden.");
|
||||||
|
const sourceRoot = projectDataRoot(previous, support);
|
||||||
|
const targetRoot = projectDataRoot(next, support);
|
||||||
|
if (await exists(targetRoot)) {
|
||||||
|
throw new Error("Für diesen Ordner gibt es bereits ein Velum-Projekt. Die Projekte wurden nicht zusammengeführt.");
|
||||||
|
}
|
||||||
|
const runs = await listRuns(previous, support);
|
||||||
|
if (!runs.length) throw new Error("Für den bisherigen Ordner gibt es keinen gespeicherten Projektstand.");
|
||||||
|
const originals = await Promise.all(runs.map(async ({ directory }) =>
|
||||||
|
await fs.readFile(join(directory, "run.json"), "utf8")));
|
||||||
|
const updated = await Promise.all(runs.map(async ({ run }) => ({
|
||||||
|
...run,
|
||||||
|
projectPath: next,
|
||||||
|
projectName: basename(next),
|
||||||
|
copyPath: await relocatedCopyPath(run, next),
|
||||||
|
})));
|
||||||
|
const copyExists = await Promise.all(updated.map(async (run) =>
|
||||||
|
!run.copyPath || await isDirectory(run.copyPath)));
|
||||||
|
await fs.rename(sourceRoot, targetRoot);
|
||||||
|
try {
|
||||||
|
for (let index = 0; index < runs.length; index++) {
|
||||||
|
await saveRun(join(targetRoot, "runs", basename(runs[index].directory)), updated[index]);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
try {
|
||||||
|
for (let index = 0; index < runs.length; index++) {
|
||||||
|
await fs.writeFile(join(targetRoot, "runs", basename(runs[index].directory), "run.json"),
|
||||||
|
originals[index], { encoding: "utf8", mode: 0o600 });
|
||||||
|
}
|
||||||
|
await fs.rename(targetRoot, sourceRoot);
|
||||||
|
} catch (rollbackError) {
|
||||||
|
throw new Error(`Projektpfad konnte nicht vollständig aktualisiert werden: ${(error as Error).message}. `
|
||||||
|
+ `Bitte die Projektstände prüfen; Rücksetzung fehlgeschlagen: ${(rollbackError as Error).message}`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
runsMoved: runs.length,
|
||||||
|
copiesRelinked: updated.filter((run, index) => run.copyPath !== runs[index].run.copyPath).length,
|
||||||
|
copiesMissing: copyExists.filter((available) => !available).length,
|
||||||
|
};
|
||||||
|
}
|
||||||
246
src/lib/project-review.ts
Normal file
246
src/lib/project-review.ts
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
import { whitelistKey } from "./project-whitelist";
|
||||||
|
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||||
|
|
||||||
|
const SEPARATOR = "\n\n\n\n";
|
||||||
|
export const MAX_BATCH_CODEPOINTS = 24000;
|
||||||
|
|
||||||
|
export type BatchItem = { key: string; text: string };
|
||||||
|
export type BatchSegment = BatchItem & { start: number; end: number };
|
||||||
|
export type TextBatch = { text: string; segments: BatchSegment[] };
|
||||||
|
|
||||||
|
/** Filename separators look like spaces to NER, except inside known literal terms. */
|
||||||
|
export function filenameScanText(stem: string, knownTerms: Iterable<string>): string {
|
||||||
|
const protectedOffsets = new Set<number>();
|
||||||
|
for (const term of knownTerms) {
|
||||||
|
if (!term.includes("_")) continue;
|
||||||
|
const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
const pattern = new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "giu");
|
||||||
|
for (const match of stem.matchAll(pattern)) {
|
||||||
|
for (let offset = match.index; offset < match.index + match[0].length; offset++) protectedOffsets.add(offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return stem.replace(/_/g, (_character, offset: number) => protectedOffsets.has(offset) ? "_" : " ");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep file boundaries while reducing many small text/path API calls to a few batches. */
|
||||||
|
export function makeTextBatches(items: BatchItem[], limit = MAX_BATCH_CODEPOINTS): TextBatch[] {
|
||||||
|
const batches: TextBatch[] = [];
|
||||||
|
let segments: BatchSegment[] = [];
|
||||||
|
let text = "";
|
||||||
|
let length = 0;
|
||||||
|
const separatorLength = [...SEPARATOR].length;
|
||||||
|
const flush = () => {
|
||||||
|
if (segments.length) batches.push({ text, segments });
|
||||||
|
segments = [];
|
||||||
|
text = "";
|
||||||
|
length = 0;
|
||||||
|
};
|
||||||
|
for (const item of items) {
|
||||||
|
if (!item.text) continue;
|
||||||
|
const itemLength = [...item.text].length;
|
||||||
|
if (segments.length && length + separatorLength + itemLength > limit) flush();
|
||||||
|
if (segments.length) { text += SEPARATOR; length += separatorLength; }
|
||||||
|
segments.push({ ...item, start: length, end: length + itemLength });
|
||||||
|
text += item.text;
|
||||||
|
length += itemLength;
|
||||||
|
}
|
||||||
|
flush();
|
||||||
|
return batches;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function spansBySegment<T extends { start: number; end: number }>(
|
||||||
|
batch: TextBatch, spans: T[],
|
||||||
|
): Map<string, T[]> {
|
||||||
|
const result = new Map<string, T[]>(batch.segments.map((segment) => [segment.key, []]));
|
||||||
|
let segmentIndex = 0;
|
||||||
|
for (const span of [...spans].sort((a, b) => a.start - b.start)) {
|
||||||
|
while (segmentIndex < batch.segments.length && span.start >= batch.segments[segmentIndex].end) segmentIndex++;
|
||||||
|
const segment = batch.segments[segmentIndex];
|
||||||
|
if (!segment || span.start < segment.start || span.end > segment.end) continue;
|
||||||
|
result.get(segment.key)!.push({ ...span, start: span.start - segment.start, end: span.end - segment.start });
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GroupableHit = { id: string; type: string; original: string; placeholder: string };
|
||||||
|
export type DocumentReviewHit = { id: string; source: string; start: number; end: number;
|
||||||
|
type: string; original: string; context: string };
|
||||||
|
|
||||||
|
/** Rebind approved document hits only when the reviewed occurrence is unchanged. */
|
||||||
|
export function reconcileDocumentHitIds(
|
||||||
|
reviewed: DocumentReviewHit[], acceptedIds: readonly string[], refreshed: DocumentReviewHit[],
|
||||||
|
): string[] | null {
|
||||||
|
const key = (hit: DocumentReviewHit) => JSON.stringify([
|
||||||
|
hit.source, hit.start, hit.end, hit.type, hit.original, hit.context,
|
||||||
|
]);
|
||||||
|
const reviewedById = new Map(reviewed.map((hit) => [hit.id, hit]));
|
||||||
|
const reviewedByKey = new Map<string, DocumentReviewHit[]>();
|
||||||
|
const refreshedByKey = new Map<string, DocumentReviewHit[]>();
|
||||||
|
for (const hit of reviewed) (reviewedByKey.get(key(hit)) ??
|
||||||
|
(reviewedByKey.set(key(hit), []), reviewedByKey.get(key(hit))!)).push(hit);
|
||||||
|
for (const hit of refreshed) (refreshedByKey.get(key(hit)) ??
|
||||||
|
(refreshedByKey.set(key(hit), []), refreshedByKey.get(key(hit))!)).push(hit);
|
||||||
|
const acceptedByKey = new Map<string, Set<string>>();
|
||||||
|
for (const id of acceptedIds) {
|
||||||
|
const hit = reviewedById.get(id);
|
||||||
|
if (!hit) return null;
|
||||||
|
(acceptedByKey.get(key(hit)) ?? (acceptedByKey.set(key(hit), new Set()), acceptedByKey.get(key(hit))!)).add(id);
|
||||||
|
}
|
||||||
|
const resolved: string[] = [];
|
||||||
|
for (const [signature, selected] of acceptedByKey) {
|
||||||
|
const old = reviewedByKey.get(signature)!;
|
||||||
|
const fresh = refreshedByKey.get(signature);
|
||||||
|
if (!fresh || fresh.length !== old.length) return null;
|
||||||
|
if (selected.size === old.length) resolved.push(...fresh.map((hit) => hit.id));
|
||||||
|
else {
|
||||||
|
const matching = fresh.filter((hit) => selected.has(hit.id));
|
||||||
|
if (matching.length !== selected.size) return null;
|
||||||
|
resolved.push(...matching.map((hit) => hit.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ReviewGroup<T extends GroupableHit> = {
|
||||||
|
key: string; type: string; original: string; placeholder: string; hits: T[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export function groupReviewHits<T extends GroupableHit>(hits: T[]): ReviewGroup<T>[] {
|
||||||
|
const groups = new Map<string, ReviewGroup<T>>();
|
||||||
|
for (const hit of hits) {
|
||||||
|
const key = JSON.stringify([hit.type, hit.original, hit.placeholder]);
|
||||||
|
let group = groups.get(key);
|
||||||
|
if (!group) {
|
||||||
|
group = { key, type: hit.type, original: hit.original, placeholder: hit.placeholder,
|
||||||
|
hits: [] };
|
||||||
|
groups.set(key, group);
|
||||||
|
}
|
||||||
|
group.hits.push(hit);
|
||||||
|
}
|
||||||
|
return [...groups.values()].sort((a, b) => a.type.localeCompare(b.type) || a.original.localeCompare(b.original));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render source text literally, even if it contains Markdown or HTML. */
|
||||||
|
export function literalReviewContext(text: string): string {
|
||||||
|
let longestRun = 2;
|
||||||
|
for (const [run] of text.matchAll(/`+/g)) longestRun = Math.max(longestRun, run.length);
|
||||||
|
const fence = "`".repeat(longestRun + 1);
|
||||||
|
return `${fence}\n${text}\n${fence}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeReviewMarkdown(text: string): string {
|
||||||
|
return text.replace(/[^\p{L}\p{M}\p{N} \r\n]/gu, (character) => `&#${character.codePointAt(0)};`)
|
||||||
|
.replace(/ {2,}/g, (spaces) => " " + " ".repeat(spaces.length - 1))
|
||||||
|
.replace(/\r\n?|\n/g, " \n");
|
||||||
|
}
|
||||||
|
|
||||||
|
const latexTextEscapes: Record<string, string> = {
|
||||||
|
"\\": "\\textbackslash{}", "~": "\\textasciitilde{}", "^": "\\textasciicircum{}",
|
||||||
|
"{": "\\{", "}": "\\}", "%": "\\%", "$": "\\$", "&": "\\&", "#": "\\#", "_": "\\_",
|
||||||
|
"-": "{-}", " ": "\\ ", "\t": "\\ \\ \\ \\ ",
|
||||||
|
"'": "\\texttt{'}", "`": "\\texttt{`}",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Raycast renders inline LaTeX with color support in its Markdown detail views. */
|
||||||
|
export function highlightedReviewContext(text: string, start: number, length: number): string {
|
||||||
|
const end = start + length;
|
||||||
|
if (!Number.isInteger(start) || !Number.isInteger(length) || start < 0 || length <= 0 || end > text.length) {
|
||||||
|
return literalReviewContext(text);
|
||||||
|
}
|
||||||
|
const before = escapeReviewMarkdown(text.slice(0, start));
|
||||||
|
const match = text.slice(start, end).split(/\r\n?|\n/).map((line) => {
|
||||||
|
if (!line) return "";
|
||||||
|
const literal = line.replace(/[\\~^{}%$&#_ \t'`-]/g, (character) => latexTextEscapes[character]);
|
||||||
|
return String.raw`\(\textcolor{#dc2626}{\text{${literal}}}\)`;
|
||||||
|
}).join(" \n");
|
||||||
|
return before + match + escapeReviewMarkdown(text.slice(end));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Text API positions count Unicode code points. Mark the exact occurrence in each snippet. */
|
||||||
|
export function textHitContexts(text: string, spans: Array<{ start: number; end: number }>): string[] {
|
||||||
|
const characters = Array.from(text);
|
||||||
|
const contexts: string[] = [];
|
||||||
|
let cursor = 0;
|
||||||
|
let line = 1;
|
||||||
|
for (const { span, index } of spans.map((span, index) => ({ span, index })).sort((a, b) => a.span.start - b.span.start)) {
|
||||||
|
const { start, end } = span;
|
||||||
|
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= end || end > characters.length) {
|
||||||
|
contexts[index] = "Ungültige Trefferposition der Velum-API.";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (; cursor < start; cursor++) {
|
||||||
|
if (characters[cursor] === "\n" || (characters[cursor] === "\r" && characters[cursor + 1] !== "\n")) line++;
|
||||||
|
}
|
||||||
|
const before = characters.slice(Math.max(0, start - 90), start).join("");
|
||||||
|
const match = characters.slice(start, end).join("");
|
||||||
|
const after = characters.slice(end, end + 90).join("");
|
||||||
|
contexts[index] = `**Zeile ${line}**\n\n${highlightedReviewContext(before + match + after, before.length, match.length)}`;
|
||||||
|
}
|
||||||
|
return contexts;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withoutWhitelistedHits<T extends GroupableHit>(hits: T[], whitelist: ProjectWhitelistEntry[]): T[] {
|
||||||
|
const excluded = new Set(whitelist.map(whitelistKey));
|
||||||
|
return hits.filter((hit) => !excluded.has(whitelistKey(hit)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A later run must not turn an existing Velum placeholder plus adjacent text into a new entity. */
|
||||||
|
export function withoutPlaceholderHits<T extends { original: string; type: string }>(
|
||||||
|
hits: T[], knownPlaceholders: Iterable<string> = [],
|
||||||
|
): T[] {
|
||||||
|
const placeholder = /(?<![\p{L}\p{N}])[A-Z][A-Z0-9]*_\d{2,}(?![\p{L}\p{N}])/u;
|
||||||
|
const known = [...knownPlaceholders].filter(Boolean);
|
||||||
|
return hits.filter((hit) => hit.type === "PASSWORT" || (
|
||||||
|
!placeholder.test(hit.original) && !known.some((key) => hit.original.includes(key))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withoutWhitelistedRules<T extends { type: string; value: string }>(
|
||||||
|
rules: T[], whitelist: ProjectWhitelistEntry[],
|
||||||
|
): T[] {
|
||||||
|
const excluded = new Set(whitelist.map(whitelistKey));
|
||||||
|
return rules.filter((rule) => !excluded.has(whitelistKey({ type: rule.type, original: rule.value })));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function canonicalPerson(placeholder: string, merges: Record<string, string>): string {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let current = placeholder;
|
||||||
|
while (merges[current] && !seen.has(current)) {
|
||||||
|
seen.add(current);
|
||||||
|
current = merges[current];
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mergePeople(merges: Record<string, string>, source: string, target: string): Record<string, string> {
|
||||||
|
const from = canonicalPerson(source, merges);
|
||||||
|
const into = canonicalPerson(target, merges);
|
||||||
|
if (from === into) return merges;
|
||||||
|
const next = { ...merges };
|
||||||
|
for (const person of new Set([...Object.keys(next), ...Object.values(next), from])) {
|
||||||
|
if (canonicalPerson(person, merges) === from && person !== into) next[person] = into;
|
||||||
|
}
|
||||||
|
delete next[into];
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mappingForSelection(
|
||||||
|
preview: PlaceholderMapping, previous: PlaceholderMapping, accepted: GroupableHit[],
|
||||||
|
merges: Record<string, string>,
|
||||||
|
): PlaceholderMapping {
|
||||||
|
const keys = new Set([...Object.keys(previous), ...accepted.map((hit) => hit.placeholder)]);
|
||||||
|
const mapping: PlaceholderMapping = {};
|
||||||
|
for (const key of keys) {
|
||||||
|
const entry = preview[key] ?? previous[key];
|
||||||
|
if (entry) mapping[key] = { ...entry };
|
||||||
|
}
|
||||||
|
for (const [source, target] of Object.entries(merges)) {
|
||||||
|
const root = canonicalPerson(target, merges);
|
||||||
|
if (source === root || mapping[source]?.type !== "PERSON" || mapping[root]?.type !== "PERSON") {
|
||||||
|
throw new Error("Ungültige Personen-Zusammenführung.");
|
||||||
|
}
|
||||||
|
mapping[source] = { ...mapping[source], merged_into: root };
|
||||||
|
}
|
||||||
|
return mapping;
|
||||||
|
}
|
||||||
212
src/lib/project-revision.ts
Normal file
212
src/lib/project-revision.ts
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { basename, dirname, join } from "node:path";
|
||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
import { canonicalPerson } from "./project-review";
|
||||||
|
import { mappingForRestoration, mappingRoot } from "./mapping-groups";
|
||||||
|
import {
|
||||||
|
createRun, digest, isMarkdownFile, isRestorableDocument, listRuns, loadProjectWhitelist, publishProjectCopies,
|
||||||
|
replaceProjectFilesInPlace, resolveWithin, restorePath, restoreText,
|
||||||
|
saveProjectWhitelist, saveRun,
|
||||||
|
} from "./velum-project";
|
||||||
|
import type { ProjectRun, ProjectWhitelistEntry } from "./velum-project";
|
||||||
|
|
||||||
|
export type RevisionPlan = {
|
||||||
|
mapping: PlaceholderMapping;
|
||||||
|
replacements: PlaceholderMapping;
|
||||||
|
whitelist: ProjectWhitelistEntry[];
|
||||||
|
released: string[];
|
||||||
|
merged: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function existingRoot(key: string, mapping: PlaceholderMapping): string {
|
||||||
|
return mappingRoot(key, mapping);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build a single direct substitution for each changed placeholder; no replacement chains. */
|
||||||
|
export function planProjectRevision(
|
||||||
|
previous: PlaceholderMapping, selectedRelease: Set<string>, requestedMerges: Record<string, string>,
|
||||||
|
): RevisionPlan {
|
||||||
|
for (const key of selectedRelease) if (!previous[key]) throw new Error(`Unbekannter Platzhalter: ${key}`);
|
||||||
|
const releasedRoots = new Set([...selectedRelease].map((key) => existingRoot(key, previous)));
|
||||||
|
const released = Object.keys(previous).filter((key) => releasedRoots.has(existingRoot(key, previous)));
|
||||||
|
const releaseSet = new Set(released);
|
||||||
|
const roots = new Set(Object.keys(previous).filter((key) =>
|
||||||
|
previous[key].type === "PERSON" && existingRoot(key, previous) === key && !releaseSet.has(key)));
|
||||||
|
const merges: Record<string, string> = {};
|
||||||
|
for (const [source, target] of Object.entries(requestedMerges)) {
|
||||||
|
if (!roots.has(source) || !roots.has(target) || source === target) {
|
||||||
|
throw new Error("Zusammenführung benötigt zwei aktive Personen.");
|
||||||
|
}
|
||||||
|
merges[source] = target;
|
||||||
|
}
|
||||||
|
for (const root of roots) {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let cursor = root;
|
||||||
|
while (merges[cursor]) {
|
||||||
|
if (seen.has(cursor)) throw new Error("Zyklische Zusammenführung.");
|
||||||
|
seen.add(cursor);
|
||||||
|
cursor = merges[cursor];
|
||||||
|
}
|
||||||
|
const final = canonicalPerson(root, merges);
|
||||||
|
if (!roots.has(final)) throw new Error("Ungültiges Ziel der Zusammenführung.");
|
||||||
|
}
|
||||||
|
const mapping: PlaceholderMapping = {};
|
||||||
|
const replacements: PlaceholderMapping = {};
|
||||||
|
const restoration = mappingForRestoration(previous);
|
||||||
|
const merged: string[] = [];
|
||||||
|
for (const [key, entry] of Object.entries(previous)) {
|
||||||
|
const oldRoot = existingRoot(key, previous);
|
||||||
|
if (releaseSet.has(key)) {
|
||||||
|
// A canonical placeholder can stand for several spelling variants. Its
|
||||||
|
// visible text restores to the canonical original; every variant is excluded.
|
||||||
|
replacements[key] = { original: restoration[key].original, type: entry.type };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const finalRoot = entry.type === "PERSON" ? canonicalPerson(oldRoot, merges) : oldRoot;
|
||||||
|
mapping[key] = { ...entry };
|
||||||
|
if (entry.type === "PERSON") {
|
||||||
|
if (finalRoot === key) delete mapping[key].merged_into;
|
||||||
|
else mapping[key].merged_into = finalRoot;
|
||||||
|
}
|
||||||
|
// Older files can still contain an alias even when the mapping already
|
||||||
|
// points at its canonical person. Reapply that substitution on revisions.
|
||||||
|
if (finalRoot !== key) {
|
||||||
|
replacements[key] = { original: finalRoot, type: entry.type };
|
||||||
|
if (finalRoot !== oldRoot) merged.push(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A saved alias may still occur in older output files. Rewrite it together
|
||||||
|
// with its former canonical root when that root is merged now.
|
||||||
|
return {
|
||||||
|
mapping, replacements,
|
||||||
|
whitelist: released.map((key) => ({ type: previous[key].type, original: previous[key].original })),
|
||||||
|
released, merged,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reviseProjectRun(args: {
|
||||||
|
previous: ProjectRun;
|
||||||
|
previousDirectory: string;
|
||||||
|
release: Set<string>;
|
||||||
|
merges: Record<string, string>;
|
||||||
|
/** Re-run already saved person merges against files from an older project stand. */
|
||||||
|
reapplyMerges?: boolean;
|
||||||
|
/** For an explicit release, rewrite the current in-place files so later user edits survive. */
|
||||||
|
useCurrentInPlaceFiles?: boolean;
|
||||||
|
rewriteDocument: (filename: string, data: Buffer, replacements: PlaceholderMapping) => Promise<Buffer>;
|
||||||
|
support?: string;
|
||||||
|
}): Promise<{ run: ProjectRun; directory: string }> {
|
||||||
|
const { previous, previousDirectory, rewriteDocument, support } = args;
|
||||||
|
const latest = (await listRuns(previous.projectPath, support))[0];
|
||||||
|
if (latest?.run.id !== previous.id) {
|
||||||
|
throw new Error("Es gibt bereits einen neueren Projektstand. Bitte die Liste aktualisieren.");
|
||||||
|
}
|
||||||
|
const plan = planProjectRevision(previous.mapping, args.release, args.merges);
|
||||||
|
if (!plan.released.length && !plan.merged.length
|
||||||
|
&& !(args.reapplyMerges && Object.keys(plan.replacements).length)) {
|
||||||
|
throw new Error("Bitte mindestens einen Begriff freigeben oder Personen zusammenführen.");
|
||||||
|
}
|
||||||
|
const inPlace = Boolean(previous.inPlace || previous.sourceInPlace);
|
||||||
|
const previousWhitelist = plan.whitelist.length
|
||||||
|
? await loadProjectWhitelist(previous.projectPath, support) : [];
|
||||||
|
const created = await createRun(previous.projectPath, support);
|
||||||
|
const { directory, run } = created;
|
||||||
|
run.origin = previous.origin;
|
||||||
|
run.revisedFrom = previous.id;
|
||||||
|
run.entityTypes = previous.entityTypes ? [...previous.entityTypes] : undefined;
|
||||||
|
run.customTermCoverage = previous.customTermCoverage;
|
||||||
|
run.commentAuthorCoverage = previous.commentAuthorCoverage;
|
||||||
|
run.reviewAuthorCoverage = previous.reviewAuthorCoverage;
|
||||||
|
run.mapping = plan.mapping;
|
||||||
|
run.sourceState = {};
|
||||||
|
run.matchModes = Object.fromEntries(Object.entries(previous.matchModes ?? {})
|
||||||
|
.filter(([key]) => key in plan.mapping));
|
||||||
|
run.sourceInPlace = inPlace;
|
||||||
|
const usedPaths = new Set<string>();
|
||||||
|
const hashes = new Map<string, string>();
|
||||||
|
// "anywhere" placeholders from imported code projects can be prefixes of
|
||||||
|
// other placeholders. Match unchanged identifiers first as identity entries.
|
||||||
|
const textReplacements: PlaceholderMapping = Object.fromEntries(Object.entries(previous.mapping)
|
||||||
|
.filter(([key]) => !(key in plan.replacements))
|
||||||
|
.map(([key, entry]) => [key, { original: key, type: entry.type }]));
|
||||||
|
Object.assign(textReplacements, plan.replacements);
|
||||||
|
let replacementAttempted = false;
|
||||||
|
let whitelistChanged = false;
|
||||||
|
let publishedCopyPath: string | undefined;
|
||||||
|
try {
|
||||||
|
for (const file of previous.files) {
|
||||||
|
const source = resolveWithin(join(previousDirectory, "files"), file.output);
|
||||||
|
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei im Projektstand: ${file.output}`);
|
||||||
|
const current = resolveWithin(previous.projectPath, file.output);
|
||||||
|
const useCurrent = inPlace && args.useCurrentInPlaceFiles;
|
||||||
|
if (useCurrent && !(await fs.lstat(current)).isFile()) {
|
||||||
|
throw new Error(`Keine reguläre Projektdatei: ${file.output}`);
|
||||||
|
}
|
||||||
|
const data = await fs.readFile(useCurrent ? current : source);
|
||||||
|
hashes.set(file.output, digest(data));
|
||||||
|
const outputPath = restorePath(file.output, textReplacements, previous.matchModes);
|
||||||
|
if (usedPaths.has(outputPath)) throw new Error(`Doppelter Dateiname nach Änderung: ${outputPath}`);
|
||||||
|
usedPaths.add(outputPath);
|
||||||
|
const target = resolveWithin(join(directory, "files"), outputPath);
|
||||||
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
|
const output = file.kind === "document" && isRestorableDocument(file.output)
|
||||||
|
? await rewriteDocument(basename(file.output), data, plan.replacements)
|
||||||
|
: file.kind === "document" ? data
|
||||||
|
: Buffer.from(restoreText(data.toString("utf8"), textReplacements, previous.matchModes,
|
||||||
|
isMarkdownFile(file.output)), "utf8");
|
||||||
|
await fs.writeFile(target, output, { flag: "wx", mode: 0o600 });
|
||||||
|
run.files.push({ source: file.output, output: outputPath, kind: file.kind });
|
||||||
|
if (inPlace) run.sourceState[outputPath] = { hash: digest(output), output: outputPath };
|
||||||
|
}
|
||||||
|
if (!inPlace && previous.sourceState) {
|
||||||
|
const revisedOutput = new Map(run.files.map((file) => [file.source, file.output]));
|
||||||
|
run.sourceState = Object.fromEntries(Object.entries(previous.sourceState)
|
||||||
|
.filter(([, state]) => revisedOutput.has(state.output))
|
||||||
|
.map(([path, state]) => [path, {
|
||||||
|
hash: state.hash, output: revisedOutput.get(state.output)!,
|
||||||
|
}]));
|
||||||
|
}
|
||||||
|
if (plan.whitelist.length) {
|
||||||
|
await saveProjectWhitelist(previous.projectPath, [...previousWhitelist, ...plan.whitelist], support);
|
||||||
|
whitelistChanged = true;
|
||||||
|
}
|
||||||
|
if (inPlace) {
|
||||||
|
// The source folder must still be exactly the snapshot being revised.
|
||||||
|
// This prevents a later local edit from being silently overwritten.
|
||||||
|
for (const file of previous.files) {
|
||||||
|
const current = resolveWithin(previous.projectPath, file.output);
|
||||||
|
if (!(await fs.lstat(current)).isFile() || digest(await fs.readFile(current)) !== hashes.get(file.output)) {
|
||||||
|
throw new Error(args.useCurrentInPlaceFiles
|
||||||
|
? `Projektdatei wurde während der Freigabe erneut geändert: ${file.output}. Bitte erneut versuchen.`
|
||||||
|
: `Projektdatei wurde seit dem letzten Stand geändert: ${file.output}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run.inPlace = true;
|
||||||
|
await saveRun(directory, run);
|
||||||
|
replacementAttempted = true;
|
||||||
|
await replaceProjectFilesInPlace(previous.projectPath, directory, run.files, hashes);
|
||||||
|
} else {
|
||||||
|
if (run.files.length) {
|
||||||
|
publishedCopyPath = await publishProjectCopies(run, directory);
|
||||||
|
run.copyPath = publishedCopyPath;
|
||||||
|
}
|
||||||
|
await saveRun(directory, run);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Keep the backup if replacing the project folder was attempted, even when
|
||||||
|
// its own rollback reports an error.
|
||||||
|
if (!replacementAttempted) {
|
||||||
|
await fs.rm(directory, { recursive: true, force: true });
|
||||||
|
if (publishedCopyPath) await fs.rm(publishedCopyPath, { recursive: true, force: true });
|
||||||
|
} else await fs.rm(join(directory, "run.json"), { force: true });
|
||||||
|
if (whitelistChanged) {
|
||||||
|
try { await saveProjectWhitelist(previous.projectPath, previousWhitelist, support); }
|
||||||
|
catch (rollbackError) {
|
||||||
|
throw new Error(`${(error as Error).message} Die Ausnahmeliste konnte nicht zurückgesetzt werden: ${(rollbackError as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (replacementAttempted) throw new Error(`${(error as Error).message} Sicherung des vorigen Projektstands: ${directory}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return { run, directory };
|
||||||
|
}
|
||||||
99
src/lib/project-text-mapping.ts
Normal file
99
src/lib/project-text-mapping.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
import type { PlaceholderMapping, PseudonymizeResponse } from "../types";
|
||||||
|
|
||||||
|
type Analyze = (text: string, mapping: PlaceholderMapping, types: string[],
|
||||||
|
masks: Record<string, string[]>) => Promise<PseudonymizeResponse>;
|
||||||
|
|
||||||
|
/** Keep project identities locally; the API sees only rules needed by this text. */
|
||||||
|
export function projectTextAnalyzer(initial: PlaceholderMapping, analyze: Analyze): Analyze {
|
||||||
|
const mapping: PlaceholderMapping = { ...initial };
|
||||||
|
const identities = new Map<string, string>();
|
||||||
|
const counters = new Map<string, number>();
|
||||||
|
const identity = (type: string, original: string) => JSON.stringify([type, original.trim().toLowerCase()]);
|
||||||
|
const roots = new Set(Object.values(initial).flatMap((entry) => entry.merged_into ? [entry.merged_into] : []));
|
||||||
|
// Ordinary historical NER mappings do not force recognition. Only custom
|
||||||
|
// terms and user-confirmed person aliases have recognition semantics.
|
||||||
|
const rules: PlaceholderMapping = {};
|
||||||
|
for (const [key, entry] of Object.entries(initial)) {
|
||||||
|
identities.set(identity(entry.type, entry.original), key);
|
||||||
|
const number = Number(key.replace(/[<>]/g, "").match(/_(\d+)$/)?.[1] ?? 0);
|
||||||
|
counters.set(entry.type, Math.max(counters.get(entry.type) ?? 0, number));
|
||||||
|
if (entry.type === "BEGRIFF" || entry.merged_into || roots.has(key)) rules[key] = entry;
|
||||||
|
}
|
||||||
|
const canonical = (key: string): string => {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
while (mapping[key]?.merged_into) {
|
||||||
|
if (seen.has(key)) throw new Error("Zyklische Personen-Zusammenführung.");
|
||||||
|
seen.add(key);
|
||||||
|
key = mapping[key].merged_into!;
|
||||||
|
if (!mapping[key]) throw new Error("Ziel einer Personen-Zusammenführung fehlt.");
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
};
|
||||||
|
return async (text, _previous, types, masks) => {
|
||||||
|
// Other project phases (for example Office analysis) may have extended
|
||||||
|
// the mapping since the previous text request. Keep those identities too.
|
||||||
|
if (_previous !== mapping) {
|
||||||
|
const addedRoots = new Set(Object.values(_previous).flatMap((entry) => entry.merged_into ? [entry.merged_into] : []));
|
||||||
|
for (const [key, entry] of Object.entries(_previous)) {
|
||||||
|
if (mapping[key] && identity(mapping[key].type, mapping[key].original) !== identity(entry.type, entry.original)) {
|
||||||
|
throw new Error("Widersprüchliche Platzhalter in der Projektzuordnung.");
|
||||||
|
}
|
||||||
|
mapping[key] = entry;
|
||||||
|
identities.set(identity(entry.type, entry.original), key);
|
||||||
|
const number = Number(key.replace(/[<>]/g, "").match(/_(\d+)$/)?.[1] ?? 0);
|
||||||
|
counters.set(entry.type, Math.max(counters.get(entry.type) ?? 0, number));
|
||||||
|
if (entry.type === "BEGRIFF" || entry.merged_into || addedRoots.has(key)) rules[key] = entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const lower = text.toLowerCase().replace(/\s+/gu, " ");
|
||||||
|
const window: PlaceholderMapping = {};
|
||||||
|
for (const [key, entry] of Object.entries(rules)) {
|
||||||
|
if (!lower.includes(entry.original.trim().toLowerCase().replace(/\s+/gu, " "))) continue;
|
||||||
|
let dependency: string | null | undefined = key;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
while (dependency) {
|
||||||
|
if (seen.has(dependency) || !mapping[dependency]) throw new Error("Ungültige Personen-Zusammenführung.");
|
||||||
|
seen.add(dependency);
|
||||||
|
window[dependency] = mapping[dependency];
|
||||||
|
dependency = mapping[dependency].merged_into;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const response = await analyze(text, window, types, masks);
|
||||||
|
const translated = new Map<string, string>();
|
||||||
|
for (const [remote, entry] of Object.entries(response.mapping)) {
|
||||||
|
const id = identity(entry.type, entry.original);
|
||||||
|
let local = identities.get(id);
|
||||||
|
if (!local) {
|
||||||
|
const number = (counters.get(entry.type) ?? 0) + 1;
|
||||||
|
counters.set(entry.type, number);
|
||||||
|
local = `${entry.type}_${String(number).padStart(2, "0")}`;
|
||||||
|
if (mapping[local]) throw new Error("Doppelte Platzhalternummer in der Projektzuordnung.");
|
||||||
|
mapping[local] = { original: entry.original, type: entry.type };
|
||||||
|
identities.set(id, local);
|
||||||
|
if (entry.type === "BEGRIFF") rules[local] = mapping[local];
|
||||||
|
}
|
||||||
|
translated.set(remote, canonical(local));
|
||||||
|
}
|
||||||
|
const spans = response.spans.map((span) => {
|
||||||
|
const placeholder = translated.get(span.placeholder);
|
||||||
|
if (!placeholder) throw new Error("Velum-Treffer ohne passende Zuordnung.");
|
||||||
|
return { ...span, placeholder };
|
||||||
|
});
|
||||||
|
// Rebuild from original positions so existing literal placeholders are
|
||||||
|
// never accidentally renumbered alongside newly detected entities.
|
||||||
|
const characters = Array.from(text);
|
||||||
|
const pieces: string[] = [];
|
||||||
|
let offset = 0;
|
||||||
|
for (const span of [...spans].sort((a, b) => a.start - b.start)) {
|
||||||
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|
||||||
|
|| span.start < offset || span.start >= span.end || span.end > characters.length) {
|
||||||
|
throw new Error("Ungültige Trefferposition der Velum-API.");
|
||||||
|
}
|
||||||
|
pieces.push(characters.slice(offset, span.start).join(""), span.placeholder);
|
||||||
|
offset = span.end;
|
||||||
|
}
|
||||||
|
pieces.push(characters.slice(offset).join(""));
|
||||||
|
return { ...response, pseudonymized_text: pieces.join(""), mapping, spans,
|
||||||
|
entity_count: identities.size };
|
||||||
|
};
|
||||||
|
}
|
||||||
169
src/lib/project-text-stream.ts
Normal file
169
src/lib/project-text-stream.ts
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
import { createReadStream, promises as fs } from "node:fs";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
|
||||||
|
export const TEXT_CORE_LENGTH = 10_000;
|
||||||
|
export const MAX_TEXT_LINE_LENGTH = 20_000;
|
||||||
|
const OVERLAP = 384;
|
||||||
|
|
||||||
|
export async function hashProjectFile(path: string): Promise<string> {
|
||||||
|
const hash = createHash("sha256");
|
||||||
|
for await (const data of createReadStream(path)) hash.update(data);
|
||||||
|
return hash.digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preserve BOM, CRLF and Unicode; incomplete UTF-8 sequences carry into the next read. */
|
||||||
|
export async function* decodedText(path: string, hash?: ReturnType<typeof createHash>, highWaterMark = 64 * 1024): AsyncGenerator<string> {
|
||||||
|
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||||
|
for await (const data of createReadStream(path, { highWaterMark })) {
|
||||||
|
const buffer = data as Buffer;
|
||||||
|
hash?.update(buffer);
|
||||||
|
if (buffer.includes(0)) throw new Error("Binärdatei");
|
||||||
|
let text: string;
|
||||||
|
try { text = decoder.decode(buffer, { stream: true }); }
|
||||||
|
catch { throw new Error("Keine gültige UTF-8-Textdatei"); }
|
||||||
|
if (text) yield text;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const tail = decoder.decode();
|
||||||
|
if (tail) yield tail;
|
||||||
|
} catch { throw new Error("Keine gültige UTF-8-Textdatei"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function inspectTextFile(path: string): Promise<string> {
|
||||||
|
const hash = createHash("sha256");
|
||||||
|
for await (const text of decodedText(path, hash)) { if (!text.length) continue; }
|
||||||
|
return hash.digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Yield complete lines, retaining their exact delimiters and the final unterminated line. */
|
||||||
|
export async function* textLines(chunks: AsyncIterable<string>, maxLineLength = MAX_TEXT_LINE_LENGTH): AsyncGenerator<string> {
|
||||||
|
let pending = "";
|
||||||
|
let line = 1;
|
||||||
|
const check = (value: string) => {
|
||||||
|
if (value.length > maxLineLength) throw new Error(`Zeile ${line} ist länger als ${maxLineLength} Zeichen. Bitte diese Zeile an Wortgrenzen aufteilen; Velum zerschneidet keine Wörter.`);
|
||||||
|
};
|
||||||
|
for await (const chunk of chunks) {
|
||||||
|
pending += chunk;
|
||||||
|
let start = 0;
|
||||||
|
const endings = /\r\n|\r|\n/g;
|
||||||
|
for (let match = endings.exec(pending); match; match = endings.exec(pending)) {
|
||||||
|
if (match[0] === "\r" && match.index === pending.length - 1) break;
|
||||||
|
const end = match.index + match[0].length;
|
||||||
|
const value = pending.slice(start, end);
|
||||||
|
check(value);
|
||||||
|
yield value;
|
||||||
|
line++;
|
||||||
|
start = end;
|
||||||
|
}
|
||||||
|
pending = pending.slice(start);
|
||||||
|
check(pending);
|
||||||
|
}
|
||||||
|
if (pending) { check(pending); yield pending; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function* lineCores(path: string): AsyncGenerator<string> {
|
||||||
|
let core = "";
|
||||||
|
for await (const line of textLines(decodedText(path))) {
|
||||||
|
if (core && core.length + line.length > TEXT_CORE_LENGTH) { yield core; core = ""; }
|
||||||
|
core += line;
|
||||||
|
if (core.length >= TEXT_CORE_LENGTH) { yield core; core = ""; }
|
||||||
|
}
|
||||||
|
if (core) yield core;
|
||||||
|
}
|
||||||
|
|
||||||
|
function leftContext(text: string): string {
|
||||||
|
if (text.length <= OVERLAP) return text;
|
||||||
|
// Start at a complete token; the core itself always contains complete lines.
|
||||||
|
const tail = text.slice(-OVERLAP);
|
||||||
|
const boundary = tail.search(/\s/u);
|
||||||
|
return boundary < 0 ? "" : tail.slice(boundary + 1);
|
||||||
|
}
|
||||||
|
function rightContext(text: string): string {
|
||||||
|
if (text.length <= OVERLAP) return text;
|
||||||
|
const head = text.slice(0, OVERLAP);
|
||||||
|
for (let i = head.length - 1; i >= 0; i--) if (/\s/u.test(head[i])) return head.slice(0, i + 1);
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TextAnalysisPart = { text: string; scanStart: number; coreStart: number; coreEnd: number };
|
||||||
|
|
||||||
|
/** One previous, current and next core at most; no array of the entire source. */
|
||||||
|
export async function* fileTextParts(path: string): AsyncGenerator<TextAnalysisPart> {
|
||||||
|
const cores = lineCores(path)[Symbol.asyncIterator]();
|
||||||
|
let current = await cores.next();
|
||||||
|
let previous = "";
|
||||||
|
let offset = 0;
|
||||||
|
try {
|
||||||
|
while (!current.done) {
|
||||||
|
const next = await cores.next();
|
||||||
|
const left = leftContext(previous);
|
||||||
|
const right = rightContext(next.done ? "" : next.value);
|
||||||
|
yield { text: left + current.value + right, scanStart: offset - left.length,
|
||||||
|
coreStart: offset, coreEnd: offset + current.value.length };
|
||||||
|
offset += current.value.length;
|
||||||
|
previous = current.value;
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
} finally { await cores.return?.(undefined); }
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReplacementSpan = { start: number; end: number; placeholder: string; id: string };
|
||||||
|
|
||||||
|
/** Reassemble the original stream, substituting only approved original-coordinate spans. */
|
||||||
|
export async function writeReplacedTextFile(
|
||||||
|
source: string, target: string, spans: ReplacementSpan[], accepted: Set<string>, expectedHash: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const selected = spans.filter((span) => accepted.has(span.id)).sort((a, b) => a.start - b.start);
|
||||||
|
for (let index = 0; index < selected.length; index++) {
|
||||||
|
const span = selected[index];
|
||||||
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.start >= span.end
|
||||||
|
|| (index && span.start < selected[index - 1].end)) throw new Error("Ungültige oder überlappende Trefferposition.");
|
||||||
|
}
|
||||||
|
const inputHash = createHash("sha256");
|
||||||
|
const outputHash = createHash("sha256");
|
||||||
|
const output = await fs.open(target, "wx", 0o600);
|
||||||
|
let fragments: string[] = [];
|
||||||
|
let bufferedLength = 0;
|
||||||
|
const flushOutput = async () => {
|
||||||
|
if (!bufferedLength) return;
|
||||||
|
const bytes = Buffer.from(fragments.join(""), "utf8");
|
||||||
|
fragments = [];
|
||||||
|
bufferedLength = 0;
|
||||||
|
outputHash.update(bytes);
|
||||||
|
await output.writeFile(bytes);
|
||||||
|
};
|
||||||
|
const write = async (text: string) => {
|
||||||
|
if (!text) return;
|
||||||
|
fragments.push(text);
|
||||||
|
bufferedLength += text.length;
|
||||||
|
if (bufferedLength >= 64 * 1024) await flushOutput();
|
||||||
|
};
|
||||||
|
let offset = 0;
|
||||||
|
let pending = "";
|
||||||
|
let index = 0;
|
||||||
|
let complete = false;
|
||||||
|
try {
|
||||||
|
for await (const chunk of decodedText(source, inputHash)) {
|
||||||
|
pending += chunk;
|
||||||
|
let consumed = 0;
|
||||||
|
while (index < selected.length && selected[index].end <= offset + pending.length) {
|
||||||
|
const span = selected[index++];
|
||||||
|
await write(pending.slice(consumed, span.start - offset));
|
||||||
|
await write(span.placeholder);
|
||||||
|
consumed = span.end - offset;
|
||||||
|
}
|
||||||
|
const flush = index < selected.length ? Math.min(pending.length, selected[index].start - offset) : pending.length;
|
||||||
|
await write(pending.slice(consumed, flush));
|
||||||
|
pending = pending.slice(flush);
|
||||||
|
offset += flush;
|
||||||
|
}
|
||||||
|
if (index !== selected.length || pending) throw new Error("Trefferposition liegt außerhalb der Quelldatei.");
|
||||||
|
await flushOutput();
|
||||||
|
if (inputHash.digest("hex") !== expectedHash) throw new Error("Datei wurde seit der Vorschau geändert.");
|
||||||
|
complete = true;
|
||||||
|
return outputHash.digest("hex");
|
||||||
|
} finally {
|
||||||
|
await output.close();
|
||||||
|
if (!complete) await fs.rm(target, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
5
src/lib/project-whitelist.ts
Normal file
5
src/lib/project-whitelist.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export type ProjectWhitelistEntry = { type: string; original: string };
|
||||||
|
|
||||||
|
export function whitelistKey(entry: ProjectWhitelistEntry): string {
|
||||||
|
return JSON.stringify([entry.type.toUpperCase(), entry.original.trim().toLocaleLowerCase("de")]);
|
||||||
|
}
|
||||||
366
src/lib/project-work.ts
Normal file
366
src/lib/project-work.ts
Normal file
@@ -0,0 +1,366 @@
|
|||||||
|
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||||
|
import { basename, dirname, extname, join } from "node:path";
|
||||||
|
import { pseudonymize, pseudonymizeDocument, requireProjectCapabilities } from "../velum";
|
||||||
|
import type { DocumentHit } from "../velum";
|
||||||
|
import type { EntityType, PlaceholderMapping } from "../types";
|
||||||
|
import {
|
||||||
|
createRun, digest, forceMasks, listRuns, loadProjectWhitelist, publishProjectCopies, replaceSpans,
|
||||||
|
reusableProjectOutput, replaceProjectFilesInPlace, resolveWithin, safeRelativePath,
|
||||||
|
saveProjectWhitelist, saveRun, sameEntityTypeCoverage, toUtf16Offsets,
|
||||||
|
} from "./velum-project";
|
||||||
|
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, RunFile, SkippedProjectFile } from "./velum-project";
|
||||||
|
import {
|
||||||
|
canonicalPerson, filenameScanText, makeTextBatches, mappingForSelection, reconcileDocumentHitIds, spansBySegment,
|
||||||
|
withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
|
||||||
|
} from "./project-review";
|
||||||
|
import { analyzeProjectBatch, analyzeProjectTextFiles } from "./project-analysis";
|
||||||
|
import { projectTextAnalyzer } from "./project-text-mapping";
|
||||||
|
import { hashProjectFile, inspectTextFile, writeReplacedTextFile } from "./project-text-stream";
|
||||||
|
import { checkedImageReport, sameImagePolicyCoverage, summarizeImages } from "./image-policy";
|
||||||
|
import type { ImagePolicy, DocumentImageReport } from "./image-policy";
|
||||||
|
import { inspectDocx, writeDocx } from "./local-docx";
|
||||||
|
|
||||||
|
export type Hit = {
|
||||||
|
id: string; file: string; source: string; original: string; placeholder: string;
|
||||||
|
type: string; score: number; context: string; start: number; end: number;
|
||||||
|
kind: "content" | "path"; segment?: number; contextOffset?: number;
|
||||||
|
};
|
||||||
|
type Draft = { file: ProjectFile; hash: string; hits: Hit[]; analysisMapping?: PlaceholderMapping; docxSegmentCount?: number };
|
||||||
|
type PathDraft = { key: string; value: string; hits: Hit[] };
|
||||||
|
export type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string; imageReport?: DocumentImageReport; localDocx?: true }>;
|
||||||
|
baseRunId?: string; paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
|
||||||
|
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
|
||||||
|
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy; customTermCoverage?: string };
|
||||||
|
|
||||||
|
function isLocalDocx(file: ProjectFile): boolean {
|
||||||
|
return file.kind === "document" && extname(file.relPath).toLowerCase() === ".docx";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUnreadableDocument(error: unknown): boolean {
|
||||||
|
const message = error instanceof Error ? error.message : "";
|
||||||
|
return /request failed: 422\b/i.test(message)
|
||||||
|
&& /konnte nicht gelesen werden|not a zip file|BadZipFile/i.test(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
|
||||||
|
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
|
||||||
|
contextOffset: Array.from(hit.context).slice(0, Math.min(60, hit.start)).join("").length,
|
||||||
|
file: file.relPath, kind: "content" as const }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function pathSegments(files: ProjectFile[]): PathDraft[] {
|
||||||
|
const map = new Map<string, PathDraft>();
|
||||||
|
for (const file of files) {
|
||||||
|
const parts = file.relPath.split("/");
|
||||||
|
for (let index = 0; index < parts.length; index++) {
|
||||||
|
const key = parts.slice(0, index + 1).join("/");
|
||||||
|
const isFile = index === parts.length - 1;
|
||||||
|
const value = isFile ? basename(parts[index], extname(parts[index])) : parts[index];
|
||||||
|
if (value && !map.has(key)) map.set(key, { key, value, hits: [] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...map.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function prepareProject(assets: string, root: string, files: ProjectFile[], rules: ProjectRule[], whitelist: ProjectWhitelistEntry[], entityTypes: EntityType[],
|
||||||
|
skipped: SkippedProjectFile[], reanalyzeUnchanged: boolean,
|
||||||
|
onProgress: (message: string) => void, imagePolicy: ImagePolicy): Promise<Preview> {
|
||||||
|
await requireProjectCapabilities(files.some((file) => file.kind === "document" && !isLocalDocx(file)));
|
||||||
|
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
||||||
|
const latestEntry = (await listRuns(root))[0];
|
||||||
|
const latest = latestEntry?.run;
|
||||||
|
const categoryCoverageChanged = Boolean(latest && !sameEntityTypeCoverage(latest, entityTypes));
|
||||||
|
const customTermCoverage = rules.length ? digest(Buffer.from(JSON.stringify(rules))) : undefined;
|
||||||
|
const customTermsChanged = latest?.customTermCoverage !== customTermCoverage;
|
||||||
|
if (categoryCoverageChanged) onProgress("Kategorien geändert oder alter Stand: Dateien erneut analysieren");
|
||||||
|
const previousMapping: PlaceholderMapping = latest?.mapping ?? {};
|
||||||
|
const previousPlaceholders = Object.keys(previousMapping);
|
||||||
|
let mapping: PlaceholderMapping = previousMapping;
|
||||||
|
const drafts: Draft[] = [];
|
||||||
|
const retained: Preview["retained"] = [];
|
||||||
|
const hits: Hit[] = [];
|
||||||
|
const sourceInPlace = Boolean(latest?.inPlace || latest?.sourceInPlace);
|
||||||
|
const previousDirectory = latestEntry?.directory;
|
||||||
|
for (const file of files) {
|
||||||
|
onProgress(`Datei prüfen: ${file.relPath}`);
|
||||||
|
let hash: string;
|
||||||
|
try { hash = file.kind === "text" ? await inspectTextFile(file.absPath) : await hashProjectFile(file.absPath); }
|
||||||
|
catch (error) {
|
||||||
|
const reason = (error as Error).message;
|
||||||
|
if (!/^(Binärdatei|Keine gültige UTF-8-Textdatei)$/.test(reason)) throw error;
|
||||||
|
skipped.push({ path: file.relPath, reason });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const imageCoverageMatches = file.kind !== "document" || sameImagePolicyCoverage(latest, imagePolicy);
|
||||||
|
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && !customTermsChanged && imageCoverageMatches && latest && previousDirectory
|
||||||
|
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
|
||||||
|
const previousFile = latest?.files.find((saved) => saved.output === previousOutput);
|
||||||
|
if (previousOutput && previousDirectory && (!isLocalDocx(file) || previousFile?.localDocx)) {
|
||||||
|
retained.push({ file, hash, output: previousOutput, directory: previousDirectory,
|
||||||
|
imageReport: previousFile?.imageReport, localDocx: previousFile?.localDocx });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const draft: Draft = { file, hash, hits: [] };
|
||||||
|
drafts.push(draft);
|
||||||
|
}
|
||||||
|
const addHits = (draft: Draft, found: Hit[]) => {
|
||||||
|
draft.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||||
|
for (const hit of draft.hits) hits.push(hit);
|
||||||
|
};
|
||||||
|
const textDrafts = drafts.filter((draft) => draft.file.kind === "text");
|
||||||
|
const analyzeText = projectTextAnalyzer(mapping, async (text, current, types, rules) => {
|
||||||
|
try {
|
||||||
|
return await pseudonymize(text, current, types, rules, AbortSignal.timeout(60_000));
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && /timeout|abort/i.test(error.name)) {
|
||||||
|
throw new Error("Velum: Analyse-Zeitlimit nach 60 Sekunden erreicht. Backend-Auslastung und Proxy-Zeitlimit prüfen.", { cause: error });
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const analyzedTexts = await analyzeProjectTextFiles(textDrafts.map((draft) => ({
|
||||||
|
key: draft.file.relPath, path: draft.file.absPath,
|
||||||
|
})), mapping, entityTypes, masks, analyzeText,
|
||||||
|
(file, index) => onProgress(`Textdateien analysieren: ${file} · Paket ${index}`));
|
||||||
|
mapping = analyzedTexts.mapping;
|
||||||
|
for (const draft of textDrafts) {
|
||||||
|
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde während der Analyse geändert: ${draft.file.relPath}`);
|
||||||
|
addHits(draft, (analyzedTexts.spansByFile.get(draft.file.relPath) ?? []).map((span, index) => Object.assign(span, {
|
||||||
|
id: `${draft.file.relPath}:content:${index}`, file: draft.file.relPath,
|
||||||
|
source: draft.file.relPath, kind: "content" as const,
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
const documents = drafts.filter((draft) => draft.file.kind === "document");
|
||||||
|
for (const [index, draft] of documents.entries()) {
|
||||||
|
onProgress(`Dokumente analysieren: ${index + 1}/${documents.length}`);
|
||||||
|
try {
|
||||||
|
if (isLocalDocx(draft.file)) {
|
||||||
|
const result = await inspectDocx(assets, draft.file.absPath, draft.file.relPath, draft.hash,
|
||||||
|
imagePolicy, mapping, entityTypes, masks, onProgress);
|
||||||
|
mapping = result.mapping;
|
||||||
|
draft.docxSegmentCount = result.segmentCount;
|
||||||
|
addHits(draft, result.hits);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const data = await fs.readFile(draft.file.absPath);
|
||||||
|
draft.analysisMapping = mapping;
|
||||||
|
const result = await pseudonymizeDocument(basename(draft.file.relPath), data, mapping, masks, undefined, entityTypes, undefined, imagePolicy);
|
||||||
|
mapping = result.mapping;
|
||||||
|
addHits(draft, documentHits(draft.file, result.hits));
|
||||||
|
} catch (error) {
|
||||||
|
if (isLocalDocx(draft.file) || !isUnreadableDocument(error)) {
|
||||||
|
throw new Error(`${draft.file.relPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
|
}
|
||||||
|
skipped.push({ path: draft.file.relPath, reason: "Office-/PDF-Inhalt konnte nicht gelesen werden" });
|
||||||
|
drafts.splice(drafts.indexOf(draft), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Names of retained files already have a reviewed output in the saved stand.
|
||||||
|
// Only new or changed files need another filename analysis.
|
||||||
|
if (!drafts.length && !retained.length) {
|
||||||
|
const first = skipped[0];
|
||||||
|
throw new Error(`Keine lesbaren Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`);
|
||||||
|
}
|
||||||
|
const paths = pathSegments(drafts.map((draft) => draft.file));
|
||||||
|
const knownTerms = [...Object.keys(mapping), ...Object.values(mapping).map((entry) => entry.original),
|
||||||
|
...withoutWhitelistedRules(rules, whitelist).map((rule) => rule.value)];
|
||||||
|
const pathBatches = makeTextBatches(paths.map((path) => ({
|
||||||
|
key: path.key, text: filenameScanText(path.value, knownTerms),
|
||||||
|
})));
|
||||||
|
const byPath = new Map(paths.map((path) => [path.key, path]));
|
||||||
|
for (const [index, batch] of pathBatches.entries()) {
|
||||||
|
onProgress(`Dateinamen analysieren: Paket ${index + 1}/${pathBatches.length}`);
|
||||||
|
const analyzed = await analyzeProjectBatch(batch, mapping, entityTypes, masks, analyzeText,
|
||||||
|
"Dateinamen analysieren");
|
||||||
|
mapping = analyzed.mapping;
|
||||||
|
for (const { batch: part, result } of analyzed.results) {
|
||||||
|
const spans = spansBySegment(part, result.spans);
|
||||||
|
for (const segment of part.segments) {
|
||||||
|
const path = byPath.get(segment.key)!;
|
||||||
|
const found = toUtf16Offsets(segment.text, spans.get(path.key) ?? []).map((span, hitIndex) => ({
|
||||||
|
...span, id: `${path.key}:path:${hitIndex}`, file: path.key,
|
||||||
|
source: "Datei- oder Ordnername", kind: "path" as const,
|
||||||
|
context: path.value, contextOffset: span.start,
|
||||||
|
}));
|
||||||
|
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
|
||||||
|
for (const hit of path.hits) hits.push(hit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { drafts, retained, paths, mapping, previousMapping, baseRunId: latest?.id,
|
||||||
|
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy, customTermCoverage };
|
||||||
|
}
|
||||||
|
|
||||||
|
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
|
||||||
|
merges: Record<string, string>): string {
|
||||||
|
const lookup = new Map(paths.map((item) => [item.key, item]));
|
||||||
|
const parts = relPath.split("/");
|
||||||
|
const output = parts.map((part, index) => {
|
||||||
|
const key = parts.slice(0, index + 1).join("/");
|
||||||
|
const path = lookup.get(key);
|
||||||
|
if (!path) return part;
|
||||||
|
const isFile = index === parts.length - 1;
|
||||||
|
const extension = isFile ? (document && extname(part).toLowerCase() === ".pdf" ? ".docx" : extname(part)) : "";
|
||||||
|
return replaceSpans(path.value, withPersonMerges(path.hits, merges), accepted) + extension;
|
||||||
|
});
|
||||||
|
return safeRelativePath(output.join("/"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function withPersonMerges(hits: Hit[], merges: Record<string, string>): Hit[] {
|
||||||
|
return hits.map((hit) => hit.type === "PERSON"
|
||||||
|
? { ...hit, placeholder: canonicalPerson(hit.placeholder, merges) } : hit);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ProjectOutput = {
|
||||||
|
directory: string; inPlace: boolean; files: number; replaced: number;
|
||||||
|
images: ReturnType<typeof summarizeImages>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function applyProject(
|
||||||
|
assets: string, root: string, preview: Preview, rules: ProjectRule[], whitelist: ProjectWhitelistEntry[],
|
||||||
|
decision: { inPlace: boolean; acceptedIds: string[]; activeMerges: Record<string, string>; rejected: ProjectWhitelistEntry[] },
|
||||||
|
progress: (message: string) => void,
|
||||||
|
): Promise<ProjectOutput> {
|
||||||
|
const { inPlace, acceptedIds, activeMerges, rejected } = decision;
|
||||||
|
const accepted = new Set(acceptedIds);
|
||||||
|
const acceptedHits = preview.hits.filter((hit) => accepted.has(hit.id));
|
||||||
|
if (acceptedHits.length !== accepted.size) throw new Error("Die Auswahl passt nicht mehr zur gespeicherten Vorschau.");
|
||||||
|
let directory: string | undefined;
|
||||||
|
let publishedCopyPath: string | undefined;
|
||||||
|
let persisted = false;
|
||||||
|
let keepRecoveryDirectory = false;
|
||||||
|
try {
|
||||||
|
if ((await listRuns(root))[0]?.run.id !== preview.baseRunId) {
|
||||||
|
throw new Error("Seit der Vorschau wurde ein neuer Projektstand gespeichert. Bitte erneut analysieren.");
|
||||||
|
}
|
||||||
|
const created = await createRun(root);
|
||||||
|
directory = created.directory;
|
||||||
|
const { run } = created;
|
||||||
|
run.mapping = mappingForSelection(preview.mapping, preview.previousMapping,
|
||||||
|
acceptedHits, activeMerges);
|
||||||
|
run.entityTypes = [...preview.entityTypes];
|
||||||
|
run.customTermCoverage = preview.customTermCoverage;
|
||||||
|
run.imagePolicy = preview.imagePolicy;
|
||||||
|
run.sourceState = {};
|
||||||
|
run.commentAuthorCoverage = preview.entityTypes.includes("PERSON");
|
||||||
|
run.reviewAuthorCoverage = preview.entityTypes.includes("PERSON");
|
||||||
|
run.matchModes = preview.matchModes;
|
||||||
|
run.sourceInPlace = preview.sourceInPlace || inPlace;
|
||||||
|
const usedPaths = new Set<string>();
|
||||||
|
const replacements: RunFile[] = [];
|
||||||
|
const sources = new Map<string, string>();
|
||||||
|
const total = preview.retained.length + preview.drafts.length;
|
||||||
|
let processed = 0;
|
||||||
|
for (const retained of preview.retained) {
|
||||||
|
progress(`Ausgaben vorbereiten: ${++processed}/${total}`);
|
||||||
|
sources.set(retained.file.relPath, retained.hash);
|
||||||
|
if (await hashProjectFile(retained.file.absPath) !== retained.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${retained.file.relPath}`);
|
||||||
|
const relPath = retained.output;
|
||||||
|
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
||||||
|
usedPaths.add(relPath);
|
||||||
|
const target = resolveWithin(join(directory, "files"), relPath);
|
||||||
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.copyFile(resolveWithin(join(retained.directory, "files"), retained.output), target,
|
||||||
|
fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
|
||||||
|
await fs.chmod(target, 0o600);
|
||||||
|
const file: RunFile = { source: retained.file.relPath, output: relPath, kind: retained.file.kind, imageReport: retained.imageReport, localDocx: retained.localDocx };
|
||||||
|
run.files.push(file);
|
||||||
|
run.sourceState[inPlace ? relPath : file.source] = {
|
||||||
|
hash: inPlace ? await hashProjectFile(target) : retained.hash, output: relPath,
|
||||||
|
};
|
||||||
|
// A prior copy-only run did not change the source files. Switching to in-place
|
||||||
|
// must install its reviewed outputs even when their names are unchanged.
|
||||||
|
if (file.source !== file.output || (inPlace && !preview.sourceInPlace)) replacements.push(file);
|
||||||
|
}
|
||||||
|
for (const draft of preview.drafts) {
|
||||||
|
progress(`Ausgaben vorbereiten: ${++processed}/${total}`);
|
||||||
|
sources.set(draft.file.relPath, draft.hash);
|
||||||
|
if (await hashProjectFile(draft.file.absPath) !== draft.hash) throw new Error(`Datei wurde seit der Vorschau geändert: ${draft.file.relPath}`);
|
||||||
|
const relPath = outputPath(draft.file.relPath, preview.paths, accepted,
|
||||||
|
draft.file.kind === "document", activeMerges);
|
||||||
|
if (usedPaths.has(relPath)) throw new Error(`Zwei Dateien hätten denselben Ausgabenamen: ${relPath}`);
|
||||||
|
usedPaths.add(relPath);
|
||||||
|
const target = resolveWithin(join(directory, "files"), relPath);
|
||||||
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
|
let outputHash: string;
|
||||||
|
let imageReport: DocumentImageReport | undefined;
|
||||||
|
if (draft.docxSegmentCount !== undefined) {
|
||||||
|
imageReport = await writeDocx(assets, draft.file.absPath, target, draft.hash, preview.imagePolicy,
|
||||||
|
draft.docxSegmentCount, withPersonMerges(draft.hits, activeMerges), accepted);
|
||||||
|
outputHash = await hashProjectFile(target);
|
||||||
|
} else if (draft.file.kind === "document") {
|
||||||
|
const data = await fs.readFile(draft.file.absPath);
|
||||||
|
const idPrefix = `${draft.file.relPath}:document:`;
|
||||||
|
const reviewed = draft.hits.map((hit) => ({ ...hit, id: hit.id.slice(idPrefix.length) }));
|
||||||
|
let docIds = draft.hits.filter((hit) => accepted.has(hit.id)).map((hit) => hit.id.slice(idPrefix.length));
|
||||||
|
const masks = forceMasks(withoutWhitelistedRules(rules, whitelist));
|
||||||
|
let result;
|
||||||
|
try {
|
||||||
|
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||||
|
masks, docIds, preview.entityTypes, draft.analysisMapping, preview.imagePolicy);
|
||||||
|
} catch (error) {
|
||||||
|
if (!/\b409\b/.test((error as Error).message) || !/Treffer passen nicht mehr/.test((error as Error).message)) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const refreshed = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||||
|
masks, undefined, preview.entityTypes, undefined, preview.imagePolicy);
|
||||||
|
const ids = reconcileDocumentHitIds(reviewed, docIds, refreshed.hits);
|
||||||
|
if (!ids) throw new Error(`${draft.file.relPath}: Erkennungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
||||||
|
docIds = ids;
|
||||||
|
result = await pseudonymizeDocument(basename(draft.file.relPath), data, run.mapping,
|
||||||
|
masks, docIds, preview.entityTypes, run.mapping, preview.imagePolicy);
|
||||||
|
}
|
||||||
|
const selectedIds = new Set(docIds);
|
||||||
|
const selectedHits = result.hits.filter((hit) => selectedIds.has(hit.id));
|
||||||
|
if (selectedHits.length !== selectedIds.size || selectedHits.some((hit) => !Object.entries(run.mapping)
|
||||||
|
.some(([placeholder, entry]) => entry.type === hit.type
|
||||||
|
&& entry.original.toLocaleLowerCase() === hit.original.toLocaleLowerCase()
|
||||||
|
&& (entry.merged_into ?? placeholder) === hit.placeholder))) {
|
||||||
|
throw new Error(`${draft.file.relPath}: Zuordnungen haben sich seit der Prüfung geändert. Bitte Treffer erneut prüfen.`);
|
||||||
|
}
|
||||||
|
imageReport = checkedImageReport(result, preview.imagePolicy);
|
||||||
|
const output = Buffer.from(result.file_base64, "base64");
|
||||||
|
await fs.writeFile(target, output, { mode: 0o600 });
|
||||||
|
outputHash = digest(output);
|
||||||
|
} else {
|
||||||
|
outputHash = await writeReplacedTextFile(draft.file.absPath, target,
|
||||||
|
withPersonMerges(draft.hits, activeMerges), accepted, draft.hash);
|
||||||
|
}
|
||||||
|
const file: RunFile = { source: draft.file.relPath, output: relPath, kind: draft.file.kind, imageReport,
|
||||||
|
localDocx: draft.docxSegmentCount !== undefined ? true : undefined };
|
||||||
|
run.files.push(file);
|
||||||
|
run.sourceState[inPlace ? relPath : file.source] = {
|
||||||
|
hash: inPlace ? outputHash : draft.hash, output: relPath,
|
||||||
|
};
|
||||||
|
replacements.push(file);
|
||||||
|
}
|
||||||
|
if ((await listRuns(root))[0]?.run.id !== preview.baseRunId) {
|
||||||
|
throw new Error("Seit der Vorschau wurde ein neuer Projektstand gespeichert. Bitte erneut analysieren.");
|
||||||
|
}
|
||||||
|
if (!inPlace) {
|
||||||
|
publishedCopyPath = await publishProjectCopies(run, directory);
|
||||||
|
run.copyPath = publishedCopyPath;
|
||||||
|
}
|
||||||
|
if (inPlace) {
|
||||||
|
if (replacements.length) {
|
||||||
|
// Keep recoverable files if an interrupted replacement needs its backup.
|
||||||
|
keepRecoveryDirectory = true;
|
||||||
|
await replaceProjectFilesInPlace(root, directory, replacements, sources);
|
||||||
|
}
|
||||||
|
run.inPlace = true;
|
||||||
|
}
|
||||||
|
await saveRun(directory, run);
|
||||||
|
persisted = true;
|
||||||
|
if (rejected.length) {
|
||||||
|
const nextWhitelist = [...await loadProjectWhitelist(root), ...rejected];
|
||||||
|
await saveProjectWhitelist(root, nextWhitelist);
|
||||||
|
}
|
||||||
|
return { directory: inPlace && replacements.length ? join(directory, "backup")
|
||||||
|
: inPlace ? root : publishedCopyPath!, inPlace, files: run.files.length,
|
||||||
|
replaced: replacements.length, images: summarizeImages(run.files) };
|
||||||
|
} catch (error) {
|
||||||
|
if (directory && !persisted && !keepRecoveryDirectory) await fs.rm(directory, { recursive: true, force: true });
|
||||||
|
if (publishedCopyPath && !persisted) await fs.rm(publishedCopyPath, { recursive: true, force: true });
|
||||||
|
throw new Error(`${(error as Error).message}${(persisted || keepRecoveryDirectory) && directory ? ` Kopien/Sicherung: ${directory}` : ""}`, { cause: error });
|
||||||
|
}
|
||||||
|
}
|
||||||
17
src/lib/restore-case.ts
Normal file
17
src/lib/restore-case.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
/** Keep the saved spelling for the canonical placeholder and adapt edited case variants. */
|
||||||
|
export function restoreOriginalCase(match: string, key: string, original: string): string {
|
||||||
|
if (match === key) return original;
|
||||||
|
const letters = match.replace(/[^\p{L}]/gu, "");
|
||||||
|
if (!letters) return original;
|
||||||
|
if (letters === letters.toLocaleLowerCase("de")) return original.toLocaleLowerCase("de");
|
||||||
|
if (letters === letters.toLocaleUpperCase("de")) return original.toLocaleUpperCase("de");
|
||||||
|
if (/^\p{Lu}\p{Ll}+$/u.test(letters)) {
|
||||||
|
const originalLetters = original.replace(/[^\p{L}]/gu, "");
|
||||||
|
if (originalLetters && (originalLetters === originalLetters.toLocaleLowerCase("de")
|
||||||
|
|| originalLetters === originalLetters.toLocaleUpperCase("de"))) {
|
||||||
|
return original.toLocaleLowerCase("de").replace(/(^|[^\p{L}])(\p{L})/gu,
|
||||||
|
(_, prefix: string, letter: string) => prefix + letter.toLocaleUpperCase("de"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return original;
|
||||||
|
}
|
||||||
26
src/lib/restore-file-selection.ts
Normal file
26
src/lib/restore-file-selection.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { dirname } from "node:path";
|
||||||
|
import type { ProjectFile } from "./velum-project";
|
||||||
|
|
||||||
|
export type RestorableFolder = { path: string; fileCount: number; textCount: number; documentCount: number };
|
||||||
|
|
||||||
|
export function listRestorableFolders(files: ProjectFile[]): RestorableFolder[] {
|
||||||
|
const folders = new Map<string, RestorableFolder>();
|
||||||
|
for (const file of files) {
|
||||||
|
let path = dirname(file.relPath);
|
||||||
|
while (path !== ".") {
|
||||||
|
const folder = folders.get(path) ?? { path, fileCount: 0, textCount: 0, documentCount: 0 };
|
||||||
|
folder.fileCount++;
|
||||||
|
if (file.kind === "text") folder.textCount++;
|
||||||
|
else folder.documentCount++;
|
||||||
|
folders.set(path, folder);
|
||||||
|
path = dirname(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...folders.values()].sort((a, b) => a.path.localeCompare(b.path, "de"));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectRestorableFolder(files: ProjectFile[], folder: string, includeDocuments = false): Set<string> {
|
||||||
|
const prefix = `${folder}/`;
|
||||||
|
return new Set(files.filter((file) => file.relPath.startsWith(prefix)
|
||||||
|
&& (includeDocuments || file.kind === "text")).map((file) => file.relPath));
|
||||||
|
}
|
||||||
195
src/lib/rich-text.ts
Normal file
195
src/lib/rich-text.ts
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
import type { ProjectRun } from "./velum-project";
|
||||||
|
import { restoreOriginalCase } from "./restore-case";
|
||||||
|
|
||||||
|
function escapeRegExp(value: string): string {
|
||||||
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """)
|
||||||
|
.replace(/'/g, "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeEntities(value: string): string {
|
||||||
|
const named: Record<string, string> = {
|
||||||
|
amp: "&",
|
||||||
|
lt: "<",
|
||||||
|
gt: ">",
|
||||||
|
quot: '"',
|
||||||
|
apos: "'",
|
||||||
|
nbsp: " ",
|
||||||
|
ndash: "–",
|
||||||
|
mdash: "—",
|
||||||
|
hellip: "…",
|
||||||
|
rsquo: "’",
|
||||||
|
lsquo: "‘",
|
||||||
|
rdquo: "”",
|
||||||
|
ldquo: "“",
|
||||||
|
};
|
||||||
|
return value.replace(
|
||||||
|
/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]+);/gi,
|
||||||
|
(entity, code: string) => {
|
||||||
|
if (code.startsWith("#")) {
|
||||||
|
const point =
|
||||||
|
code[1].toLowerCase() === "x"
|
||||||
|
? Number.parseInt(code.slice(2), 16)
|
||||||
|
: Number.parseInt(code.slice(1), 10);
|
||||||
|
return Number.isInteger(point) && point >= 0 && point <= 0x10ffff
|
||||||
|
? String.fromCodePoint(point)
|
||||||
|
: entity;
|
||||||
|
}
|
||||||
|
return named[code.toLowerCase()] ?? entity;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalized(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/\u00a0/g, " ")
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
type HtmlToken = { kind: "tag" | "text"; value: string };
|
||||||
|
|
||||||
|
function tokenizeHtml(html: string): HtmlToken[] | null {
|
||||||
|
const tokens: HtmlToken[] = [];
|
||||||
|
for (let start = 0; start < html.length; ) {
|
||||||
|
if (html[start] !== "<") {
|
||||||
|
const end = html.indexOf("<", start);
|
||||||
|
const next = end < 0 ? html.length : end;
|
||||||
|
tokens.push({ kind: "text", value: html.slice(start, next) });
|
||||||
|
start = next;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (html.startsWith("<!--", start)) {
|
||||||
|
const end = html.indexOf("-->", start + 4);
|
||||||
|
if (end < 0) return null;
|
||||||
|
tokens.push({ kind: "tag", value: html.slice(start, end + 3) });
|
||||||
|
start = end + 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let quote = "";
|
||||||
|
let end = start + 1;
|
||||||
|
for (; end < html.length; end++) {
|
||||||
|
const character = html[end];
|
||||||
|
if (quote) {
|
||||||
|
if (character === quote) quote = "";
|
||||||
|
} else if (character === '"' || character === "'") quote = character;
|
||||||
|
else if (character === ">") break;
|
||||||
|
}
|
||||||
|
if (end === html.length) return null;
|
||||||
|
tokens.push({ kind: "tag", value: html.slice(start, end + 1) });
|
||||||
|
start = end + 1;
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Match = { start: number; end: number; replacement: string };
|
||||||
|
|
||||||
|
function replaceNode(
|
||||||
|
value: string,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
matchModes: ProjectRun["matchModes"],
|
||||||
|
session: boolean,
|
||||||
|
): { value: string; count: number } {
|
||||||
|
const candidates: Match[] = [];
|
||||||
|
const foldedCounts = new Map<string, number>();
|
||||||
|
if (!session) {
|
||||||
|
for (const key of Object.keys(mapping)) {
|
||||||
|
const folded = key.toUpperCase();
|
||||||
|
foldedCounts.set(folded, (foldedCounts.get(folded) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
const stripped = key.replace(/[<>]/g, "");
|
||||||
|
const bare = session ? stripped : key;
|
||||||
|
const boundary =
|
||||||
|
matchModes?.[key] === "anywhere"
|
||||||
|
? escapeRegExp(bare)
|
||||||
|
: `(?<![\\p{L}\\p{N}])${escapeRegExp(bare)}(?![\\p{L}\\p{N}])`;
|
||||||
|
const patterns = [new RegExp(boundary, session ? "gu" : "giu")];
|
||||||
|
if (session) {
|
||||||
|
patterns.unshift(
|
||||||
|
new RegExp(
|
||||||
|
`(?:<|�*60;|�*3c;)${escapeRegExp(stripped)}(?:>|�*62;|�*3e;)`,
|
||||||
|
"giu",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const pattern of patterns) {
|
||||||
|
for (const match of value.matchAll(pattern)) {
|
||||||
|
if (!session && match[0] !== key && (Object.prototype.hasOwnProperty.call(mapping, match[0])
|
||||||
|
|| foldedCounts.get(key.toUpperCase()) !== 1)) continue;
|
||||||
|
candidates.push({
|
||||||
|
start: match.index,
|
||||||
|
end: match.index + match[0].length,
|
||||||
|
replacement: escapeHtml(session ? entry.original : restoreOriginalCase(match[0], key, entry.original)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates.sort((a, b) => a.start - b.start || b.end - a.end);
|
||||||
|
let output = "";
|
||||||
|
let cursor = 0;
|
||||||
|
let count = 0;
|
||||||
|
for (const match of candidates) {
|
||||||
|
if (match.start < cursor) continue;
|
||||||
|
output += value.slice(cursor, match.start) + match.replacement;
|
||||||
|
cursor = match.end;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return { value: output + value.slice(cursor), count };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep the source markup untouched except for verified placeholder text nodes. */
|
||||||
|
export function restoreRichHtml(
|
||||||
|
html: string,
|
||||||
|
sourceText: string,
|
||||||
|
restoredText: string,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
matchModes?: ProjectRun["matchModes"],
|
||||||
|
session = false,
|
||||||
|
): string | undefined {
|
||||||
|
const tokens = tokenizeHtml(html);
|
||||||
|
if (!tokens) return undefined;
|
||||||
|
const ignored = new Set(["head", "script", "style", "title", "noscript"]);
|
||||||
|
const blocks = new Set(["p", "div", "li", "tr", "h1", "h2", "h3", "br"]);
|
||||||
|
let ignoredDepth = 0;
|
||||||
|
let before = "";
|
||||||
|
let after = "";
|
||||||
|
let output = "";
|
||||||
|
for (const token of tokens) {
|
||||||
|
if (token.kind === "tag") {
|
||||||
|
const tag = /^<\s*(\/?)\s*([a-z][\w:-]*)/i.exec(token.value);
|
||||||
|
if (tag) {
|
||||||
|
const name = tag[2].toLowerCase();
|
||||||
|
if (ignored.has(name))
|
||||||
|
ignoredDepth = Math.max(0, ignoredDepth + (tag[1] ? -1 : 1));
|
||||||
|
if (!ignoredDepth && blocks.has(name) && (tag[1] || name === "br")) {
|
||||||
|
before += " ";
|
||||||
|
after += " ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output += token.value;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ignoredDepth) {
|
||||||
|
output += token.value;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
before += decodeEntities(token.value);
|
||||||
|
const replaced = replaceNode(token.value, mapping, matchModes, session);
|
||||||
|
after += decodeEntities(replaced.value);
|
||||||
|
output += replaced.value;
|
||||||
|
}
|
||||||
|
return normalized(before) === normalized(sourceText) &&
|
||||||
|
normalized(after) === normalized(restoredText)
|
||||||
|
? output
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
779
src/lib/velum-project.ts
Normal file
779
src/lib/velum-project.ts
Normal file
@@ -0,0 +1,779 @@
|
|||||||
|
import { hashProjectFile, inspectTextFile } from "./project-text-stream";
|
||||||
|
import { createHash, randomUUID } from "node:crypto";
|
||||||
|
import { constants as fsConstants, promises as fs } from "node:fs";
|
||||||
|
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
||||||
|
import { environment } from "@raycast/api";
|
||||||
|
import type { CustomTerm, EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
||||||
|
import { whitelistKey } from "./project-whitelist";
|
||||||
|
import type { DocumentImageReport, ImagePolicy } from "./image-policy";
|
||||||
|
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||||
|
import { restoreOriginalCase } from "./restore-case";
|
||||||
|
import { mappingForRestoration } from "./mapping-groups";
|
||||||
|
|
||||||
|
export { whitelistKey } from "./project-whitelist";
|
||||||
|
export type { ProjectWhitelistEntry } from "./project-whitelist";
|
||||||
|
|
||||||
|
export type ProjectRule = CustomTerm;
|
||||||
|
export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
|
||||||
|
export type SkippedProjectFile = { path: string; reason: string };
|
||||||
|
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport; localDocx?: true };
|
||||||
|
export type ProjectRun = {
|
||||||
|
version: 2;
|
||||||
|
origin?: "direct" | "imported";
|
||||||
|
id: string;
|
||||||
|
projectPath: string;
|
||||||
|
projectName: string;
|
||||||
|
createdAt: string;
|
||||||
|
mapping: PlaceholderMapping;
|
||||||
|
/** Categories actually used to analyze the files in this snapshot. */
|
||||||
|
entityTypes?: EntityType[];
|
||||||
|
customTermCoverage?: string;
|
||||||
|
/** Explicit image handling applied to documents in this snapshot. Unknown means reprocess. */
|
||||||
|
imagePolicy?: ImagePolicy;
|
||||||
|
/** Hash of each live project file and its immutable output in this run. */
|
||||||
|
sourceState?: Record<string, { hash: string; output: string }>;
|
||||||
|
/** Generic replacement mode for placeholders embedded in code identifiers. */
|
||||||
|
matchModes?: Record<string, "token" | "anywhere">;
|
||||||
|
files: RunFile[];
|
||||||
|
inPlace?: boolean;
|
||||||
|
/** The project source already contains outputs of an earlier in-place run. */
|
||||||
|
sourceInPlace?: boolean;
|
||||||
|
/** Previous immutable snapshot when a project run was revised after creation. */
|
||||||
|
revisedFrom?: string;
|
||||||
|
/** Word comment authors were reviewed with the explicit author recognizer. */
|
||||||
|
commentAuthorCoverage?: boolean;
|
||||||
|
/** Word tracked-change authors and deleted text were reviewed. */
|
||||||
|
reviewAuthorCoverage?: boolean;
|
||||||
|
/** Visible copy next to the source project; immutable snapshots remain in Raycast support. */
|
||||||
|
copyPath?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DOCUMENTS = new Set([".docx", ".xlsx", ".pptx", ".pdf"]);
|
||||||
|
const RESTORABLE_DOCUMENTS = new Set([".docx", ".xlsx", ".pptx"]);
|
||||||
|
const MARKDOWN_EXTENSIONS = new Set([".md", ".markdown", ".mdx"]);
|
||||||
|
const SECRET_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
|
||||||
|
const EXCLUDES = new Set([".git", "node_modules", "dist", "build", "out", ".next", ".nuxt",
|
||||||
|
".venv", "venv", "__pycache__", "target", "vendor", "coverage", ".cache", ".turbo",
|
||||||
|
".idea", ".vscode", "Pods", "DerivedData"]);
|
||||||
|
|
||||||
|
export function canonicalProjectPath(path: string): string {
|
||||||
|
return resolve(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
function projectIdFor(path: string): string {
|
||||||
|
return createHash("sha1").update(canonicalProjectPath(path)).digest("hex").slice(0, 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function isBinary(path: string): Promise<boolean> {
|
||||||
|
const file = await fs.open(path, "r");
|
||||||
|
try {
|
||||||
|
const buffer = Buffer.alloc(8192);
|
||||||
|
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
||||||
|
return buffer.subarray(0, bytesRead).includes(0);
|
||||||
|
} finally { await file.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function isOfficeArchive(path: string): Promise<boolean> {
|
||||||
|
const file = await fs.open(path, "r");
|
||||||
|
try {
|
||||||
|
const header = Buffer.alloc(4);
|
||||||
|
const { bytesRead } = await file.read(header, 0, header.length, 0);
|
||||||
|
return bytesRead === 4 && header.equals(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
||||||
|
} finally { await file.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectDataRoot(projectPath: string, support = environment.supportPath): string {
|
||||||
|
return join(support, "velum-projects", projectIdFor(projectPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rulesPath(projectPath: string, support = environment.supportPath): string {
|
||||||
|
return join(projectDataRoot(projectPath, support), "rules.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function whitelistPath(projectPath: string, support = environment.supportPath): string {
|
||||||
|
return join(projectDataRoot(projectPath, support), "whitelist.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function entityTypesPath(projectPath: string, support = environment.supportPath): string {
|
||||||
|
return join(projectDataRoot(projectPath, support), "entity-types.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fileExclusionsPath(projectPath: string, support = environment.supportPath): string {
|
||||||
|
return join(projectDataRoot(projectPath, support), "excluded-files.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkedFileExclusions(value: unknown): string[] {
|
||||||
|
if (!Array.isArray(value) || value.some((path) => typeof path !== "string")) {
|
||||||
|
throw new Error("Ungültige Dateiauswahl für dieses Projekt.");
|
||||||
|
}
|
||||||
|
try { return [...new Set(value.map((path: string) => safeRelativePath(path)))]; }
|
||||||
|
catch { throw new Error("Ungültiger Dateipfad in der Projektauswahl."); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadProjectFileExclusions(projectPath: string, support?: string): Promise<string[]> {
|
||||||
|
try {
|
||||||
|
return checkedFileExclusions(JSON.parse(await fs.readFile(fileExclusionsPath(projectPath, support), "utf8")));
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveProjectFileExclusions(projectPath: string, paths: string[], support?: string): Promise<void> {
|
||||||
|
const unique = checkedFileExclusions(paths);
|
||||||
|
const path = fileExclusionsPath(projectPath, support);
|
||||||
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||||
|
const temp = `${path}.${randomUUID()}.tmp`;
|
||||||
|
try {
|
||||||
|
await fs.writeFile(temp, JSON.stringify(unique), { encoding: "utf8", mode: 0o600 });
|
||||||
|
await fs.rename(temp, path);
|
||||||
|
} catch (error) {
|
||||||
|
await fs.rm(temp, { force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withoutExcludedProjectFiles(files: ProjectFile[], excluded: readonly string[]): ProjectFile[] {
|
||||||
|
const paths = new Set(excluded);
|
||||||
|
return files.filter((file) => !paths.has(file.relPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadProjectEntityTypes(projectPath: string, support?: string): Promise<EntityType[] | null> {
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(await fs.readFile(entityTypesPath(projectPath, support), "utf8")) as unknown;
|
||||||
|
if (!Array.isArray(value) || value.some((type) => typeof type !== "string" || !type)) {
|
||||||
|
throw new Error("Ungültige Kategorienauswahl für dieses Projekt.");
|
||||||
|
}
|
||||||
|
return [...new Set(value)];
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveProjectEntityTypes(projectPath: string, types: EntityType[], support?: string): Promise<void> {
|
||||||
|
const path = entityTypesPath(projectPath, support);
|
||||||
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||||
|
const temp = `${path}.${randomUUID()}.tmp`;
|
||||||
|
try {
|
||||||
|
await fs.writeFile(temp, JSON.stringify([...new Set(types)]), { encoding: "utf8", mode: 0o600 });
|
||||||
|
await fs.rename(temp, path);
|
||||||
|
} catch (error) {
|
||||||
|
await fs.rm(temp, { force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadProjectWhitelist(projectPath: string, support?: string): Promise<ProjectWhitelistEntry[]> {
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(await fs.readFile(whitelistPath(projectPath, support), "utf8")) as unknown;
|
||||||
|
if (!Array.isArray(value)) throw new Error("Ungültige Projekt-Whitelist.");
|
||||||
|
return value.filter((entry): entry is ProjectWhitelistEntry => Boolean(entry) && typeof entry === "object"
|
||||||
|
&& typeof entry.type === "string" && typeof entry.original === "string"
|
||||||
|
&& entry.type.length > 0 && entry.original.trim().length > 0);
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveProjectWhitelist(projectPath: string, entries: ProjectWhitelistEntry[], support?: string): Promise<void> {
|
||||||
|
const unique = [...new Map(entries.map((entry) => [whitelistKey(entry),
|
||||||
|
{ type: entry.type.toUpperCase(), original: entry.original.trim() }])).values()];
|
||||||
|
const path = whitelistPath(projectPath, support);
|
||||||
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||||
|
const temp = `${path}.${randomUUID()}.tmp`;
|
||||||
|
try {
|
||||||
|
await fs.writeFile(temp, JSON.stringify(unique), { encoding: "utf8", mode: 0o600 });
|
||||||
|
await fs.rename(temp, path);
|
||||||
|
} catch (error) {
|
||||||
|
await fs.rm(temp, { force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadProjectRules(projectPath: string, support?: string): Promise<ProjectRule[]> {
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(await fs.readFile(rulesPath(projectPath, support), "utf8")) as unknown;
|
||||||
|
return Array.isArray(value) ? value.filter(isProjectRule) : [];
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isProjectRule(value: unknown): value is ProjectRule {
|
||||||
|
if (!value || typeof value !== "object") return false;
|
||||||
|
const rule = value as Record<string, unknown>;
|
||||||
|
return typeof rule.type === "string" && /^[A-Z][A-Z0-9_]*$/.test(rule.type)
|
||||||
|
&& typeof rule.value === "string" && rule.value.trim().length >= 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseProjectRules(input: string,
|
||||||
|
entityTypes: readonly string[] = ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"]): ProjectRule[] {
|
||||||
|
const allowed = new Set(entityTypes);
|
||||||
|
const rules = input.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
|
||||||
|
const match = /^([A-Z][A-Z0-9_]*):\s*(.+)$/i.exec(line);
|
||||||
|
const type = match?.[1].toUpperCase();
|
||||||
|
return match && type && allowed.has(type)
|
||||||
|
? { type, value: match[2].trim() }
|
||||||
|
: { type: "BEGRIFF" as const, value: line };
|
||||||
|
});
|
||||||
|
if (rules.length > 500 || rules.some((rule) => !validCustomTerm(rule.value))) {
|
||||||
|
throw new Error("Maximal 500 Begriffe mit jeweils 2 bis 200 Zeichen sind erlaubt.");
|
||||||
|
}
|
||||||
|
return rules.filter((rule, index) => rules.findIndex(
|
||||||
|
(other) => other.type === rule.type && other.value.toLocaleLowerCase() === rule.value.toLocaleLowerCase(),
|
||||||
|
) === index);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validCustomTerm(value: string): boolean {
|
||||||
|
const length = Array.from(value.trim()).length;
|
||||||
|
return length >= 2 && length <= 200;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveProjectRules(projectPath: string, rules: ProjectRule[], support?: string): Promise<void> {
|
||||||
|
const path = rulesPath(projectPath, support);
|
||||||
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||||
|
const temp = `${path}.${randomUUID()}.tmp`;
|
||||||
|
try {
|
||||||
|
await fs.writeFile(temp, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 });
|
||||||
|
await fs.rename(temp, path);
|
||||||
|
} finally {
|
||||||
|
await fs.rm(temp, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
||||||
|
const result: Record<string, string[]> = {};
|
||||||
|
for (const rule of rules) (result[rule.type] ??= []).push(rule.value);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function scanProjectFiles(root: string, maxSize?: number,
|
||||||
|
validateText = true, documentLimits: Readonly<Record<string, number>> = {}): Promise<{
|
||||||
|
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||||
|
}> {
|
||||||
|
const files: ProjectFile[] = [];
|
||||||
|
const skipped: SkippedProjectFile[] = [];
|
||||||
|
const skip = (path: string, reason: string) => skipped.push({ path, reason });
|
||||||
|
async function walk(directory: string): Promise<void> {
|
||||||
|
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
|
||||||
|
const path = join(directory, entry.name);
|
||||||
|
const relPath = relative(root, path).split(sep).join("/");
|
||||||
|
if (entry.isSymbolicLink()) { skip(relPath, "Symbolischer Link"); continue; }
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
if (EXCLUDES.has(entry.name)) { skip(relPath, "Ausgeschlossener Ordner"); continue; }
|
||||||
|
await walk(path);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!entry.isFile()) continue;
|
||||||
|
if (entry.name.startsWith("~$") || entry.name.startsWith("._")) {
|
||||||
|
skip(relPath, "Temporäre Office-/macOS-Datei");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (entry.name === ".env" || entry.name.startsWith(".env.") || SECRET_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
|
||||||
|
skip(relPath, "Vertraulicher Dateityp");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const stat = await fs.stat(path);
|
||||||
|
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
||||||
|
const limit = maxSize ?? (kind === "document"
|
||||||
|
? documentLimits[extname(path).toLowerCase()] ?? 20 * 1024 * 1024 : Number.POSITIVE_INFINITY);
|
||||||
|
if (stat.size > limit) { skip(relPath, `Datei zu groß (Grenze: ${limit / 1024 / 1024} MiB)`); continue; }
|
||||||
|
if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) {
|
||||||
|
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (kind === "text" && validateText) {
|
||||||
|
if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; }
|
||||||
|
try { await inspectTextFile(path); }
|
||||||
|
catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; }
|
||||||
|
}
|
||||||
|
files.push({ relPath, absPath: path, kind, size: stat.size });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await walk(root);
|
||||||
|
files.sort((a, b) => a.relPath.localeCompare(b.relPath));
|
||||||
|
return { files, skipped };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function digest(data: Buffer): string {
|
||||||
|
return createHash("sha256").update(data).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Python API spans count Unicode code points; JavaScript strings use UTF-16 offsets. */
|
||||||
|
export function toUtf16Offsets<T extends { start: number; end: number }>(text: string, spans: T[]): T[] {
|
||||||
|
const positions = [0];
|
||||||
|
let offset = 0;
|
||||||
|
for (const character of text) {
|
||||||
|
offset += character.length;
|
||||||
|
positions.push(offset);
|
||||||
|
}
|
||||||
|
return spans.map((span) => {
|
||||||
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|
||||||
|
|| span.start < 0 || span.end > positions.length - 1 || span.start >= span.end) {
|
||||||
|
throw new Error("Ungültige Trefferposition der Velum-API.");
|
||||||
|
}
|
||||||
|
return { ...span, start: positions[span.start], end: positions[span.end] };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function replaceSpans(
|
||||||
|
source: string,
|
||||||
|
spans: Array<{ start: number; end: number; placeholder: string; id: string }>,
|
||||||
|
accepted: Set<string>,
|
||||||
|
): string {
|
||||||
|
let output = source;
|
||||||
|
for (const span of [...spans].filter((item) => accepted.has(item.id)).sort((a, b) => b.start - a.start)) {
|
||||||
|
if (span.start < 0 || span.end > source.length || span.start >= span.end) throw new Error("Ungültige Trefferposition.");
|
||||||
|
output = output.slice(0, span.start) + span.placeholder + output.slice(span.end);
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["matchModes"], allowEmbedded = false): {
|
||||||
|
pattern: RegExp; originalFor: (match: string) => string | undefined;
|
||||||
|
} | undefined {
|
||||||
|
const keys = Object.keys(mapping).sort((a, b) => b.length - a.length);
|
||||||
|
if (!keys.length) return undefined;
|
||||||
|
const foldedKeys = new Map<string, string | null>();
|
||||||
|
for (const key of keys) {
|
||||||
|
const folded = key.toUpperCase();
|
||||||
|
if (foldedKeys.has(folded)) foldedKeys.set(folded, null);
|
||||||
|
else foldedKeys.set(folded, key);
|
||||||
|
}
|
||||||
|
const parts = keys.map((key) => {
|
||||||
|
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
return allowEmbedded || matchModes?.[key] === "anywhere"
|
||||||
|
? `${escaped}(?!\\d)` : `(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
pattern: new RegExp(parts.join("|"), "giu"),
|
||||||
|
originalFor: (match) => {
|
||||||
|
const key = Object.prototype.hasOwnProperty.call(mapping, match)
|
||||||
|
? match : foldedKeys.get(match.toUpperCase());
|
||||||
|
return key ? restoreOriginalCase(match, key, mapping[key].original) : undefined;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restoreTextWithCount(source: string, mapping: PlaceholderMapping,
|
||||||
|
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): { text: string; replacements: number } {
|
||||||
|
const pattern = restorePattern(mapping, matchModes, allowEmbedded);
|
||||||
|
let replacements = 0;
|
||||||
|
const text = pattern ? source.replace(pattern.pattern, (match) => {
|
||||||
|
const original = pattern.originalFor(match);
|
||||||
|
if (original === undefined) return match;
|
||||||
|
replacements++;
|
||||||
|
return original;
|
||||||
|
}) : source;
|
||||||
|
return { text, replacements };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restoreText(source: string, mapping: PlaceholderMapping,
|
||||||
|
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): string {
|
||||||
|
return restoreTextWithCount(source, mapping, matchModes, allowEmbedded).text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Older snapshots can supply a missing key only when its meaning never changed. */
|
||||||
|
export function withUnambiguousHistoricalMappings(current: PlaceholderMapping,
|
||||||
|
earlier: PlaceholderMapping[]): PlaceholderMapping {
|
||||||
|
const result = { ...current };
|
||||||
|
const candidates = new Map<string, PlaceholderMapping[string] | null>();
|
||||||
|
for (const mapping of earlier) {
|
||||||
|
for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(current, key)) continue;
|
||||||
|
const previous = candidates.get(key);
|
||||||
|
if (previous === null) continue;
|
||||||
|
if (previous && (previous.original !== entry.original || previous.type !== entry.type)) {
|
||||||
|
candidates.set(key, null);
|
||||||
|
} else if (!previous) candidates.set(key, entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [key, entry] of candidates) if (entry) result[key] = entry;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Report recognizable Velum IDs that remain after a Markdown restore. */
|
||||||
|
export function unresolvedPlaceholderIds(source: string, mappings: PlaceholderMapping[]): string[] {
|
||||||
|
const prefixes = new Set(mappings.flatMap((mapping) => Object.keys(mapping)
|
||||||
|
.map((key) => /^([\p{L}]+)_\d+$/u.exec(key)?.[1]).filter((value): value is string => Boolean(value))));
|
||||||
|
if (!prefixes.size) return [];
|
||||||
|
const alternatives = [...prefixes].sort((a, b) => b.length - a.length)
|
||||||
|
.map((prefix) => prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
||||||
|
const pattern = new RegExp(`(?<![\\p{L}\\p{N}])(?:${alternatives.join("|")})_\\d+(?!\\d)`, "giu");
|
||||||
|
return [...new Set(source.match(pattern) ?? [])];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restorePath(relPath: string, mapping: PlaceholderMapping, matchModes?: ProjectRun["matchModes"]): string {
|
||||||
|
// Filenames can join a placeholder directly to another identifier fragment.
|
||||||
|
// Restricting replacements to word boundaries would leave those names masked.
|
||||||
|
const pattern = restorePattern(mapping, matchModes, true);
|
||||||
|
const segments = safeRelativePath(relPath).split("/").map((segment) => {
|
||||||
|
const restored = pattern ? segment.replace(pattern.pattern, (match) => pattern.originalFor(match) ?? match) : segment;
|
||||||
|
if (restored.includes("/") || restored.includes("\\") || restored === "." || restored === "..") {
|
||||||
|
throw new Error("Rückübersetzter Dateiname enthält einen ungültigen Pfadteil.");
|
||||||
|
}
|
||||||
|
return restored;
|
||||||
|
});
|
||||||
|
return safeRelativePath(segments.join("/"));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function safeRelativePath(path: string): string {
|
||||||
|
const normalized = path.split("\\").join("/");
|
||||||
|
if (!normalized || normalized.startsWith("/") || normalized.split("/").some((part) => part === ".." || part === "." || !part)) {
|
||||||
|
throw new Error("Ungültiger Ausgabepfad.");
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createRun(projectPath: string, support = environment.supportPath): Promise<{
|
||||||
|
run: ProjectRun; directory: string;
|
||||||
|
}> {
|
||||||
|
projectPath = canonicalProjectPath(projectPath);
|
||||||
|
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`;
|
||||||
|
const directory = join(projectDataRoot(projectPath, support), "runs", id);
|
||||||
|
await fs.mkdir(join(directory, "files"), { recursive: true, mode: 0o700 });
|
||||||
|
return {
|
||||||
|
directory,
|
||||||
|
run: { version: 2, origin: "direct", id, projectPath, projectName: basename(projectPath),
|
||||||
|
createdAt: new Date().toISOString(), mapping: {}, files: [] },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveRun(directory: string, run: ProjectRun): Promise<void> {
|
||||||
|
const dest = join(directory, "run.json");
|
||||||
|
const tmp = `${dest}.tmp`;
|
||||||
|
await fs.writeFile(tmp, JSON.stringify(run), { encoding: "utf8", mode: 0o600 });
|
||||||
|
await fs.rename(tmp, dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function prepareManualMappingEntry(current: PlaceholderMapping, earlier: PlaceholderMapping[],
|
||||||
|
input: { original: string; type: string; placeholder?: string }): { placeholder: string; entry: MappingEntry } {
|
||||||
|
const original = input.original.trim();
|
||||||
|
const type = input.type.trim().toUpperCase();
|
||||||
|
if (!original) throw new Error("Bitte einen Klartext-Begriff eingeben.");
|
||||||
|
if (!/^[A-ZÄÖÜ][A-ZÄÖÜ0-9_]*$/u.test(type)) throw new Error("Ungültige Kategorie.");
|
||||||
|
if (Object.values(current).some((entry) => entry.type === type
|
||||||
|
&& entry.original.toLocaleLowerCase("de") === original.toLocaleLowerCase("de"))) {
|
||||||
|
throw new Error("Dieser Begriff ist in der Kategorie bereits vorhanden.");
|
||||||
|
}
|
||||||
|
const known = [current, ...earlier];
|
||||||
|
const keys = known.flatMap((mapping) => Object.keys(mapping));
|
||||||
|
const placeholderPattern = new RegExp(`^${type}_(\\d+)$`, "u");
|
||||||
|
const placeholder = input.placeholder?.trim().toUpperCase() || (() => {
|
||||||
|
const max = keys.reduce((currentMax, key) => Math.max(currentMax,
|
||||||
|
Number(placeholderPattern.exec(key)?.[1] ?? 0)), 0);
|
||||||
|
return `${type}_${String(max + 1).padStart(2, "0")}`;
|
||||||
|
})();
|
||||||
|
if (!placeholderPattern.test(placeholder)) {
|
||||||
|
throw new Error("Platzhalter muss zur Kategorie passen, z. B. PERSON_61.");
|
||||||
|
}
|
||||||
|
if (Object.keys(current).some((key) => key.toUpperCase() === placeholder)) {
|
||||||
|
throw new Error("Dieser Platzhalter ist im aktuellen Stand bereits belegt.");
|
||||||
|
}
|
||||||
|
for (const mapping of earlier) for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
if (key.toUpperCase() === placeholder && (entry.type !== type || entry.original !== original)) {
|
||||||
|
throw new Error("Dieser Platzhalter hatte früher eine andere Bedeutung. Bitte die betroffene Datei einzeln zuordnen.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { placeholder, entry: { original, type } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Save a mapping correction as a new immutable project stand without rewriting project files. */
|
||||||
|
export async function updateProjectMapping(projectPath: string,
|
||||||
|
change: (current: PlaceholderMapping, earlier: PlaceholderMapping[]) => PlaceholderMapping,
|
||||||
|
support = environment.supportPath): Promise<ProjectRun> {
|
||||||
|
const entries = await listRuns(projectPath, support);
|
||||||
|
const latest = entries[0];
|
||||||
|
if (!latest) throw new Error("Für dieses Projekt gibt es noch keinen gespeicherten Stand.");
|
||||||
|
const mapping = change(latest.run.mapping, entries.slice(1).map((saved) => saved.run.mapping));
|
||||||
|
const created = await createRun(projectPath, support);
|
||||||
|
const { run, directory } = created;
|
||||||
|
run.createdAt = new Date(Math.max(Date.now(), Date.parse(latest.run.createdAt) + 1)).toISOString();
|
||||||
|
run.origin = latest.run.origin;
|
||||||
|
run.revisedFrom = latest.run.id;
|
||||||
|
run.mapping = mapping;
|
||||||
|
run.entityTypes = latest.run.entityTypes ? [...latest.run.entityTypes] : undefined;
|
||||||
|
run.customTermCoverage = latest.run.customTermCoverage;
|
||||||
|
run.matchModes = { ...latest.run.matchModes };
|
||||||
|
run.files = latest.run.files.map((file) => ({ ...file }));
|
||||||
|
run.sourceState = latest.run.sourceState ? { ...latest.run.sourceState } : undefined;
|
||||||
|
run.inPlace = latest.run.inPlace;
|
||||||
|
run.sourceInPlace = latest.run.sourceInPlace;
|
||||||
|
run.commentAuthorCoverage = latest.run.commentAuthorCoverage;
|
||||||
|
run.reviewAuthorCoverage = latest.run.reviewAuthorCoverage;
|
||||||
|
run.copyPath = latest.run.copyPath;
|
||||||
|
try {
|
||||||
|
for (const file of run.files) {
|
||||||
|
const source = resolveWithin(join(latest.directory, "files"), file.output);
|
||||||
|
const target = resolveWithin(join(directory, "files"), file.output);
|
||||||
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.copyFile(source, target, fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
|
||||||
|
await fs.chmod(target, 0o600);
|
||||||
|
}
|
||||||
|
if ((await listRuns(projectPath, support))[0]?.run.id !== latest.run.id) {
|
||||||
|
throw new Error("Es gibt bereits einen neueren Projektstand. Bitte die Liste aktualisieren.");
|
||||||
|
}
|
||||||
|
await saveRun(directory, run);
|
||||||
|
} catch (error) {
|
||||||
|
await fs.rm(directory, { recursive: true, force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addProjectMappingEntry(projectPath: string,
|
||||||
|
input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise<ProjectRun> {
|
||||||
|
return updateProjectMapping(projectPath, (current, earlier) => {
|
||||||
|
const { placeholder, entry } = prepareManualMappingEntry(current, earlier, input);
|
||||||
|
return { ...current, [placeholder]: entry };
|
||||||
|
}, support);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runCopiesPath(run: ProjectRun, directory: string): string {
|
||||||
|
return run.copyPath ?? join(directory, "files");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function scanRestorableCopyFiles(run: ProjectRun, directory: string, current = true): Promise<{
|
||||||
|
root: string; files: ProjectFile[]; skipped: number;
|
||||||
|
}> {
|
||||||
|
const inPlace = Boolean(run.inPlace || run.sourceInPlace);
|
||||||
|
let root = current && inPlace ? canonicalProjectPath(run.projectPath)
|
||||||
|
: current ? runCopiesPath(run, directory) : join(directory, "files");
|
||||||
|
if (current && !inPlace && run.copyPath) {
|
||||||
|
try {
|
||||||
|
if (!(await fs.lstat(root)).isDirectory()) throw new Error("Kopienpfad ist kein regulärer Ordner.");
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||||
|
root = join(directory, "files");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// XLSX restoration runs locally as a stream and does not upload the file.
|
||||||
|
const scan = await scanProjectFiles(root, undefined, true, { ".xlsx": Number.POSITIVE_INFINITY });
|
||||||
|
const files = scan.files.filter((file) => file.kind === "text" || isRestorableDocument(file.relPath));
|
||||||
|
return { root, files, skipped: scan.skipped.length + scan.files.length - files.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Publish only output files next to the project, without the private mapping. */
|
||||||
|
export async function publishProjectCopies(run: ProjectRun, directory: string): Promise<string> {
|
||||||
|
const projectPath = canonicalProjectPath(run.projectPath);
|
||||||
|
const parent = dirname(projectPath);
|
||||||
|
const target = join(parent, `${basename(projectPath)}-Velum-${run.id}`);
|
||||||
|
try {
|
||||||
|
await fs.lstat(target);
|
||||||
|
throw new Error(`Kopienordner bereits vorhanden: ${target}`);
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||||
|
}
|
||||||
|
const staging = await fs.mkdtemp(join(parent, `.${basename(projectPath)}-Velum-`));
|
||||||
|
try {
|
||||||
|
for (const file of run.files) {
|
||||||
|
const source = resolveWithin(join(directory, "files"), file.output);
|
||||||
|
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Ausgabedatei: ${file.output}`);
|
||||||
|
const destination = resolveWithin(staging, file.output);
|
||||||
|
await fs.mkdir(dirname(destination), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.copyFile(source, destination, fsConstants.COPYFILE_EXCL);
|
||||||
|
await fs.chmod(destination, 0o600);
|
||||||
|
}
|
||||||
|
await fs.rename(staging, target);
|
||||||
|
return target;
|
||||||
|
} catch (error) {
|
||||||
|
await fs.rm(staging, { recursive: true, force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listRuns(projectPath: string, support = environment.supportPath): Promise<Array<{
|
||||||
|
run: ProjectRun; directory: string;
|
||||||
|
}>> {
|
||||||
|
const root = join(projectDataRoot(projectPath, support), "runs");
|
||||||
|
let entries;
|
||||||
|
try { entries = await fs.readdir(root, { withFileTypes: true }); }
|
||||||
|
catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const runs = [];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
const directory = join(root, entry.name);
|
||||||
|
try {
|
||||||
|
const run = JSON.parse(await fs.readFile(join(directory, "run.json"), "utf8")) as ProjectRun;
|
||||||
|
if (run.version === 2 && canonicalProjectPath(run.projectPath) === canonicalProjectPath(projectPath)) {
|
||||||
|
runs.push({ run, directory });
|
||||||
|
}
|
||||||
|
} catch { /* incomplete run: not offered for restoration */ }
|
||||||
|
}
|
||||||
|
return runs.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An unchanged output from an in-place run can be carried into the next snapshot. */
|
||||||
|
export async function matchesPreviousOutput(directory: string, relPath: string, currentHash: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
return await hashProjectFile(resolveWithin(join(directory, "files"), relPath)) === currentHash;
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reuse only an output proven to correspond to the current source bytes. */
|
||||||
|
export async function reusableProjectOutput(run: ProjectRun, directory: string,
|
||||||
|
relPath: string, currentHash: string): Promise<string | undefined> {
|
||||||
|
const state = run.sourceState?.[relPath];
|
||||||
|
if (state) {
|
||||||
|
if (state.hash !== currentHash || !run.files.some((file) => file.output === state.output)) return undefined;
|
||||||
|
try {
|
||||||
|
const output = resolveWithin(join(directory, "files"), state.output);
|
||||||
|
return (await fs.lstat(output)).isFile() ? state.output : undefined;
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Older in-place snapshots lack source hashes. An identical saved output is
|
||||||
|
// still authoritative; copy-mode source bytes cannot be reconstructed.
|
||||||
|
if (!(run.inPlace || run.sourceInPlace) || !run.files.some((file) => file.output === relPath)) return undefined;
|
||||||
|
return await matchesPreviousOutput(directory, relPath, currentHash) ? relPath : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unknown or changed category coverage requires a new review of unchanged files. */
|
||||||
|
export function sameEntityTypeCoverage(run: ProjectRun, selected: readonly EntityType[]): boolean {
|
||||||
|
if (!Array.isArray(run.entityTypes)) return false;
|
||||||
|
const covered = new Set(run.entityTypes);
|
||||||
|
return covered.size === new Set(selected).size && selected.every((type) => covered.has(type));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only an identical saved file can disambiguate a placeholder reused across runs. */
|
||||||
|
export async function mappingForMatchingSnapshots(relPath: string, currentHash: string,
|
||||||
|
earlier: Array<{ run: ProjectRun; directory: string }>): Promise<PlaceholderMapping> {
|
||||||
|
const matching = await Promise.all(earlier.filter(({ run }) =>
|
||||||
|
run.files.some((file) => file.output === relPath))
|
||||||
|
.map(async ({ run, directory }) => await matchesPreviousOutput(directory, relPath, currentHash)
|
||||||
|
? mappingForRestoration(run.mapping) : undefined));
|
||||||
|
return withUnambiguousHistoricalMappings({},
|
||||||
|
matching.filter((mapping): mapping is PlaceholderMapping => Boolean(mapping)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listAllRuns(support = environment.supportPath): Promise<Array<{
|
||||||
|
run: ProjectRun; directory: string;
|
||||||
|
}>> {
|
||||||
|
const root = join(support, "velum-projects");
|
||||||
|
let projects;
|
||||||
|
try { projects = await fs.readdir(root, { withFileTypes: true }); }
|
||||||
|
catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const results = [];
|
||||||
|
for (const project of projects) {
|
||||||
|
if (!project.isDirectory()) continue;
|
||||||
|
const runsDir = join(root, project.name, "runs");
|
||||||
|
let entries;
|
||||||
|
try { entries = await fs.readdir(runsDir, { withFileTypes: true }); }
|
||||||
|
catch { continue; }
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isDirectory()) continue;
|
||||||
|
const directory = join(runsDir, entry.name);
|
||||||
|
try {
|
||||||
|
const run = JSON.parse(await fs.readFile(join(directory, "run.json"), "utf8")) as ProjectRun;
|
||||||
|
if (run.version === 2) results.push({ run, directory });
|
||||||
|
} catch { /* incomplete run */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return results.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isRestorableDocument(filename: string): boolean {
|
||||||
|
return RESTORABLE_DOCUMENTS.has(extname(filename).toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMarkdownFile(filename: string): boolean {
|
||||||
|
return MARKDOWN_EXTENSIONS.has(extname(filename).toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWithin(root: string, relPath: string): string {
|
||||||
|
const target = resolve(root, safeRelativePath(relPath));
|
||||||
|
if (!target.startsWith(resolve(root) + sep)) throw new Error("Ausgabepfad verlässt den Zielordner.");
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertNoSymlinkParents(root: string, relPath: string): Promise<void> {
|
||||||
|
const parts = safeRelativePath(relPath).split("/");
|
||||||
|
let parent = resolve(root);
|
||||||
|
for (const part of parts.slice(0, -1)) {
|
||||||
|
parent = join(parent, part);
|
||||||
|
try {
|
||||||
|
if ((await fs.lstat(parent)).isSymbolicLink()) throw new Error(`Symbolischer Link im Ausgabepfad: ${relPath}`);
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces selected originals only after every output exists and a private backup is complete. */
|
||||||
|
export async function replaceProjectFilesInPlace(projectPath: string, runDirectory: string, files: RunFile[],
|
||||||
|
expectedHashes?: ReadonlyMap<string, string>): Promise<void> {
|
||||||
|
const root = resolve(projectPath);
|
||||||
|
const sourcePaths = new Set(files.map((file) => resolveWithin(root, file.source)));
|
||||||
|
const targetPaths = new Set<string>();
|
||||||
|
const sourceModes = new Map<string, number>();
|
||||||
|
for (const file of files) {
|
||||||
|
const source = resolveWithin(root, file.source);
|
||||||
|
const target = resolveWithin(root, file.output);
|
||||||
|
if (targetPaths.has(target)) throw new Error(`Doppelter Zielname: ${file.output}`);
|
||||||
|
targetPaths.add(target);
|
||||||
|
await assertNoSymlinkParents(root, file.output);
|
||||||
|
const sourceInfo = await fs.lstat(source);
|
||||||
|
if (!sourceInfo.isFile()) throw new Error(`Quelldatei ist keine reguläre Datei: ${file.source}`);
|
||||||
|
sourceModes.set(source, sourceInfo.mode & 0o777);
|
||||||
|
try {
|
||||||
|
await fs.lstat(target);
|
||||||
|
if (!sourcePaths.has(target)) throw new Error(`Zielname bereits vorhanden: ${file.output}`);
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||||
|
}
|
||||||
|
await fs.access(resolveWithin(join(runDirectory, "files"), file.output));
|
||||||
|
}
|
||||||
|
|
||||||
|
const backupRoot = join(runDirectory, "backup");
|
||||||
|
for (const file of files) {
|
||||||
|
const backup = resolveWithin(backupRoot, file.source);
|
||||||
|
await fs.mkdir(dirname(backup), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.copyFile(resolveWithin(root, file.source), backup, fsConstants.COPYFILE_EXCL);
|
||||||
|
await fs.chmod(backup, 0o600);
|
||||||
|
}
|
||||||
|
|
||||||
|
const written: string[] = [];
|
||||||
|
try {
|
||||||
|
for (const file of files) {
|
||||||
|
const source = resolveWithin(root, file.source);
|
||||||
|
if (expectedHashes && await hashProjectFile(source) !== expectedHashes.get(file.source)) {
|
||||||
|
throw new Error(`Projektdatei wurde vor dem Ersetzen erneut geändert: ${file.source}`);
|
||||||
|
}
|
||||||
|
await fs.unlink(source);
|
||||||
|
}
|
||||||
|
for (const file of files) {
|
||||||
|
const target = resolveWithin(root, file.output);
|
||||||
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.copyFile(resolveWithin(join(runDirectory, "files"), file.output), target, fsConstants.COPYFILE_EXCL);
|
||||||
|
written.push(target);
|
||||||
|
await fs.chmod(target, sourceModes.get(resolveWithin(root, file.source)) ?? 0o600);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
for (const target of written) await fs.rm(target, { force: true });
|
||||||
|
for (const file of files) {
|
||||||
|
const source = resolveWithin(root, file.source);
|
||||||
|
try { await fs.lstat(source); }
|
||||||
|
catch (missing) {
|
||||||
|
if ((missing as NodeJS.ErrnoException).code !== "ENOENT") throw missing;
|
||||||
|
await fs.mkdir(dirname(source), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.copyFile(resolveWithin(backupRoot, file.source), source, fsConstants.COPYFILE_EXCL);
|
||||||
|
await fs.chmod(source, sourceModes.get(source) ?? 0o600);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error(`Ersetzen fehlgeschlagen; Originale wurden wiederhergestellt. Sicherung: ${backupRoot}. ${(error as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/lib/worker-runtime.ts
Normal file
21
src/lib/worker-runtime.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import type { NormalizedPreferences } from "../preferences";
|
||||||
|
|
||||||
|
// Only these Raycast services are used by the shared Node project code.
|
||||||
|
export const environment = { assetsPath: "", supportPath: "" };
|
||||||
|
let preferences: NormalizedPreferences;
|
||||||
|
export function getPreferenceValues<T>(): T {
|
||||||
|
return preferences as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenStore = new Map<string, string>();
|
||||||
|
export const LocalStorage = {
|
||||||
|
async getItem<T>(key: string) { return tokenStore.get(key) as T | undefined; },
|
||||||
|
async setItem(key: string, value: string) { tokenStore.set(key, value); },
|
||||||
|
async removeItem(key: string) { tokenStore.delete(key); },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function configureWorker(config: { assets: string; support: string; preferences: NormalizedPreferences }) {
|
||||||
|
environment.assetsPath = config.assets;
|
||||||
|
environment.supportPath = config.support;
|
||||||
|
preferences = config.preferences;
|
||||||
|
}
|
||||||
274
src/lib/xlsx-restoration.ts
Normal file
274
src/lib/xlsx-restoration.ts
Normal file
@@ -0,0 +1,274 @@
|
|||||||
|
import { createReadStream, closeSync, openSync, writeSync, promises as fs } from "node:fs";
|
||||||
|
import { join, posix } from "node:path";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { TextDecoder } from "node:util";
|
||||||
|
import { Unzip, UnzipInflate, Zip, ZipDeflate } from "fflate";
|
||||||
|
import { SaxesParser, type SaxesTagNS } from "saxes";
|
||||||
|
import type { PlaceholderMapping } from "../types";
|
||||||
|
|
||||||
|
const EMPTY = new Uint8Array(0);
|
||||||
|
const SPREADSHEET = new Set([
|
||||||
|
"http://schemas.openxmlformats.org/spreadsheetml/2006/main",
|
||||||
|
"http://purl.oclc.org/ooxml/spreadsheetml/main",
|
||||||
|
]);
|
||||||
|
const DRAWING = new Set([
|
||||||
|
"http://schemas.openxmlformats.org/drawingml/2006/main",
|
||||||
|
"http://purl.oclc.org/ooxml/drawingml/main",
|
||||||
|
]);
|
||||||
|
const WORD = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
|
||||||
|
const isTextRun = (node: SaxesTagNS) => node.local === "t" && (SPREADSHEET.has(node.uri) || DRAWING.has(node.uri) || node.uri === WORD);
|
||||||
|
const isTextUnit = (node: SaxesTagNS) => SPREADSHEET.has(node.uri) && ["si", "is"].includes(node.local)
|
||||||
|
|| node.local === "p" && (DRAWING.has(node.uri) || node.uri === WORD);
|
||||||
|
const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, index) => {
|
||||||
|
let value = index;
|
||||||
|
for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ (value & 1 ? 0xedb88320 : 0);
|
||||||
|
return value >>> 0;
|
||||||
|
});
|
||||||
|
function crcUpdate(crc: number, data: Uint8Array): number {
|
||||||
|
for (const value of data) crc = (crc >>> 8) ^ CRC_TABLE[(crc ^ value) & 255];
|
||||||
|
return crc;
|
||||||
|
}
|
||||||
|
type ZipPart = { size: number; crc: number };
|
||||||
|
|
||||||
|
/** Inspect the small central directory; never load a worksheet or the whole ZIP. */
|
||||||
|
async function zipIndex(path: string): Promise<Map<string, ZipPart>> {
|
||||||
|
const file = await fs.open(path, "r");
|
||||||
|
try {
|
||||||
|
const { size } = await file.stat();
|
||||||
|
const tail = Buffer.alloc(Math.min(size, 65_557));
|
||||||
|
await file.read(tail, 0, tail.length, size - tail.length);
|
||||||
|
let end = -1;
|
||||||
|
for (let i = tail.length - 22; i >= 0; i--) {
|
||||||
|
if (tail.readUInt32LE(i) === 0x06054b50 && i + 22 + tail.readUInt16LE(i + 20) === tail.length) { end = i; break; }
|
||||||
|
}
|
||||||
|
if (end < 0) throw new Error("Excel-Datei ist kein vollständiges ZIP-Archiv.");
|
||||||
|
const entries = tail.readUInt16LE(end + 10);
|
||||||
|
const length = tail.readUInt32LE(end + 12), offset = tail.readUInt32LE(end + 16);
|
||||||
|
if (tail.readUInt16LE(end + 4) || tail.readUInt16LE(end + 6) || entries !== tail.readUInt16LE(end + 8)
|
||||||
|
|| entries === 0xffff || offset === 0xffffffff || length > 16 * 1024 * 1024 || offset + length > size - tail.length + end) {
|
||||||
|
throw new Error("Nicht unterstütztes Excel-ZIP-Archiv (mehrteilig, ZIP64 oder zu großes Inhaltsverzeichnis).");
|
||||||
|
}
|
||||||
|
const directory = Buffer.alloc(length);
|
||||||
|
if ((await file.read(directory, 0, length, offset)).bytesRead !== length) throw new Error("Unvollständiges ZIP-Inhaltsverzeichnis.");
|
||||||
|
const parts = new Map<string, ZipPart>();
|
||||||
|
let cursor = 0, total = 0;
|
||||||
|
for (let index = 0; index < entries; index++) {
|
||||||
|
if (cursor + 46 > length || directory.readUInt32LE(cursor) !== 0x02014b50) throw new Error("Ungültiges ZIP-Inhaltsverzeichnis.");
|
||||||
|
const flags = directory.readUInt16LE(cursor + 8), method = directory.readUInt16LE(cursor + 10);
|
||||||
|
const nameLength = directory.readUInt16LE(cursor + 28);
|
||||||
|
const next = cursor + 46 + nameLength + directory.readUInt16LE(cursor + 30) + directory.readUInt16LE(cursor + 32);
|
||||||
|
if (next > length || flags & 1 || ![0, 8].includes(method)) throw new Error("Verschlüsselte oder nicht unterstützte Excel-Datei.");
|
||||||
|
const rawName = directory.subarray(cursor + 46, cursor + 46 + nameLength);
|
||||||
|
if (!(flags & 0x800) && rawName.some((value) => value > 127)) throw new Error("Nicht unterstützte ZIP-Dateinamencodierung.");
|
||||||
|
const name = new TextDecoder("utf-8", { fatal: true }).decode(rawName);
|
||||||
|
if (parts.has(name) || name.startsWith("/") || name.includes("\\")
|
||||||
|
|| posix.normalize(name) !== name || name.split("/").includes("..")) throw new Error("Ungültiger oder doppelter Excel-Paketbestandteil.");
|
||||||
|
const part = { size: directory.readUInt32LE(cursor + 24), crc: directory.readUInt32LE(cursor + 16) };
|
||||||
|
total += part.size;
|
||||||
|
if (part.size === 0xffffffff || total > 2 * 1024 * 1024 * 1024) throw new Error("Entpackte Excel-Datei überschreitet 2 GiB.");
|
||||||
|
parts.set(name, part);
|
||||||
|
cursor = next;
|
||||||
|
}
|
||||||
|
if (cursor !== length || !parts.has("xl/workbook.xml") || !parts.has("[Content_Types].xml")) throw new Error("Datei ist kein unterstütztes Excel-Workbook.");
|
||||||
|
return parts;
|
||||||
|
} finally { await file.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeXml(value: string, attribute = false): string {
|
||||||
|
let result = value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\r/g, " ");
|
||||||
|
if (attribute) result = result.replace(/"/g, """).replace(/\t/g, "	").replace(/\n/g, " ");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
function restorationPattern(mapping: PlaceholderMapping) {
|
||||||
|
const originals = new Map<string, string>();
|
||||||
|
for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
for (const char of entry.original) {
|
||||||
|
const code = char.codePointAt(0)!;
|
||||||
|
if ((code < 32 && ![9, 10, 13].includes(code)) || (code >= 0xd800 && code <= 0xdfff) || code === 0xfffe || code === 0xffff) {
|
||||||
|
throw new Error("Zuordnung enthält Zeichen, die in Excel-XML nicht erlaubt sind.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
originals.set(key, entry.original);
|
||||||
|
}
|
||||||
|
const keys = [...originals.keys()].filter((key) => key && !/^[A-Z][A-Z0-9]*_\d+$/.test(key)).sort((a, b) => b.length - a.length);
|
||||||
|
const alternatives = keys.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
||||||
|
alternatives.push("[A-Z][A-Z0-9]*_\\d+");
|
||||||
|
const pattern = originals.size ? new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alternatives.join("|")})(?![\\p{L}\\p{N}_])`, "gu") : undefined;
|
||||||
|
return { originals, pattern };
|
||||||
|
}
|
||||||
|
type Token = { markup: string } | { text: string; run: boolean };
|
||||||
|
|
||||||
|
/** Buffer one rich-text cell or drawing paragraph, never a table or worksheet. */
|
||||||
|
function xmlRestorer(mapping: ReturnType<typeof restorationPattern>, emit: (text: string) => void, workbook: boolean) {
|
||||||
|
let replacements = 0;
|
||||||
|
const restore = (text: string) => mapping.pattern ? text.replace(mapping.pattern, (match) => {
|
||||||
|
const original = mapping.originals.get(match);
|
||||||
|
if (original === undefined) return match;
|
||||||
|
replacements++;
|
||||||
|
return original;
|
||||||
|
}) : text;
|
||||||
|
const parser = new SaxesParser({ xmlns: true });
|
||||||
|
const stack: SaxesTagNS[] = [];
|
||||||
|
let cell: { depth: number; tokens: Token[]; length: number } | undefined;
|
||||||
|
let pending = "";
|
||||||
|
const append = (token: Token) => {
|
||||||
|
if (!cell) { emit("markup" in token ? token.markup : escapeXml(restore(token.text))); return; }
|
||||||
|
cell.length += "markup" in token ? token.markup.length : token.text.length;
|
||||||
|
if (cell.length > 4 * 1024 * 1024) throw new Error("Eine einzelne Excel-Zelle überschreitet 4 MiB XML.");
|
||||||
|
cell.tokens.push(token);
|
||||||
|
};
|
||||||
|
const flushText = () => {
|
||||||
|
if (!pending) return;
|
||||||
|
const node = stack.at(-1);
|
||||||
|
append({ text: pending, run: Boolean(node && isTextRun(node)) });
|
||||||
|
pending = "";
|
||||||
|
};
|
||||||
|
const flushCell = () => {
|
||||||
|
const tokens = cell!.tokens;
|
||||||
|
const runs = tokens.filter((token): token is Extract<Token, { text: string }> => "text" in token && token.run);
|
||||||
|
const joined = runs.map((run) => run.text).join("");
|
||||||
|
const matches = mapping.pattern ? [...joined.matchAll(mapping.pattern)].filter((match) => mapping.originals.has(match[0])) : [];
|
||||||
|
replacements += matches.length;
|
||||||
|
let offset = 0, next = 0;
|
||||||
|
for (const run of runs) {
|
||||||
|
const start = offset, end = start + run.text.length;
|
||||||
|
let cursor = 0, output = "";
|
||||||
|
while (next < matches.length && matches[next].index + matches[next][0].length <= start) next++;
|
||||||
|
for (let i = next; i < matches.length && matches[i].index < end; i++) {
|
||||||
|
const match = matches[i], stop = match.index + match[0].length;
|
||||||
|
output += run.text.slice(cursor, Math.max(cursor, match.index - start));
|
||||||
|
if (match.index >= start) output += mapping.originals.get(match[0])!;
|
||||||
|
cursor = Math.min(run.text.length, stop - start);
|
||||||
|
}
|
||||||
|
run.text = output + run.text.slice(cursor);
|
||||||
|
offset = end;
|
||||||
|
}
|
||||||
|
for (const token of tokens) emit("markup" in token ? token.markup : escapeXml(token.run ? token.text : restore(token.text)));
|
||||||
|
cell = undefined;
|
||||||
|
};
|
||||||
|
parser.on("xmldecl", (declaration) => {
|
||||||
|
if (declaration.version !== "1.0") throw new Error("Nur XML 1.0 wird in Excel-Dateien unterstützt.");
|
||||||
|
});
|
||||||
|
parser.on("doctype", () => { throw new Error("DTD/Entities werden in Excel-Dateien nicht unterstützt."); });
|
||||||
|
parser.on("opentag", (node) => {
|
||||||
|
flushText();
|
||||||
|
if (!stack.length && workbook && (!SPREADSHEET.has(node.uri) || node.local !== "workbook")) throw new Error("Ungültiger Excel-Workbook-Bestandteil.");
|
||||||
|
stack.push(node);
|
||||||
|
if (!cell && isTextUnit(node)) cell = { depth: stack.length, tokens: [], length: 0 };
|
||||||
|
const attributes = Object.values(node.attributes).map((attr) => ` ${attr.name}="${escapeXml(restore(attr.value), true)}"`).join("");
|
||||||
|
const preserve = SPREADSHEET.has(node.uri) && node.local === "t" && !node.attributes["xml:space"] ? ' xml:space="preserve"' : "";
|
||||||
|
append({ markup: `<${node.name}${attributes}${preserve}>` });
|
||||||
|
});
|
||||||
|
parser.on("closetag", (node) => {
|
||||||
|
flushText();
|
||||||
|
append({ markup: `</${node.name}>` });
|
||||||
|
if (cell?.depth === stack.length) flushCell();
|
||||||
|
stack.pop();
|
||||||
|
});
|
||||||
|
const text = (value: string) => {
|
||||||
|
pending += value;
|
||||||
|
if (pending.length > 4 * 1024 * 1024) throw new Error("Ein Excel-Textknoten überschreitet 4 MiB.");
|
||||||
|
};
|
||||||
|
parser.on("text", text);
|
||||||
|
parser.on("cdata", text);
|
||||||
|
parser.on("comment", (value) => { flushText(); append({ markup: `<!--${value}-->` }); });
|
||||||
|
parser.on("processinginstruction", (value) => { flushText(); append({ markup: `<?${value.target}${value.body ? " " + value.body : ""}?>` }); });
|
||||||
|
emit('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>');
|
||||||
|
return { push: (text: string) => parser.write(text), end: () => { parser.close(); flushText(); return replacements; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Restore an XLSX directly from disk to a new private file, with bounded XML memory. */
|
||||||
|
export async function restoreXlsxFile(source: string, target: string, mapping: PlaceholderMapping,
|
||||||
|
onProgress: (percent: number) => void = () => undefined): Promise<{ replacements: number }> {
|
||||||
|
const before = await fs.stat(source);
|
||||||
|
const index = await zipIndex(source);
|
||||||
|
const matcher = restorationPattern(mapping);
|
||||||
|
const descriptor = openSync(target, "wx", 0o600);
|
||||||
|
let complete = false, zipComplete = false, replacements = 0, processed = 0, progress = -1;
|
||||||
|
const seen = new Set<string>(), finished = new Set<string>();
|
||||||
|
const total = [...index.values()].reduce((sum, part) => sum + part.size, 0);
|
||||||
|
const zip = new Zip((error, data, final) => {
|
||||||
|
if (error) throw error;
|
||||||
|
let offset = 0;
|
||||||
|
while (offset < data.length) offset += writeSync(descriptor, data, offset, data.length - offset);
|
||||||
|
if (final) zipComplete = true;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const unzip = new Unzip((file) => {
|
||||||
|
const expected = index.get(file.name);
|
||||||
|
if (!expected || seen.has(file.name)) throw new Error("Excel-ZIP-Inhaltsverzeichnis stimmt nicht mit den Paketdaten überein.");
|
||||||
|
seen.add(file.name);
|
||||||
|
const output = new ZipDeflate(file.name, { level: 4 });
|
||||||
|
zip.add(output);
|
||||||
|
let crc = 0xffffffff, size = 0;
|
||||||
|
let fragments: string[] = [], length = 0;
|
||||||
|
const flush = () => {
|
||||||
|
if (!length) return;
|
||||||
|
output.push(Buffer.from(fragments.join(""), "utf8"));
|
||||||
|
fragments = []; length = 0;
|
||||||
|
};
|
||||||
|
const xml = /\.(xml|rels)$/i.test(file.name) ? xmlRestorer(matcher, (value) => {
|
||||||
|
fragments.push(value); length += value.length;
|
||||||
|
if (length >= 64 * 1024) flush();
|
||||||
|
}, file.name === "xl/workbook.xml") : undefined;
|
||||||
|
let decoder: TextDecoder | undefined, header = Buffer.alloc(0);
|
||||||
|
const decode = (data: Uint8Array, final: boolean) => {
|
||||||
|
if (!decoder) {
|
||||||
|
header = Buffer.concat([header, data]);
|
||||||
|
if (header.length < 4 && !final) return;
|
||||||
|
const encoding = header[0] === 0xff && header[1] === 0xfe || header[0] === 0x3c && header[1] === 0 ? "utf-16le"
|
||||||
|
: header[0] === 0xfe && header[1] === 0xff || header[0] === 0 && header[1] === 0x3c ? "utf-16be" : "utf-8";
|
||||||
|
decoder = new TextDecoder(encoding, { fatal: true });
|
||||||
|
data = header; header = Buffer.alloc(0);
|
||||||
|
}
|
||||||
|
xml!.push(decoder.decode(data, { stream: !final }));
|
||||||
|
};
|
||||||
|
file.ondata = (error, data, final) => {
|
||||||
|
if (error) throw error;
|
||||||
|
size += data.length;
|
||||||
|
if (size > expected.size) throw new Error("Excel-Paketbestandteil überschreitet seine angegebene Größe.");
|
||||||
|
crc = crcUpdate(crc, data);
|
||||||
|
for (let offset = 0; offset < data.length; offset += 64 * 1024) {
|
||||||
|
const part = data.subarray(offset, offset + 64 * 1024);
|
||||||
|
if (xml) decode(part, false); else output.push(part);
|
||||||
|
}
|
||||||
|
processed += data.length;
|
||||||
|
const percent = Math.floor(processed * 100 / Math.max(total, 1));
|
||||||
|
if (percent !== progress) { progress = percent; onProgress(percent); }
|
||||||
|
if (final) {
|
||||||
|
if (size !== expected.size || ((crc ^ 0xffffffff) >>> 0) !== expected.crc) throw new Error("Excel-Paketbestandteil ist beschädigt (Größe/CRC).");
|
||||||
|
if (xml) { decode(EMPTY, true); replacements += xml.end(); flush(); }
|
||||||
|
output.push(EMPTY, true);
|
||||||
|
finished.add(file.name);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
file.start();
|
||||||
|
});
|
||||||
|
unzip.register(UnzipInflate);
|
||||||
|
for await (const data of createReadStream(source, { highWaterMark: 16 * 1024 })) unzip.push(data, false);
|
||||||
|
unzip.push(EMPTY, true);
|
||||||
|
if (finished.size !== index.size) throw new Error("Excel-ZIP-Archiv ist unvollständig.");
|
||||||
|
zip.end();
|
||||||
|
if (!zipComplete) throw new Error("Excel-Ausgabedatei wurde nicht vollständig geschrieben.");
|
||||||
|
const after = await fs.stat(source);
|
||||||
|
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) throw new Error("Excel-Datei wurde während der Wiederherstellung geändert.");
|
||||||
|
complete = true;
|
||||||
|
return { replacements };
|
||||||
|
} finally {
|
||||||
|
zip.terminate();
|
||||||
|
closeSync(descriptor);
|
||||||
|
if (!complete) await fs.rm(target, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Compatibility for callers already holding an Office document in memory. */
|
||||||
|
export async function restoreXlsxBuffer(data: Buffer, mapping: PlaceholderMapping): Promise<Buffer> {
|
||||||
|
const directory = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-"));
|
||||||
|
try {
|
||||||
|
const source = join(directory, "source.xlsx"), target = join(directory, "restored.xlsx");
|
||||||
|
await fs.writeFile(source, data, { mode: 0o600 });
|
||||||
|
await restoreXlsxFile(source, target, mapping);
|
||||||
|
return await fs.readFile(target);
|
||||||
|
} finally { await fs.rm(directory, { recursive: true, force: true }); }
|
||||||
|
}
|
||||||
@@ -1,260 +0,0 @@
|
|||||||
import {
|
|
||||||
Action,
|
|
||||||
ActionPanel,
|
|
||||||
Alert,
|
|
||||||
confirmAlert,
|
|
||||||
Detail,
|
|
||||||
Form,
|
|
||||||
Icon,
|
|
||||||
List,
|
|
||||||
showToast,
|
|
||||||
Toast,
|
|
||||||
useNavigation,
|
|
||||||
} from "@raycast/api";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import {
|
|
||||||
clearSessionMapping,
|
|
||||||
countMappingEntries,
|
|
||||||
createSession,
|
|
||||||
deleteAllSessions,
|
|
||||||
deleteSession,
|
|
||||||
getActiveSessionId,
|
|
||||||
listSessions,
|
|
||||||
renameSession,
|
|
||||||
setActiveSession,
|
|
||||||
} from "./sessions";
|
|
||||||
import type { VelumSession } from "./types";
|
|
||||||
import { mappingSummary, sessionSubtitle } from "./ui";
|
|
||||||
|
|
||||||
export default function Command() {
|
|
||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
|
||||||
|
|
||||||
async function reload() {
|
|
||||||
const [loadedSessions, activeId] = await Promise.all([
|
|
||||||
listSessions(),
|
|
||||||
getActiveSessionId(),
|
|
||||||
]);
|
|
||||||
setSessions(loadedSessions);
|
|
||||||
setActiveSessionId(activeId);
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
reload();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
async function activate(session: VelumSession) {
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
await reload();
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Success,
|
|
||||||
title: "Aktive Sitzung geändert",
|
|
||||||
message: session.name,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function clearMapping(session: VelumSession) {
|
|
||||||
const confirmed = await confirmAlert({
|
|
||||||
title: "Zuordnung leeren?",
|
|
||||||
message: `${session.name} behält den Namen, verliert aber alle Platzhalter-Zuordnungen.`,
|
|
||||||
primaryAction: {
|
|
||||||
title: "Zuordnung leeren",
|
|
||||||
style: Alert.ActionStyle.Destructive,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (!confirmed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await clearSessionMapping(session.id);
|
|
||||||
await reload();
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Success,
|
|
||||||
title: "Zuordnung geleert",
|
|
||||||
message: session.name,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function remove(session: VelumSession) {
|
|
||||||
const confirmed = await confirmAlert({
|
|
||||||
title: "Sitzung löschen?",
|
|
||||||
message: `${session.name} und ihre Zuordnung werden gelöscht.`,
|
|
||||||
primaryAction: {
|
|
||||||
title: "Sitzung löschen",
|
|
||||||
style: Alert.ActionStyle.Destructive,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (!confirmed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await deleteSession(session.id);
|
|
||||||
await reload();
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Success,
|
|
||||||
title: "Sitzung gelöscht",
|
|
||||||
message: session.name,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function removeAll() {
|
|
||||||
const confirmed = await confirmAlert({
|
|
||||||
title: "Alle Sitzungen löschen?",
|
|
||||||
message:
|
|
||||||
"Alle gespeicherten Velum-Zuordnungen dieser Raycast-Extension werden gelöscht.",
|
|
||||||
primaryAction: {
|
|
||||||
title: "Alle löschen",
|
|
||||||
style: Alert.ActionStyle.Destructive,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (!confirmed) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await deleteAllSessions();
|
|
||||||
await reload();
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Success,
|
|
||||||
title: "Alle Sitzungen gelöscht",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<List isLoading={isLoading} searchBarPlaceholder="Velum-Sitzungen suchen">
|
|
||||||
<List.EmptyView
|
|
||||||
title="Keine Sitzungen"
|
|
||||||
description="Lege eine Sitzung an oder pseudonymisiere Text, um Zuordnungen zu speichern."
|
|
||||||
actions={
|
|
||||||
<ActionPanel>
|
|
||||||
<Action.Push
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
target={<SessionNameForm onSaved={reload} />}
|
|
||||||
/>
|
|
||||||
</ActionPanel>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<List.Item
|
|
||||||
key={session.id}
|
|
||||||
title={session.name}
|
|
||||||
subtitle={sessionSubtitle(session)}
|
|
||||||
icon={session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle}
|
|
||||||
accessories={[{ text: `${countMappingEntries(session.mapping)}` }]}
|
|
||||||
actions={
|
|
||||||
<ActionPanel>
|
|
||||||
<Action
|
|
||||||
title="Als Aktive Sitzung Setzen"
|
|
||||||
icon={Icon.CheckCircle}
|
|
||||||
onAction={() => activate(session)}
|
|
||||||
/>
|
|
||||||
<Action.Push
|
|
||||||
title="Details anzeigen"
|
|
||||||
icon={Icon.List}
|
|
||||||
target={<SessionDetail session={session} />}
|
|
||||||
/>
|
|
||||||
<Action.Push
|
|
||||||
title="Sitzung umbenennen"
|
|
||||||
icon={Icon.Pencil}
|
|
||||||
target={<SessionNameForm session={session} onSaved={reload} />}
|
|
||||||
/>
|
|
||||||
<Action.Push
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
target={<SessionNameForm onSaved={reload} />}
|
|
||||||
/>
|
|
||||||
<Action
|
|
||||||
title="Zuordnung leeren"
|
|
||||||
icon={Icon.XMarkCircle}
|
|
||||||
style={Action.Style.Destructive}
|
|
||||||
onAction={() => clearMapping(session)}
|
|
||||||
/>
|
|
||||||
<Action
|
|
||||||
title="Sitzung löschen"
|
|
||||||
icon={Icon.Trash}
|
|
||||||
style={Action.Style.Destructive}
|
|
||||||
onAction={() => remove(session)}
|
|
||||||
/>
|
|
||||||
<Action
|
|
||||||
title="Alle Sitzungen löschen"
|
|
||||||
icon={Icon.Trash}
|
|
||||||
style={Action.Style.Destructive}
|
|
||||||
onAction={removeAll}
|
|
||||||
/>
|
|
||||||
</ActionPanel>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</List>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SessionNameForm({
|
|
||||||
session,
|
|
||||||
onSaved,
|
|
||||||
}: {
|
|
||||||
session?: VelumSession;
|
|
||||||
onSaved: () => Promise<void>;
|
|
||||||
}) {
|
|
||||||
const { pop } = useNavigation();
|
|
||||||
|
|
||||||
async function handleSubmit(values: { name: string }) {
|
|
||||||
if (session) {
|
|
||||||
await renameSession(session.id, values.name);
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Success,
|
|
||||||
title: "Sitzung umbenannt",
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
await createSession(values.name.trim() || undefined);
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Success,
|
|
||||||
title: "Sitzung erstellt",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await onSaved();
|
|
||||||
pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Form
|
|
||||||
actions={
|
|
||||||
<ActionPanel>
|
|
||||||
<Action.SubmitForm
|
|
||||||
title={session ? "Sitzung Umbenennen" : "Sitzung Erstellen"}
|
|
||||||
onSubmit={handleSubmit}
|
|
||||||
/>
|
|
||||||
</ActionPanel>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Form.TextField
|
|
||||||
id="name"
|
|
||||||
title="Name"
|
|
||||||
defaultValue={session?.name}
|
|
||||||
placeholder="Sitzungsname"
|
|
||||||
/>
|
|
||||||
</Form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SessionDetail({ session }: { session: VelumSession }) {
|
|
||||||
const markdown = [
|
|
||||||
`# ${session.name}`,
|
|
||||||
sessionSubtitle(session),
|
|
||||||
"",
|
|
||||||
`Erstellt: ${new Date(session.createdAt).toLocaleString()}`,
|
|
||||||
"",
|
|
||||||
"## Zuordnung",
|
|
||||||
mappingSummary(session.mapping),
|
|
||||||
"",
|
|
||||||
"## Platzhalter",
|
|
||||||
...Object.entries(session.mapping)
|
|
||||||
.sort(([a], [b]) => a.localeCompare(b))
|
|
||||||
.map(([placeholder, entry]) => `- \`${placeholder}\` · ${entry.type}`),
|
|
||||||
].join("\n");
|
|
||||||
|
|
||||||
return <Detail markdown={markdown} />;
|
|
||||||
}
|
|
||||||
8
src/migration-location.tsx
Normal file
8
src/migration-location.tsx
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { Action, ActionPanel, Detail, environment } from "@raycast/api";
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
return <Detail markdown={"Der eigenständige Migrationsbefehl benötigt diesen Velum-Datenordner als `--target-support`. Er verarbeitet die alten Tabellen lokal; Velum selbst greift nicht auf die frühere Erweiterung zu."}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action.CopyToClipboard title="Velum-Datenordner kopieren" content={environment.supportPath} />
|
||||||
|
</ActionPanel>} />;
|
||||||
|
}
|
||||||
5
src/paste-pseudonymized-clipboard.tsx
Normal file
5
src/paste-pseudonymized-clipboard.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import PseudonymizeTextForm from "./pseudonymize-text";
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
return <PseudonymizeTextForm initialSource="clipboard" autoOutput forcePaste />;
|
||||||
|
}
|
||||||
5
src/paste-restored-clipboard.tsx
Normal file
5
src/paste-restored-clipboard.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import RestoreTextForm from "./depseudonymize-text";
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
return <RestoreTextForm initialSource="clipboard" autoPaste />;
|
||||||
|
}
|
||||||
76
src/person-merge-targets.tsx
Normal file
76
src/person-merge-targets.tsx
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import { Action, ActionPanel, Icon, List, useNavigation } from "@raycast/api";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
const PAGE_SIZE = 200;
|
||||||
|
|
||||||
|
export function PersonMergeTargets(props: {
|
||||||
|
people: Array<{ placeholder: string; originals: string[] }>;
|
||||||
|
onChoose: (placeholder: string) => void;
|
||||||
|
}) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [page, setPage] = useState(0);
|
||||||
|
const matching = props.people.filter((person) =>
|
||||||
|
`${person.originals.join(" ")} ${person.placeholder}`
|
||||||
|
.toLowerCase()
|
||||||
|
.includes(query.trim().toLowerCase()),
|
||||||
|
);
|
||||||
|
const pages = Math.ceil(matching.length / PAGE_SIZE);
|
||||||
|
return (
|
||||||
|
<List
|
||||||
|
navigationTitle="Zusammenführen mit"
|
||||||
|
filtering={false}
|
||||||
|
searchText={query}
|
||||||
|
searchBarPlaceholder="Person oder Platzhalter suchen"
|
||||||
|
onSearchTextChange={(value) => {
|
||||||
|
setQuery(value);
|
||||||
|
setPage(0);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{pages > 1 && (
|
||||||
|
<List.Item
|
||||||
|
id="page"
|
||||||
|
title={`Seite ${page + 1}/${pages}`}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
{page + 1 < pages && (
|
||||||
|
<Action
|
||||||
|
title="Nächste Seite"
|
||||||
|
onAction={() => setPage(page + 1)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{page > 0 && (
|
||||||
|
<Action
|
||||||
|
title="Vorherige Seite"
|
||||||
|
onAction={() => setPage(page - 1)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{matching
|
||||||
|
.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE)
|
||||||
|
.map((person) => (
|
||||||
|
<List.Item
|
||||||
|
key={person.placeholder}
|
||||||
|
id={person.placeholder}
|
||||||
|
title={person.originals.join(" · ")}
|
||||||
|
subtitle={person.placeholder}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
<Action
|
||||||
|
title="Personen zusammenfassen"
|
||||||
|
icon={Icon.Link}
|
||||||
|
onAction={() => {
|
||||||
|
props.onChoose(person.placeholder);
|
||||||
|
pop();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</List>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { getPreferenceValues } from "@raycast/api";
|
import { getPreferenceValues } from "@raycast/api";
|
||||||
import type { ExtensionPreferences, QuickOutput, SessionMode } from "./types";
|
import type { ExtensionPreferences, QuickOutput } from "./types";
|
||||||
|
|
||||||
export type NormalizedPreferences = {
|
export type NormalizedPreferences = {
|
||||||
velumBaseUrl: string;
|
velumBaseUrl: string;
|
||||||
@@ -8,7 +8,6 @@ export type NormalizedPreferences = {
|
|||||||
serviceAccountUsername: string;
|
serviceAccountUsername: string;
|
||||||
serviceAccountPassword: string;
|
serviceAccountPassword: string;
|
||||||
scope: string;
|
scope: string;
|
||||||
sessionMode: SessionMode;
|
|
||||||
quickOutput: QuickOutput;
|
quickOutput: QuickOutput;
|
||||||
userFullName: string;
|
userFullName: string;
|
||||||
maxSessions: number;
|
maxSessions: number;
|
||||||
@@ -34,7 +33,6 @@ export function getPreferences(): NormalizedPreferences {
|
|||||||
serviceAccountUsername: preferences.serviceAccountUsername.trim(),
|
serviceAccountUsername: preferences.serviceAccountUsername.trim(),
|
||||||
serviceAccountPassword: preferences.serviceAccountPassword,
|
serviceAccountPassword: preferences.serviceAccountPassword,
|
||||||
scope: preferences.scope?.trim() || "profile",
|
scope: preferences.scope?.trim() || "profile",
|
||||||
sessionMode: preferences.sessionMode,
|
|
||||||
quickOutput: preferences.quickOutput,
|
quickOutput: preferences.quickOutput,
|
||||||
userFullName: preferences.userFullName?.trim() ?? "",
|
userFullName: preferences.userFullName?.trim() ?? "",
|
||||||
maxSessions: parsePositiveInteger(preferences.maxSessions, 20),
|
maxSessions: parsePositiveInteger(preferences.maxSessions, 20),
|
||||||
|
|||||||
12
src/project-mapping-actions.ts
Normal file
12
src/project-mapping-actions.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { listRuns } from "./lib/velum-project";
|
||||||
|
import { reviseProjectRun } from "./lib/project-revision";
|
||||||
|
import { depseudonymizeDocument } from "./velum";
|
||||||
|
|
||||||
|
/** Release the whole alias group and update the latest saved project files. */
|
||||||
|
export async function releaseProjectMapping(projectPath: string, placeholder: string) {
|
||||||
|
const latest = (await listRuns(projectPath))[0];
|
||||||
|
if (!latest) throw new Error("Projektstand nicht gefunden.");
|
||||||
|
return reviseProjectRun({ previous: latest.run, previousDirectory: latest.directory,
|
||||||
|
release: new Set([placeholder]), merges: {}, rewriteDocument: depseudonymizeDocument,
|
||||||
|
useCurrentInPlaceFiles: true });
|
||||||
|
}
|
||||||
45
src/project-relocation-form.tsx
Normal file
45
src/project-relocation-form.tsx
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { Action, ActionPanel, confirmAlert, Form, Icon, showToast, Toast, useNavigation } from "@raycast/api";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { relocateProject } from "./lib/project-relocation";
|
||||||
|
|
||||||
|
export function RelocateProjectForm(props: { projectName: string; oldPath: string; onMoved: () => Promise<void> }) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
async function save(values: { newPath: string[] }) {
|
||||||
|
const newPath = values.newPath?.[0];
|
||||||
|
if (!newPath) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Bitte den neuen Projektordner wählen" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!(await confirmAlert({
|
||||||
|
title: "Projektordner aktualisieren?",
|
||||||
|
message: `Alle gespeicherten Projektstände und Regeln werden künftig ${newPath} zugeordnet. `
|
||||||
|
+ `Bisheriger Pfad: ${props.oldPath}. Die Dateien im gewählten Ordner werden nicht verändert.`,
|
||||||
|
primaryAction: { title: "Projektpfad aktualisieren" },
|
||||||
|
}))) return;
|
||||||
|
setBusy(true);
|
||||||
|
const toast = await showToast({ style: Toast.Style.Animated, title: "Projektpfad wird aktualisiert" });
|
||||||
|
try {
|
||||||
|
const result = await relocateProject(props.oldPath, newPath);
|
||||||
|
await props.onMoved();
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = "Projektordner aktualisiert";
|
||||||
|
toast.message = `${result.runsMoved} Projektstände übernommen`
|
||||||
|
+ (result.copiesRelinked ? ` · ${result.copiesRelinked} Kopienordner neu gefunden` : "")
|
||||||
|
+ (result.copiesMissing ? ` · ${result.copiesMissing} Kopienordner nicht gefunden; gespeicherte Stände bleiben verfügbar` : "");
|
||||||
|
pop();
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Projektpfad nicht aktualisiert";
|
||||||
|
toast.message = (error as Error).message;
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
return <Form isLoading={busy} navigationTitle={`${props.projectName}: Projektordner ändern`}
|
||||||
|
actions={<ActionPanel><Action.SubmitForm title="Projektpfad aktualisieren" icon={Icon.Folder}
|
||||||
|
onSubmit={save} /></ActionPanel>}>
|
||||||
|
<Form.Description title="Bisheriger Projektordner" text={props.oldPath} />
|
||||||
|
<Form.FilePicker id="newPath" title="Neuer Projektordner" allowMultipleSelection={false}
|
||||||
|
canChooseDirectories canChooseFiles={false} />
|
||||||
|
<Form.Description text="Gespeicherte Stände, Ausnahmen und Projektbegriffe bleiben erhalten. Dateien im neuen Ordner werden weder analysiert noch geändert." />
|
||||||
|
</Form>;
|
||||||
|
}
|
||||||
@@ -21,20 +21,16 @@ import {
|
|||||||
import { PseudonymizationConfirm } from "./ai-views";
|
import { PseudonymizationConfirm } from "./ai-views";
|
||||||
import { getPreferences } from "./preferences";
|
import { getPreferences } from "./preferences";
|
||||||
import { getSelectedTextSafely } from "./selection";
|
import { getSelectedTextSafely } from "./selection";
|
||||||
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
import {
|
import {
|
||||||
createSession,
|
|
||||||
getActiveSessionId,
|
getActiveSessionId,
|
||||||
getSession,
|
|
||||||
listSessions,
|
listSessions,
|
||||||
setActiveSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
} from "./sessions";
|
||||||
import type { EntityType, VelumSession } from "./types";
|
import type { EntityType, VelumSession } from "./types";
|
||||||
import { NEW_SESSION_ID } from "./ui";
|
|
||||||
import {
|
import {
|
||||||
getEntityTypes,
|
getEntityTypes,
|
||||||
normalizePseudonymizeResponse,
|
|
||||||
pseudonymize,
|
|
||||||
} from "./velum";
|
} from "./velum";
|
||||||
|
|
||||||
function getIsoWeek(date: Date): number {
|
function getIsoWeek(date: Date): number {
|
||||||
@@ -126,9 +122,8 @@ function buildProjectStatusPrompt(userFullName: string) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = ContextFormValues & {
|
||||||
text: string;
|
text: string;
|
||||||
sessionId: string;
|
|
||||||
entityTypes: string[];
|
entityTypes: string[];
|
||||||
model: string;
|
model: string;
|
||||||
creativity: Creativity;
|
creativity: Creativity;
|
||||||
@@ -141,6 +136,7 @@ export default function Command() {
|
|||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@@ -169,8 +165,9 @@ export default function Command() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const loadedEntityTypes = await getEntityTypes();
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
setEntityTypes(loadedEntityTypes);
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
setSelectedEntityTypes(loadedEntityTypes);
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
} catch {
|
} catch {
|
||||||
setEntityTypes([]);
|
setEntityTypes([]);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -180,11 +177,6 @@ export default function Command() {
|
|||||||
load();
|
load();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadSelectedText() {
|
async function loadSelectedText() {
|
||||||
const selected = await getSelectedTextSafely();
|
const selected = await getSelectedTextSafely();
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@@ -227,45 +219,29 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const session =
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
values.sessionId === NEW_SESSION_ID
|
|
||||||
? await createSession()
|
|
||||||
: ((await getSession(values.sessionId)) ?? (await createSession()));
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
|
|
||||||
const rawResult = await pseudonymize(
|
|
||||||
input,
|
|
||||||
session.mapping,
|
|
||||||
values.entityTypes,
|
|
||||||
);
|
|
||||||
const pseudoResult = normalizePseudonymizeResponse(rawResult);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
pseudoResult.mapping,
|
|
||||||
pseudoResult.selected_entity_types,
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Pseudonymisiert";
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
toast.message = `${pseudoResult.entity_count} Zuordnungen`;
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
|
||||||
push(
|
push(
|
||||||
<PseudonymizationConfirm
|
<PseudonymizationConfirm
|
||||||
session={updatedSession}
|
session={updatedSession}
|
||||||
pseudonymizedText={pseudoResult.pseudonymized_text}
|
pseudonymizedText={pseudoResult.pseudonymized_text}
|
||||||
model={values.model}
|
model={values.model}
|
||||||
creativity={values.creativity}
|
creativity={values.creativity}
|
||||||
instructions={values.instructions}
|
instructions={values.instructions}
|
||||||
buildPrompt={buildPrompt}
|
buildPrompt={buildPrompt}
|
||||||
labels={{
|
labels={{
|
||||||
pageHeading: "Steering-Update",
|
pageHeading: "Steering-Update",
|
||||||
runningLabel: "KI erstellt Steering-Update …",
|
runningLabel: "KI erstellt Steering-Update …",
|
||||||
failureTitle: "Steering-Update fehlgeschlagen",
|
failureTitle: "Steering-Update fehlgeschlagen",
|
||||||
copyTitle: "Steering-Update kopieren",
|
copyTitle: "Steering-Update kopieren",
|
||||||
pasteTitle: "Steering-Update einfügen",
|
pasteTitle: "Steering-Update einfügen",
|
||||||
}}
|
}}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
}} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
@@ -303,27 +279,9 @@ export default function Command() {
|
|||||||
onChange={setText}
|
onChange={setText}
|
||||||
placeholder="Statusmeeting-Stichpunkte, Email-Auszüge, Risiken, Zahlen, Entscheidungen …"
|
placeholder="Statusmeeting-Stichpunkte, Email-Auszüge, Risiken, Zahlen, Entscheidungen …"
|
||||||
/>
|
/>
|
||||||
<Form.Dropdown
|
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||||
id="sessionId"
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
title="Sitzung"
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
defaultValue={defaultSessionId}
|
|
||||||
>
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
value={NEW_SESSION_ID}
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
key={session.id}
|
|
||||||
value={session.id}
|
|
||||||
title={session.name}
|
|
||||||
icon={
|
|
||||||
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Form.Dropdown>
|
|
||||||
{entityTypes.length > 0 ? (
|
{entityTypes.length > 0 ? (
|
||||||
<Form.TagPicker
|
<Form.TagPicker
|
||||||
id="entityTypes"
|
id="entityTypes"
|
||||||
|
|||||||
64
src/project-worker.ts
Normal file
64
src/project-worker.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { promises as fs, renameSync, writeFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { configureWorker } from "./lib/worker-runtime";
|
||||||
|
import { readJobJson, writeJobJson } from "./lib/project-jobs";
|
||||||
|
import type { AnalysisInput, Decision, JobPhase, ProjectJobState } from "./lib/project-jobs";
|
||||||
|
import { applyProject, prepareProject } from "./lib/project-work";
|
||||||
|
import type { Preview } from "./lib/project-work";
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const [, , directory, phaseArg] = process.argv;
|
||||||
|
if (!directory || (phaseArg !== "analysis" && phaseArg !== "apply")) throw new Error("Ungültiger Projektauftrag.");
|
||||||
|
const phase: JobPhase = phaseArg;
|
||||||
|
try {
|
||||||
|
let configuration = "";
|
||||||
|
process.stdin.setEncoding("utf8");
|
||||||
|
for await (const chunk of process.stdin) configuration += chunk;
|
||||||
|
const config = JSON.parse(configuration) as Parameters<typeof configureWorker>[0];
|
||||||
|
configureWorker(config);
|
||||||
|
configuration = "";
|
||||||
|
|
||||||
|
// Progress is small and independent of the persisted review. Limit disk
|
||||||
|
// writes when an unchanged project has many files.
|
||||||
|
let lastUpdate = 0;
|
||||||
|
const progress = (message: string) => {
|
||||||
|
if (Date.now() - lastUpdate < 300) return;
|
||||||
|
lastUpdate = Date.now();
|
||||||
|
const partial = join(directory, "status.tmp");
|
||||||
|
const status: ProjectJobState = { phase, pid: process.pid, message };
|
||||||
|
writeFileSync(partial, JSON.stringify(status), { mode: 0o600 });
|
||||||
|
renameSync(partial, join(directory, "state.json"));
|
||||||
|
};
|
||||||
|
const input = await readJobJson<AnalysisInput>(directory, "input.json");
|
||||||
|
if (phase === "analysis") {
|
||||||
|
const preview = await prepareProject(config.assets, input.root, input.files, input.rules,
|
||||||
|
input.whitelist, input.entityTypes, input.skipped, input.reanalyzeUnchanged, progress, input.imagePolicy);
|
||||||
|
if (!preview.drafts.length && !preview.hits.length && !input.fileSelectionChanged) {
|
||||||
|
await finish(directory, { phase: "complete", reused: preview.retained.length });
|
||||||
|
} else {
|
||||||
|
await writeJobJson(directory, "preview.json", preview);
|
||||||
|
await writeJobJson(directory, "state.json", { phase: "review" });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [preview, decision] = await Promise.all([
|
||||||
|
readJobJson<Preview>(directory, "preview.json"), readJobJson<Decision>(directory, "decision.json"),
|
||||||
|
]);
|
||||||
|
const output = await applyProject(config.assets, input.root, preview, input.rules, input.whitelist, decision, progress);
|
||||||
|
await finish(directory, { phase: "complete", output });
|
||||||
|
} catch (error) {
|
||||||
|
await writeJobJson(directory, "state.json", {
|
||||||
|
phase: "error", message: error instanceof Error ? error.message : "Lokaler Projektauftrag fehlgeschlagen.",
|
||||||
|
});
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finish(directory: string, state: ProjectJobState) {
|
||||||
|
await Promise.all(["input.json", "preview.json", "decision.json"].map((file) =>
|
||||||
|
fs.rm(join(directory, file), { force: true }).catch(() => undefined)));
|
||||||
|
await writeJobJson(directory, "state.json", state);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main().catch(() => { process.exitCode = 1; });
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { Clipboard } from "@raycast/api";
|
|
||||||
import { pseudonymizeQuickText } from "./quick";
|
|
||||||
|
|
||||||
export default async function Command() {
|
|
||||||
const clipboardText = await Clipboard.readText();
|
|
||||||
await pseudonymizeQuickText(clipboardText ?? "", "Zwischenablage");
|
|
||||||
}
|
|
||||||
5
src/pseudonymize-clipboard.tsx
Normal file
5
src/pseudonymize-clipboard.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import PseudonymizeTextForm from "./pseudonymize-text";
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
return <PseudonymizeTextForm initialSource="clipboard" autoOutput />;
|
||||||
|
}
|
||||||
618
src/pseudonymize-project-files.tsx
Normal file
618
src/pseudonymize-project-files.tsx
Normal file
@@ -0,0 +1,618 @@
|
|||||||
|
import { Action, ActionPanel, Alert, Color, confirmAlert, Detail, Form, getSelectedFinderItems, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { basename, dirname } from "node:path";
|
||||||
|
import { execFile } from "node:child_process";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import type { EntityType } from "./types";
|
||||||
|
import { getEntityTypes } from "./velum";
|
||||||
|
import {
|
||||||
|
listRuns, loadProjectEntityTypes, loadProjectFileExclusions, loadProjectRules, parseProjectRules,
|
||||||
|
loadProjectWhitelist, saveProjectFileExclusions, saveProjectRules, saveProjectEntityTypes,
|
||||||
|
saveProjectWhitelist, scanProjectFiles, whitelistKey, withoutExcludedProjectFiles,
|
||||||
|
} from "./lib/velum-project";
|
||||||
|
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, SkippedProjectFile } from "./lib/velum-project";
|
||||||
|
import { canonicalPerson, groupReviewHits, highlightedReviewContext, mergePeople } from "./lib/project-review";
|
||||||
|
import { CustomTermForm } from "./custom-term-form";
|
||||||
|
import { checkedImagePolicy, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING } from "./lib/image-policy";
|
||||||
|
import type { ImagePolicy } from "./lib/image-policy";
|
||||||
|
import {
|
||||||
|
discardProjectJob, loadProjectReview, readProjectJob, startProjectAnalysis, startProjectApply,
|
||||||
|
} from "./lib/project-jobs";
|
||||||
|
import type { ProjectJobState } from "./lib/project-jobs";
|
||||||
|
import type { Hit, Preview } from "./lib/project-work";
|
||||||
|
import { PersonMergeTargets } from "./person-merge-targets";
|
||||||
|
|
||||||
|
const run = promisify(execFile);
|
||||||
|
const REVIEW_PAGE_SIZE = 200;
|
||||||
|
const typeLabels: Record<string, string> = {
|
||||||
|
PERSON: "Personen", ORT: "Orte", ORG: "Organisationen", FIRMA: "Firmen",
|
||||||
|
KUNDE: "Kunden", ADRESSE: "Adressen", BEGRIFF: "Eigene Begriffe",
|
||||||
|
EMAIL: "E-Mail-Adressen", TELEFON: "Telefonnummern", IBAN: "IBAN",
|
||||||
|
UID: "UID-Nummern", FIRMENBUCH: "Firmenbuchnummern", SVNR: "Sozialversicherungsnummern",
|
||||||
|
PASSWORT: "Passwörter", BENUTZER: "Benutzerkennungen", PROJEKT: "Projektbezeichnungen",
|
||||||
|
DATUM: "Datumsangaben", REFERENZ: "Referenzen", KARTE: "Kreditkarten",
|
||||||
|
IP: "IP-Adressen", URL: "Internetadressen", DVR: "DVR-Nummern", GISA: "GISA-Nummern",
|
||||||
|
};
|
||||||
|
const labelForType = (type: string) => typeLabels[type] ?? type;
|
||||||
|
|
||||||
|
async function finderFolder(): Promise<string | undefined> {
|
||||||
|
try {
|
||||||
|
// The user asked for the open Finder folder, even when a file inside it is selected.
|
||||||
|
const { stdout } = await run("/usr/bin/osascript", ["-e",
|
||||||
|
'tell application "Finder" to get POSIX path of (target of front window as alias)',
|
||||||
|
]);
|
||||||
|
const path = stdout.trim();
|
||||||
|
if (path && (await fs.stat(path)).isDirectory()) return path;
|
||||||
|
} catch { /* Finder may have no open window or Automation permission */ }
|
||||||
|
try {
|
||||||
|
const items = await getSelectedFinderItems();
|
||||||
|
if (items.length) {
|
||||||
|
const first = items[0].path;
|
||||||
|
return (await fs.stat(first)).isDirectory() ? first : dirname(first);
|
||||||
|
}
|
||||||
|
} catch { /* Finder selection may be empty or unavailable */ }
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function OccurrenceReview(props: { original: string; placeholder: string; hits: Hit[] }) {
|
||||||
|
const [page, setPage] = useState(0);
|
||||||
|
const pages = Math.ceil(props.hits.length / REVIEW_PAGE_SIZE);
|
||||||
|
return <List isShowingDetail navigationTitle={`${props.original} → ${props.placeholder}`}>
|
||||||
|
{pages > 1 && <List.Item id="page" title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
|
||||||
|
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
|
||||||
|
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
|
||||||
|
</ActionPanel>} />}
|
||||||
|
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => {
|
||||||
|
// Older jobs saved the same snippets without their relative hit positions.
|
||||||
|
const legacyOffset = hit.kind === "path" ? hit.start
|
||||||
|
: hit.segment !== undefined || hit.id.startsWith(`${hit.file}:document:`)
|
||||||
|
? Array.from(hit.context).slice(0, Math.min(hit.start, 60)).join("").length
|
||||||
|
: Math.min(hit.start, 70);
|
||||||
|
const first = hit.context.indexOf(hit.original);
|
||||||
|
const atLegacyOffset = hit.kind === "path" || hit.context.startsWith(hit.original, legacyOffset);
|
||||||
|
const offset = hit.contextOffset ?? (atLegacyOffset ? legacyOffset
|
||||||
|
: first === hit.context.lastIndexOf(hit.original) ? first : -1);
|
||||||
|
return <List.Item key={hit.id} id={hit.id} title={hit.file}
|
||||||
|
subtitle={hit.source === hit.file ? "Dateiinhalt" : hit.source}
|
||||||
|
detail={<List.Item.Detail
|
||||||
|
markdown={highlightedReviewContext(hit.context, offset, hit.original.length)}
|
||||||
|
metadata={offset < 0 ? <List.Item.Detail.Metadata>
|
||||||
|
<List.Item.Detail.Metadata.Label title="Treffer" text={{ color: Color.Red, value: hit.original }} />
|
||||||
|
</List.Item.Detail.Metadata> : undefined} />} />;
|
||||||
|
})}
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: ProjectWhitelistEntry[];
|
||||||
|
preview: Preview; fileSelectionChanged: boolean;
|
||||||
|
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
const groups = useMemo(() => groupReviewHits(props.preview.hits), [props.preview.hits]);
|
||||||
|
const [selectedGroups, setSelectedGroups] = useState<Set<string>>(() => new Set(groups.map((group) => group.key)));
|
||||||
|
const [stage, setStage] = useState<"selection" | "merge">("selection");
|
||||||
|
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const accepted = useMemo(() => new Set(groups.filter((group) => selectedGroups.has(group.key))
|
||||||
|
.flatMap((group) => group.hits.map((hit) => hit.id))), [groups, selectedGroups]);
|
||||||
|
const selectedOccurrences = accepted.size;
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [page, setPage] = useState(0);
|
||||||
|
const matchingGroups = useMemo(() => {
|
||||||
|
const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||||
|
return groups.filter((group) => {
|
||||||
|
const value = `${group.original} ${group.placeholder} ${group.type} ${labelForType(group.type)}`.toLowerCase();
|
||||||
|
return words.every((word) => value.includes(word));
|
||||||
|
});
|
||||||
|
}, [groups, query]);
|
||||||
|
const pages = Math.max(1, Math.ceil(matchingGroups.length / REVIEW_PAGE_SIZE));
|
||||||
|
const byType = useMemo(() => {
|
||||||
|
const result = new Map<string, typeof groups>();
|
||||||
|
for (const group of matchingGroups.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE)) (result.get(group.type) ?? (result.set(group.type, []), result.get(group.type)!)).push(group);
|
||||||
|
return result;
|
||||||
|
}, [matchingGroups, page]);
|
||||||
|
const people = useMemo(() => {
|
||||||
|
const result = new Map<string, string[]>();
|
||||||
|
for (const group of groups) {
|
||||||
|
if (group.type !== "PERSON" || !selectedGroups.has(group.key)) continue;
|
||||||
|
const originals = result.get(group.placeholder) ?? [];
|
||||||
|
if (!originals.includes(group.original)) originals.push(group.original);
|
||||||
|
result.set(group.placeholder, originals);
|
||||||
|
}
|
||||||
|
return [...result].map(([placeholder, originals]) => ({ placeholder, originals }));
|
||||||
|
}, [groups, selectedGroups]);
|
||||||
|
const earlierPeople = useMemo(() => Object.entries(props.preview.previousMapping)
|
||||||
|
.filter(([placeholder, entry]) => entry.type === "PERSON" && !entry.merged_into
|
||||||
|
&& !people.some((person) => person.placeholder === placeholder))
|
||||||
|
.map(([placeholder, entry]) => ({ placeholder, originals: [entry.original] })),
|
||||||
|
[people, props.preview.previousMapping]);
|
||||||
|
const matchingPeople = useMemo(() => people.filter((person) =>
|
||||||
|
`${person.originals.join(" ")} ${person.placeholder}`.toLowerCase().includes(query.trim().toLowerCase())), [people, query]);
|
||||||
|
const personPages = Math.max(1, Math.ceil(matchingPeople.length / REVIEW_PAGE_SIZE));
|
||||||
|
function toggle(key: string) {
|
||||||
|
setSelectedGroups((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
if (next.has(key)) next.delete(key);
|
||||||
|
else next.add(key);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function apply(inPlace = true) {
|
||||||
|
if (!props.preview.drafts.length && !accepted.size && !props.fileSelectionChanged) {
|
||||||
|
try {
|
||||||
|
const rejected = groups.map((group) => ({ type: group.type, original: group.original }));
|
||||||
|
if (rejected.length) {
|
||||||
|
await saveProjectWhitelist(props.root, [...await loadProjectWhitelist(props.root), ...rejected]);
|
||||||
|
props.onWhitelistChanged(await loadProjectWhitelist(props.root));
|
||||||
|
}
|
||||||
|
await showToast({ style: Toast.Style.Success, title: "Keine neuen Änderungen",
|
||||||
|
message: rejected.length
|
||||||
|
? "Der bestehende Projektstand bleibt erhalten. Abgewählte Begriffe wurden als Ausnahmen gespeichert."
|
||||||
|
: "Der bestehende Projektstand bleibt erhalten." });
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Ausnahmen konnten nicht gespeichert werden",
|
||||||
|
message: (error as Error).message });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!(await confirmAlert({
|
||||||
|
title: inPlace ? "Geprüfte Auswahl anwenden und Originaldateien ersetzen?" : "Geprüfte Auswahl als Kopien erstellen?",
|
||||||
|
message: `${props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING + " " : ""}${IMAGE_POLICY_LABELS[props.preview.imagePolicy]}. ${selectedGroups.size} von ${groups.length} Begriffen in ${props.preview.drafts.length} neuen oder geänderten Dateien werden maskiert. ${groups.length - selectedGroups.size} abgewählte Begriffe werden als Projektausnahmen gespeichert. ${inPlace
|
||||||
|
? "Die Originale und gegebenenfalls ihre Namen werden im Projektordner ersetzt und vorher außerhalb gesichert. PDF-Dateien werden als DOCX ausgegeben."
|
||||||
|
: "Die pseudonymisierten Kopien werden neben dem Projektordner gespeichert."}`,
|
||||||
|
primaryAction: { title: inPlace ? "Originaldateien ersetzen" : "Kopien erstellen",
|
||||||
|
style: inPlace ? Alert.ActionStyle.Destructive : Alert.ActionStyle.Default },
|
||||||
|
}))) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const selectedPeople = new Set(people.map((person) => person.placeholder));
|
||||||
|
const availableTargets = new Set([...selectedPeople, ...earlierPeople.map((person) => person.placeholder)]);
|
||||||
|
const activeMerges = Object.fromEntries(Object.entries(personMerges).filter(([source, target]) =>
|
||||||
|
selectedPeople.has(source) && availableTargets.has(canonicalPerson(target, personMerges))));
|
||||||
|
const selectedTerms = new Set(groups.filter((group) => selectedGroups.has(group.key)).map(whitelistKey));
|
||||||
|
const rejected = groups.filter((group) => !selectedGroups.has(group.key) && !selectedTerms.has(whitelistKey(group)))
|
||||||
|
.map((group) => ({ type: group.type, original: group.original }));
|
||||||
|
await startProjectApply(props.root, { inPlace, acceptedIds: [...accepted], activeMerges, rejected });
|
||||||
|
pop();
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Ausgabe konnte nicht gestartet werden",
|
||||||
|
message: (error as Error).message });
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage === "merge") return <List isLoading={busy} navigationTitle="Personen zusammenfassen" filtering={false} searchText={query}
|
||||||
|
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}
|
||||||
|
searchBarPlaceholder="Person oder Platzhalter suchen">
|
||||||
|
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||||
|
<List.Item icon={Icon.Play} title="Pseudonymisierung starten"
|
||||||
|
subtitle={`${selectedGroups.size} Zuordnungen · ${people.length} Personen · ${props.preview.retained.length} unveränderte Dateien übernommen`}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title="Originaldateien ersetzen" icon={Icon.Pencil} onAction={() => apply()} />
|
||||||
|
<Action title="Pseudonymisierte Kopien erstellen" icon={Icon.Document} onAction={() => apply(false)} />
|
||||||
|
<Action title="Zur Trefferauswahl" icon={Icon.ArrowLeft} onAction={() => { setQuery(""); setPage(0); setStage("selection"); }} />
|
||||||
|
</ActionPanel>} />
|
||||||
|
</List.Section>
|
||||||
|
{personPages > 1 && <List.Item title={`Seite ${page + 1}/${personPages}`} actions={<ActionPanel>
|
||||||
|
{page + 1 < personPages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
|
||||||
|
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
|
||||||
|
</ActionPanel>} />}
|
||||||
|
<List.Section title="Ausgewählte Personen · optional zusammenfassen">
|
||||||
|
{matchingPeople.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((person) => {
|
||||||
|
const canonical = canonicalPerson(person.placeholder, personMerges);
|
||||||
|
const targets = [...people, ...earlierPeople]
|
||||||
|
.filter((other) => canonicalPerson(other.placeholder, personMerges) !== canonical);
|
||||||
|
return <List.Item key={person.placeholder} icon={Icon.Person}
|
||||||
|
title={person.originals.join(" · ")}
|
||||||
|
subtitle={`→ ${canonical}`}
|
||||||
|
accessories={canonical !== person.placeholder ? [{ text: "Zusammengeführt" }] : []}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
{targets.length > 0 && <Action.Push title="Mit Person zusammenfassen" icon={Icon.Link}
|
||||||
|
target={<PersonMergeTargets people={targets} onChoose={(target) => setPersonMerges((current) =>
|
||||||
|
mergePeople(current, person.placeholder, target))} />} />}
|
||||||
|
{canonical !== person.placeholder && <Action title="Zusammenführung lösen"
|
||||||
|
onAction={() => setPersonMerges((current) => {
|
||||||
|
const next = { ...current }; delete next[person.placeholder]; return next;
|
||||||
|
})} />}
|
||||||
|
<Action title="Originaldateien ersetzen" icon={Icon.Pencil} onAction={() => apply()} />
|
||||||
|
<Action title="Pseudonymisierte Kopien erstellen" icon={Icon.Document} onAction={() => apply(false)} />
|
||||||
|
</ActionPanel>} />;
|
||||||
|
})}
|
||||||
|
</List.Section>
|
||||||
|
</List>;
|
||||||
|
|
||||||
|
return <List isLoading={busy} navigationTitle="Zuordnungen prüfen" filtering={false} searchText={query}
|
||||||
|
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}
|
||||||
|
searchBarPlaceholder="Begriff oder Platzhalter suchen">
|
||||||
|
<List.Section title={props.preview.imagePolicy === "keep" ? KEEP_IMAGE_WARNING : IMAGE_POLICY_LABELS[props.preview.imagePolicy]}>
|
||||||
|
<List.Item key="apply" icon={Icon.Play}
|
||||||
|
title={`${selectedGroups.size} von ${groups.length} Zuordnungen ausgewählt`}
|
||||||
|
subtitle={`${selectedOccurrences} Vorkommen · ${props.preview.drafts.length} neue/geänderte Dateien · ${props.preview.retained.length} unverändert · ${props.preview.skipped.length} übersprungen`}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title="Auswahl abschließen und Personen prüfen" icon={Icon.ArrowRight}
|
||||||
|
onAction={() => { setQuery(""); setPage(0); setStage("merge"); }} />
|
||||||
|
</ActionPanel>} />
|
||||||
|
</List.Section>
|
||||||
|
{props.preview.skipped.length > 0 && <List.Section title="Nicht verarbeitet">
|
||||||
|
<List.Item key="skipped" icon={Icon.ExclamationMark}
|
||||||
|
title={`${props.preview.skipped.length} Dateien oder Ordner übersprungen`}
|
||||||
|
subtitle="Ansehen, bevor du die Auswahl anwendest"
|
||||||
|
actions={<ActionPanel><Action.Push title="Übersprungene Dateien anzeigen"
|
||||||
|
target={<SkippedFiles files={props.preview.skipped} />} /></ActionPanel>} />
|
||||||
|
</List.Section>}
|
||||||
|
{pages > 1 && <List.Section title={`${matchingGroups.length} passende Zuordnungen`}>
|
||||||
|
<List.Item title={`Seite ${page + 1}/${pages}`} actions={<ActionPanel>
|
||||||
|
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
|
||||||
|
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
|
||||||
|
</ActionPanel>} />
|
||||||
|
</List.Section>}
|
||||||
|
{[...byType].map(([type, entries]) => <List.Section key={type}
|
||||||
|
title={`${labelForType(type)} · ${groups.filter((entry) => entry.type === type && selectedGroups.has(entry.key)).length}/${groups.filter((entry) => entry.type === type).length}`}>
|
||||||
|
{entries.map((group) => <List.Item key={group.key} id={group.hits[0].id}
|
||||||
|
icon={{ source: selectedGroups.has(group.key) ? Icon.CheckCircle : Icon.Circle,
|
||||||
|
tintColor: selectedGroups.has(group.key) ? Color.Green : Color.SecondaryText }}
|
||||||
|
title={group.original} subtitle={`→ ${group.placeholder}`}
|
||||||
|
accessories={[{ text: `${group.hits.length} Vorkommen` },
|
||||||
|
...(group.hits.some((hit) => hit.source === "Kommentarautor") ? [{ text: "Word-Kommentator" }] : []),
|
||||||
|
...(group.hits.some((hit) => hit.source === "Änderungsautor") ? [{ text: "Word-Bearbeiter" }] : [])]}
|
||||||
|
keywords={[type, labelForType(type)]}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title={selectedGroups.has(group.key) ? "Zuordnung abwählen" : "Zuordnung auswählen"}
|
||||||
|
onAction={() => toggle(group.key)} />
|
||||||
|
<Action title={`${labelForType(type)} komplett abwählen`}
|
||||||
|
onAction={() => setSelectedGroups((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
for (const entry of groups) if (entry.type === type) next.delete(entry.key);
|
||||||
|
return next;
|
||||||
|
})} />
|
||||||
|
<Action title={`${labelForType(type)} komplett auswählen`}
|
||||||
|
onAction={() => setSelectedGroups((current) => new Set([...current, ...groups.filter((entry) => entry.type === type).map((entry) => entry.key)]))} />
|
||||||
|
<Action.Push title="Vorkommen ansehen" icon={Icon.Eye}
|
||||||
|
target={<OccurrenceReview original={group.original} placeholder={group.placeholder} hits={group.hits} />} />
|
||||||
|
<Action title="Auswahl abschließen und Personen prüfen" icon={Icon.ArrowRight}
|
||||||
|
onAction={() => { setQuery(""); setPage(0); setStage("merge"); }} />
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List.Section>)}
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectWhitelist(props: { entries: ProjectWhitelistEntry[]; onRemove: (entry: ProjectWhitelistEntry) => Promise<void> }) {
|
||||||
|
return <List navigationTitle="Projekt-Whitelist" searchBarPlaceholder="Ausnahme suchen">
|
||||||
|
<List.Section title={`${props.entries.length} nicht mehr vorgeschlagene Begriffe`}>
|
||||||
|
{props.entries.map((entry) => <List.Item key={whitelistKey(entry)} title={entry.original}
|
||||||
|
subtitle={labelForType(entry.type)} actions={<ActionPanel>
|
||||||
|
<Action title="Aus Projekt-Whitelist entfernen" icon={Icon.Trash}
|
||||||
|
onAction={() => props.onRemove(entry)} />
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List.Section>
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SkippedFiles(props: { files: SkippedProjectFile[] }) {
|
||||||
|
return <List navigationTitle="Übersprungene Dateien" searchBarPlaceholder="Datei suchen">
|
||||||
|
<List.Section title={`${props.files.length} nicht verarbeitet`}>
|
||||||
|
{props.files.map((file) => <List.Item key={file.path} title={file.path} subtitle={file.reason} />)}
|
||||||
|
</List.Section>
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectJobStatus(props: { root: string; onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||||
|
const { push, pop } = useNavigation();
|
||||||
|
const [status, setStatus] = useState<ProjectJobState>();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
let timeout: ReturnType<typeof setTimeout>;
|
||||||
|
async function refresh() {
|
||||||
|
try {
|
||||||
|
const state = await readProjectJob(props.root);
|
||||||
|
if (active) setStatus(state ?? { phase: "error", message: "Der Projektauftrag wurde entfernt." });
|
||||||
|
} catch (error) {
|
||||||
|
if (active) setStatus({ phase: "error", message: (error as Error).message });
|
||||||
|
}
|
||||||
|
if (active) timeout = setTimeout(refresh, 1000);
|
||||||
|
}
|
||||||
|
void refresh();
|
||||||
|
return () => { active = false; clearTimeout(timeout); };
|
||||||
|
}, [props.root]);
|
||||||
|
|
||||||
|
async function review() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const { input, preview } = await loadProjectReview(props.root);
|
||||||
|
push(<HitReview root={props.root} rules={input.rules} whitelist={input.whitelist} preview={preview}
|
||||||
|
fileSelectionChanged={input.fileSelectionChanged} onWhitelistChanged={props.onWhitelistChanged} />);
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Vorschau nicht lesbar", message: (error as Error).message });
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function discard() {
|
||||||
|
try {
|
||||||
|
await discardProjectJob(props.root);
|
||||||
|
pop();
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Auftrag konnte nicht geschlossen werden",
|
||||||
|
message: (error as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const running = status?.phase === "analysis" || status?.phase === "apply";
|
||||||
|
const output = status?.phase === "complete" ? status.output : undefined;
|
||||||
|
const title = status?.phase === "review" ? "Treffer bereit zur Prüfung"
|
||||||
|
: status?.phase === "complete" ? output ? output.inPlace ? "Projektstand gespeichert" : `${output.files} Kopien erstellt`
|
||||||
|
: `${status.reused ?? 0} unveränderte Dateien übernommen`
|
||||||
|
: status?.phase === "error" ? "Projektauftrag fehlgeschlagen"
|
||||||
|
: status?.phase === "apply" ? "Ausgabe läuft im Hintergrund" : "Analyse läuft im Hintergrund";
|
||||||
|
return <List isLoading={busy || !status || running} navigationTitle={`Velum · ${basename(props.root)}`}>
|
||||||
|
<List.Item title={title} subtitle={status && "message" in status ? status.message : undefined}
|
||||||
|
icon={status?.phase === "error" ? Icon.ExclamationMark : status?.phase === "complete" ? Icon.CheckCircle : Icon.Document}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
{status?.phase === "review" && <Action title="Treffer Prüfen" icon={Icon.ArrowRight} onAction={review} />}
|
||||||
|
{output && <Action title={output.inPlace && output.replaced ? "Sicherung im Finder Anzeigen" : "Ergebnis im Finder Anzeigen"}
|
||||||
|
icon={Icon.Folder} onAction={() => showInFinder(output.directory)} />}
|
||||||
|
{output && <Action.CopyToClipboard title="Speicherpfad Kopieren" content={output.directory} />}
|
||||||
|
{status?.phase === "error" && <Action.CopyToClipboard title="Fehlerdetails Kopieren" content={status.message} />}
|
||||||
|
{status && !running && <Action title={status.phase === "review" ? "Vorschau Verwerfen" : "Auftrag Schließen"}
|
||||||
|
icon={Icon.XMarkCircle} onAction={discard} />}
|
||||||
|
</ActionPanel>} />
|
||||||
|
{running && <List.Item title="Du kannst Raycast schließen" subtitle="Öffne denselben Projektordner, um den Status wieder zu sehen." />}
|
||||||
|
{output && <List.Item title={`${output.images.replaced} Bilder ersetzt · ${output.images.removed} Bilder entfernt`} />}
|
||||||
|
{output?.images.warnings.map((warning) => <List.Item key={warning} icon={Icon.Warning} title={warning} />)}
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FileSelection(props: { root: string; files: ProjectFile[]; skipped: SkippedProjectFile[];
|
||||||
|
excluded: string[]; rules: ProjectRule[]; types: EntityType[]; reanalyzeUnchanged: boolean; imagePolicy: ImagePolicy;
|
||||||
|
onWhitelistChanged: (entries: ProjectWhitelistEntry[]) => void }) {
|
||||||
|
const { push } = useNavigation();
|
||||||
|
const [analysisError, setAnalysisError] = useState<string>();
|
||||||
|
const [selected, setSelected] = useState<Set<string>>(() => new Set(
|
||||||
|
withoutExcludedProjectFiles(props.files, props.excluded).map((file) => file.relPath)));
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const byFolder = useMemo(() => {
|
||||||
|
const folders = new Map<string, ProjectFile[]>();
|
||||||
|
for (const file of props.files) {
|
||||||
|
const folder = dirname(file.relPath);
|
||||||
|
(folders.get(folder) ?? (folders.set(folder, []), folders.get(folder)!)).push(file);
|
||||||
|
}
|
||||||
|
return folders;
|
||||||
|
}, [props.files]);
|
||||||
|
function toggle(path: string) {
|
||||||
|
setSelected((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
if (next.has(path)) next.delete(path);
|
||||||
|
else next.add(path);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function continueToHits() {
|
||||||
|
if (!selected.size) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Bitte mindestens eine Datei auswählen" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setAnalysisError(undefined);
|
||||||
|
const toast = await showToast({ style: Toast.Style.Animated, title: "Dateiauswahl wird gespeichert" });
|
||||||
|
try {
|
||||||
|
const visiblePaths = new Set(props.files.map((file) => file.relPath));
|
||||||
|
const excluded = [
|
||||||
|
...props.excluded.filter((path) => !visiblePaths.has(path)),
|
||||||
|
...props.files.filter((file) => !selected.has(file.relPath)).map((file) => file.relPath),
|
||||||
|
];
|
||||||
|
const previous = new Set(props.excluded);
|
||||||
|
const fileSelectionChanged = props.files.some((file) => previous.has(file.relPath) === selected.has(file.relPath));
|
||||||
|
await saveProjectFileExclusions(props.root, excluded);
|
||||||
|
const files = props.files.filter((file) => selected.has(file.relPath));
|
||||||
|
const skipped = [...props.skipped, ...props.files.filter((file) => !selected.has(file.relPath))
|
||||||
|
.map((file) => ({ path: file.relPath, reason: "Für dieses Projekt abgewählt" }))];
|
||||||
|
const whitelist = await loadProjectWhitelist(props.root);
|
||||||
|
if (!await readProjectJob(props.root)) {
|
||||||
|
await startProjectAnalysis({ root: props.root, files, rules: props.rules, whitelist,
|
||||||
|
entityTypes: props.types, skipped, reanalyzeUnchanged: props.reanalyzeUnchanged,
|
||||||
|
imagePolicy: props.imagePolicy, fileSelectionChanged });
|
||||||
|
}
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = "Projektauftrag geöffnet";
|
||||||
|
push(<ProjectJobStatus root={props.root} onWhitelistChanged={props.onWhitelistChanged} />);
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Analyse fehlgeschlagen";
|
||||||
|
toast.message = error instanceof Error ? error.message : String(error);
|
||||||
|
setAnalysisError(toast.message);
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
return <List isLoading={busy} navigationTitle="Projektdateien auswählen"
|
||||||
|
searchBarPlaceholder="Datei oder Ordner suchen">
|
||||||
|
{analysisError && <List.Section title="Analyse fehlgeschlagen">
|
||||||
|
<List.Item icon={Icon.ExclamationMark} title="Fehlerdetails anzeigen" subtitle={analysisError}
|
||||||
|
keywords={props.files.map((file) => file.relPath)}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action.Push title="Fehlerdetails anzeigen" target={<Detail markdown={analysisError.replace(/</g, "<")} />} />
|
||||||
|
<Action.CopyToClipboard title="Fehlermeldung kopieren" content={analysisError} />
|
||||||
|
</ActionPanel>} />
|
||||||
|
</List.Section>}
|
||||||
|
<List.Section title="Auswahl">
|
||||||
|
<List.Item icon={Icon.ArrowRight} title="Dateiauswahl bestätigen und Treffer prüfen"
|
||||||
|
subtitle={`${selected.size} von ${props.files.length} Dateien ausgewählt · ${props.files.length - selected.size} für dieses Projekt ausgeschlossen`}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title="Treffer prüfen" icon={Icon.ArrowRight} onAction={continueToHits} />
|
||||||
|
<Action title="Alle Dateien auswählen" onAction={() => setSelected(new Set(props.files.map((file) => file.relPath)))} />
|
||||||
|
<Action title="Alle Dateien abwählen" onAction={() => setSelected(new Set())} />
|
||||||
|
</ActionPanel>} />
|
||||||
|
</List.Section>
|
||||||
|
{props.skipped.length > 0 && <List.Section title="Nicht auswählbar">
|
||||||
|
<List.Item icon={Icon.ExclamationMark} title={`${props.skipped.length} Dateien oder Ordner nicht verarbeitet`}
|
||||||
|
actions={<ActionPanel><Action.Push title="Gründe anzeigen"
|
||||||
|
target={<SkippedFiles files={props.skipped} />} /></ActionPanel>} />
|
||||||
|
</List.Section>}
|
||||||
|
{[...byFolder].map(([folder, files]) => <List.Section key={folder}
|
||||||
|
title={`${folder === "." ? "Projektordner" : folder} · ${files.filter((file) => selected.has(file.relPath)).length}/${files.length}`}>
|
||||||
|
{files.map((file) => <List.Item key={file.relPath}
|
||||||
|
icon={{ source: selected.has(file.relPath) ? Icon.CheckCircle : Icon.Circle,
|
||||||
|
tintColor: selected.has(file.relPath) ? Color.Green : Color.SecondaryText }}
|
||||||
|
title={basename(file.relPath)} subtitle={folder === "." ? undefined : file.relPath}
|
||||||
|
accessories={[{ text: file.kind === "document" ? "Dokument" : "Textdatei" }]}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title={selected.has(file.relPath) ? "Datei ausschließen" : "Datei auswählen"}
|
||||||
|
onAction={() => toggle(file.relPath)} />
|
||||||
|
<Action title="Treffer prüfen" icon={Icon.ArrowRight} onAction={continueToHits} />
|
||||||
|
<Action title="Alle Dateien auswählen" onAction={() => setSelected(new Set(props.files.map((item) => item.relPath)))} />
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List.Section>)}
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
const { push } = useNavigation();
|
||||||
|
const [root, setRoot] = useState("");
|
||||||
|
const [imagePolicy, setImagePolicy] = useState<ImagePolicy>(DEFAULT_IMAGE_POLICY);
|
||||||
|
const [rules, setRules] = useState("");
|
||||||
|
const [availableTypes, setAvailableTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultTypes, setDefaultTypes] = useState<EntityType[]>([]);
|
||||||
|
const [selectedTypes, setSelectedTypes] = useState<EntityType[]>([]);
|
||||||
|
const [typesLoaded, setTypesLoaded] = useState(false);
|
||||||
|
const [typesReadyFor, setTypesReadyFor] = useState<string | null>(null);
|
||||||
|
const [whitelist, setWhitelist] = useState<ProjectWhitelistEntry[]>([]);
|
||||||
|
const [existingRuns, setExistingRuns] = useState<number | null>(null);
|
||||||
|
const [reanalyzeUnchanged, setReanalyzeUnchanged] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
useEffect(() => { finderFolder().then((path) => { if (path) setRoot((current) => current || path); }); }, []);
|
||||||
|
useEffect(() => {
|
||||||
|
getEntityTypes().then((types) => {
|
||||||
|
setAvailableTypes(types.all);
|
||||||
|
setDefaultTypes(types.defaults);
|
||||||
|
setTypesLoaded(true);
|
||||||
|
}).catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Kategorien nicht verfügbar", message: error.message }));
|
||||||
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!typesLoaded) return;
|
||||||
|
const defaults = defaultTypes.filter((type) => type !== "ORT");
|
||||||
|
if (!root) { setSelectedTypes(defaults); setTypesReadyFor(""); return; }
|
||||||
|
let active = true;
|
||||||
|
setTypesReadyFor(null);
|
||||||
|
loadProjectEntityTypes(root).then((stored) => {
|
||||||
|
if (!active) return;
|
||||||
|
setSelectedTypes(stored === null ? defaults : stored.filter((type) => availableTypes.includes(type)));
|
||||||
|
setTypesReadyFor(root);
|
||||||
|
}).catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Projektkategorien nicht lesbar", message: error.message }));
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [root, availableTypes, defaultTypes, typesLoaded]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!root) return;
|
||||||
|
let active = true;
|
||||||
|
loadProjectRules(root).then((found) => {
|
||||||
|
if (active) setRules(found.map((rule) => `${rule.type}: ${rule.value}`).join("\n"));
|
||||||
|
}).catch(() => { if (active) setRules(""); });
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [root]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!root) { setWhitelist([]); return; }
|
||||||
|
let active = true;
|
||||||
|
loadProjectWhitelist(root).then((found) => { if (active) setWhitelist(found); })
|
||||||
|
.catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Projekt-Whitelist nicht lesbar", message: error.message }));
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [root]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!root) { setExistingRuns(null); return; }
|
||||||
|
setReanalyzeUnchanged(false);
|
||||||
|
setExistingRuns(null);
|
||||||
|
let active = true;
|
||||||
|
listRuns(root).then((found) => { if (active) setExistingRuns(found.length); })
|
||||||
|
.catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Projektstatus nicht lesbar", message: error.message }));
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [root]);
|
||||||
|
async function removeFromWhitelist(entry: ProjectWhitelistEntry) {
|
||||||
|
try {
|
||||||
|
const next = (await loadProjectWhitelist(root)).filter((item) => whitelistKey(item) !== whitelistKey(entry));
|
||||||
|
await saveProjectWhitelist(root, next);
|
||||||
|
setWhitelist(next);
|
||||||
|
await showToast({ style: Toast.Style.Success, title: "Begriff wird wieder vorgeschlagen" });
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Entfernen fehlgeschlagen",
|
||||||
|
message: (error as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function next() {
|
||||||
|
setBusy(true);
|
||||||
|
const toast = await showToast({ style: Toast.Style.Animated, title: "Projekt wird vorbereitet" });
|
||||||
|
try {
|
||||||
|
if (!(await fs.stat(root)).isDirectory()) throw new Error("Bitte einen Projektordner wählen.");
|
||||||
|
if (await readProjectJob(root)) {
|
||||||
|
await toast.hide();
|
||||||
|
push(<ProjectJobStatus root={root} onWhitelistChanged={setWhitelist} />);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (typesReadyFor !== root) throw new Error("Projektkategorien werden noch geladen oder sind nicht lesbar.");
|
||||||
|
const parsed = parseProjectRules(rules, availableTypes);
|
||||||
|
const types = [...new Set([...selectedTypes, ...parsed.map((rule) => rule.type)])];
|
||||||
|
if (!types.length) throw new Error("Bitte mindestens eine Kategorie wählen.");
|
||||||
|
await saveProjectEntityTypes(root, types);
|
||||||
|
await saveProjectRules(root, parsed);
|
||||||
|
toast.title = "Dateien werden erfasst";
|
||||||
|
const scan = await scanProjectFiles(root, undefined, false, { ".docx": 128 * 1024 * 1024 });
|
||||||
|
if (!scan.files.length) {
|
||||||
|
const first = scan.skipped[0];
|
||||||
|
throw new Error(`Keine geeigneten Dateien im Projektordner gefunden.${first ? ` Übersprungen: ${first.path} (${first.reason}).` : ""}`);
|
||||||
|
}
|
||||||
|
const excluded = await loadProjectFileExclusions(root);
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = `${scan.files.length} Dateien zur Auswahl`;
|
||||||
|
push(<FileSelection root={root} files={scan.files} skipped={scan.skipped} excluded={excluded}
|
||||||
|
rules={parsed} types={types} reanalyzeUnchanged={reanalyzeUnchanged} imagePolicy={imagePolicy}
|
||||||
|
onWhitelistChanged={setWhitelist} />);
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Analyse fehlgeschlagen";
|
||||||
|
toast.message = error instanceof Error ? error.message : String(error);
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
async function useFinderFolder() {
|
||||||
|
const path = await finderFolder();
|
||||||
|
if (path) setRoot(path);
|
||||||
|
else await showToast({ style: Toast.Style.Failure, title: "Kein Finder-Ordner gefunden",
|
||||||
|
message: "Bitte den Ordner im Finder öffnen oder unten manuell auswählen." });
|
||||||
|
}
|
||||||
|
return <Form isLoading={busy} actions={<ActionPanel>
|
||||||
|
<Action title="Projektdateien auswählen oder Auftrag öffnen" onAction={next} />
|
||||||
|
{availableTypes.length > 0 && <Action.Push title="Eigenen Begriff hinzufügen" icon={Icon.Plus}
|
||||||
|
target={<CustomTermForm entityTypes={availableTypes} onAdd={(term) => {
|
||||||
|
const next = parseProjectRules([rules, `${term.type}: ${term.value}`].filter(Boolean).join("\n"), availableTypes);
|
||||||
|
setRules(next.map((rule) => `${rule.type}: ${rule.value}`).join("\n"));
|
||||||
|
setSelectedTypes((current) => [...new Set([...current, term.type])]);
|
||||||
|
}} />} />}
|
||||||
|
<Action title="Geöffneten Finder-Ordner übernehmen" icon={Icon.Folder} onAction={useFinderFolder} />
|
||||||
|
<Action.Push title="Projekt-Whitelist bearbeiten" icon={Icon.List}
|
||||||
|
target={<ProjectWhitelist entries={whitelist} onRemove={removeFromWhitelist} />} />
|
||||||
|
</ActionPanel>}>
|
||||||
|
<Form.FilePicker id="projectPath" title="Projektordner" allowMultipleSelection={false}
|
||||||
|
canChooseDirectories canChooseFiles={false} value={root ? [root] : []}
|
||||||
|
onChange={(paths) => setRoot(paths[0] ?? "")} />
|
||||||
|
<Form.Description title="Projektstatus" text={existingRuns === null ? "Projektordner auswählen."
|
||||||
|
: existingRuns ? `Bereits angelegt · ${existingRuns} gespeicherte Stände. Ein erneuter Lauf aktualisiert dieses Projekt; es wird kein zweites angelegt.`
|
||||||
|
: "Neues Projekt. Falls dieser Ordner aus einem bestehenden Projekt verschoben wurde, aktualisiere zuerst dessen Pfad über „Projektdateien wiederherstellen“ → „Projektordner ändern“."} />
|
||||||
|
<Form.TextArea id="projectRules" title="Begriffe nur für dieses Projekt" value={rules}
|
||||||
|
onChange={setRules} placeholder={"BEGRIFF: KundenSuite\nPERSON: Max Mustermann"}
|
||||||
|
info="Ein Begriff pro Zeile. Ohne Typ wird BEGRIFF verwendet. Die Kategorien der Projektbegriffe werden für die Analyse aktiviert." />
|
||||||
|
<Form.TagPicker id="entityTypes" title="Kategorien pseudonymisieren" value={selectedTypes}
|
||||||
|
onChange={setSelectedTypes} info="Die Auswahl wird beim Prüfen für diesen Projektordner gespeichert. Word-Kommentatoren und Bearbeiter von Änderungen werden mit der Kategorie Personen maskiert. Bei neuen Projekten sind Orte zunächst abgewählt.">
|
||||||
|
{availableTypes.map((type) => <Form.TagPicker.Item key={type} value={type} title={labelForType(type)} />)}
|
||||||
|
</Form.TagPicker>
|
||||||
|
<Form.Dropdown id="imagePolicy" title="Bilder in Office/PDF" value={imagePolicy}
|
||||||
|
onChange={(value) => setImagePolicy(checkedImagePolicy(value))}>
|
||||||
|
{Object.entries(IMAGE_POLICY_LABELS).map(([value, title]) => <Form.Dropdown.Item key={value} value={value} title={title} />)}
|
||||||
|
</Form.Dropdown>
|
||||||
|
<Form.Description title={imagePolicy === "keep" ? "Achtung" : "Bildbehandlung"}
|
||||||
|
text={imagePolicy === "keep" ? KEEP_IMAGE_WARNING
|
||||||
|
: "Keine Analyse von Bildinhalten. Position und Größe bleiben bei Office-Platzhaltern soweit möglich erhalten. PDF wird als Word-Dokument neu aufgebaut. Entfernte Bilder sind nicht wiederherstellbar."} />
|
||||||
|
<Form.Checkbox id="reanalyzeUnchanged" title="Erneute Analyse"
|
||||||
|
label="Auch unveränderte Dateien erneut analysieren" value={reanalyzeUnchanged}
|
||||||
|
onChange={setReanalyzeUnchanged}
|
||||||
|
info="Unveränderte Dateien werden nur bei geänderten Kategorien oder unbekanntem altem Prüfstand automatisch neu analysiert. Für neue Projektregeln oder Word-Erkennung diese Option aktivieren." />
|
||||||
|
<Form.Description title="Projekt-Whitelist" text={`${whitelist.length} Begriffe werden bei diesem Ordner nicht mehr vorgeschlagen. Über die Aktionen kannst du sie wieder freigeben.`} />
|
||||||
|
<Form.Description title="Ablauf" text="Dateien wählen und Treffer prüfen. Während Analyse und Ausgabe kann Raycast geschlossen werden. Den Status findest du beim erneuten Öffnen des Projektordners." />
|
||||||
|
</Form>;
|
||||||
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { showToast, Toast } from "@raycast/api";
|
|
||||||
import { pseudonymizeQuickText } from "./quick";
|
|
||||||
import { getSelectedTextSafely } from "./selection";
|
|
||||||
|
|
||||||
export default async function Command() {
|
|
||||||
const selectedText = await getSelectedTextSafely();
|
|
||||||
if (!selectedText) {
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Failure,
|
|
||||||
title: "Kein markierter Text gefunden",
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await pseudonymizeQuickText(selectedText, "Selektion");
|
|
||||||
}
|
|
||||||
5
src/pseudonymize-selected-text.tsx
Normal file
5
src/pseudonymize-selected-text.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import PseudonymizeTextForm from "./pseudonymize-text";
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
return <PseudonymizeTextForm initialSource="selection" autoOutput />;
|
||||||
|
}
|
||||||
@@ -5,40 +5,40 @@ import {
|
|||||||
Detail,
|
Detail,
|
||||||
Form,
|
Form,
|
||||||
Icon,
|
Icon,
|
||||||
|
showHUD,
|
||||||
showToast,
|
showToast,
|
||||||
Toast,
|
Toast,
|
||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { getSelectedTextSafely } from "./selection";
|
import { getSelectedTextSafely } from "./selection";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import { getActiveSessionId, listSessions } from "./sessions";
|
||||||
createSession,
|
|
||||||
getActiveSessionId,
|
|
||||||
getSession,
|
|
||||||
listSessions,
|
|
||||||
setActiveSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
|
||||||
import type { EntityType, PseudonymizeResponse, VelumSession } from "./types";
|
import type { EntityType, PseudonymizeResponse, VelumSession } from "./types";
|
||||||
import {
|
import {
|
||||||
markdownCodeBlock,
|
markdownCodeBlock,
|
||||||
mappingSummary,
|
mappingSummary,
|
||||||
NEW_SESSION_ID,
|
|
||||||
sessionSubtitle,
|
sessionSubtitle,
|
||||||
} from "./ui";
|
} from "./ui";
|
||||||
import { getEntityTypes, pseudonymize } from "./velum";
|
import { getEntityTypes } from "./velum";
|
||||||
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
|
import { getPreferences } from "./preferences";
|
||||||
|
import RelocateProjectCommand from "./relocate-project";
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = ContextFormValues & {
|
||||||
text: string;
|
text: string;
|
||||||
sessionId: string;
|
|
||||||
entityTypes: string[];
|
entityTypes: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function Command() {
|
export default function Command(props: { initialSource?: "selection" | "clipboard"; autoOutput?: boolean;
|
||||||
|
forcePaste?: boolean } = {}) {
|
||||||
const [text, setText] = useState("");
|
const [text, setText] = useState("");
|
||||||
|
const [contextVersion, setContextVersion] = useState(0);
|
||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const { push } = useNavigation();
|
const { push } = useNavigation();
|
||||||
@@ -51,11 +51,21 @@ export default function Command() {
|
|||||||
]);
|
]);
|
||||||
setSessions(loadedSessions);
|
setSessions(loadedSessions);
|
||||||
setActiveSessionId(activeId);
|
setActiveSessionId(activeId);
|
||||||
|
if (props.initialSource === "selection") {
|
||||||
|
const selected = await getSelectedTextSafely();
|
||||||
|
if (selected) setText(selected);
|
||||||
|
else await showToast({ style: Toast.Style.Failure, title: "Kein markierter Text gefunden" });
|
||||||
|
} else if (props.initialSource === "clipboard") {
|
||||||
|
const clipboard = await Clipboard.readText();
|
||||||
|
if (clipboard) setText(clipboard);
|
||||||
|
else await showToast({ style: Toast.Style.Failure, title: "Zwischenablage enthält keinen Text" });
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const loadedEntityTypes = await getEntityTypes();
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
setEntityTypes(loadedEntityTypes);
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
setSelectedEntityTypes(loadedEntityTypes);
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
} catch {
|
} catch {
|
||||||
setEntityTypes([]);
|
setEntityTypes([]);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -65,11 +75,6 @@ export default function Command() {
|
|||||||
load();
|
load();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadSelectedText() {
|
async function loadSelectedText() {
|
||||||
const selected = await getSelectedTextSafely();
|
const selected = await getSelectedTextSafely();
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@@ -110,27 +115,29 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const session =
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
values.sessionId === NEW_SESSION_ID
|
|
||||||
? await createSession()
|
|
||||||
: ((await getSession(values.sessionId)) ?? (await createSession()));
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
const result = await pseudonymize(
|
|
||||||
input,
|
|
||||||
session.mapping,
|
|
||||||
values.entityTypes,
|
|
||||||
);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
result.mapping,
|
|
||||||
result.selected_entity_types,
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Pseudonymisiert";
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
toast.message = `${result.entity_count} Zuordnungen in ${updatedSession.name}`;
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} onConfirmed={async (result, session) => {
|
||||||
push(<PseudonymizeResult result={result} session={updatedSession} />);
|
if (props.autoOutput) {
|
||||||
|
const paste = props.forcePaste || getPreferences().quickOutput === "paste";
|
||||||
|
try {
|
||||||
|
if (paste) await Clipboard.paste(result.pseudonymized_text);
|
||||||
|
else await Clipboard.copy(result.pseudonymized_text);
|
||||||
|
await showHUD(`Pseudonymisierten Text ${paste ? "eingefügt" : "kopiert"} (${session.name})`)
|
||||||
|
.catch(() => undefined);
|
||||||
|
} catch (error) {
|
||||||
|
push(<PseudonymizeResult result={result} session={session} />);
|
||||||
|
await showToast({ style: Toast.Style.Failure,
|
||||||
|
title: paste ? "Einfügen fehlgeschlagen" : "Kopieren fehlgeschlagen",
|
||||||
|
message: `${error instanceof Error ? error.message : String(error)} · Das Ergebnis bleibt zum manuellen Einfügen geöffnet.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
push(<PseudonymizeResult result={result} session={session} />);
|
||||||
|
}
|
||||||
|
}} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
@@ -148,6 +155,8 @@ export default function Command() {
|
|||||||
icon={Icon.EyeDisabled}
|
icon={Icon.EyeDisabled}
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
/>
|
/>
|
||||||
|
<Action.Push title="Projektordner ändern" icon={Icon.Folder}
|
||||||
|
target={<RelocateProjectCommand onMoved={() => setContextVersion((version) => version + 1)} />} />
|
||||||
<Action
|
<Action
|
||||||
title="Markierten Text übernehmen"
|
title="Markierten Text übernehmen"
|
||||||
icon={Icon.TextSelection}
|
icon={Icon.TextSelection}
|
||||||
@@ -168,27 +177,9 @@ export default function Command() {
|
|||||||
onChange={setText}
|
onChange={setText}
|
||||||
placeholder="Zu pseudonymisierender Text"
|
placeholder="Zu pseudonymisierender Text"
|
||||||
/>
|
/>
|
||||||
<Form.Dropdown
|
<ContextPicker key={contextVersion} sessions={sessions} activeSessionId={activeSessionId}
|
||||||
id="sessionId"
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
title="Sitzung"
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
defaultValue={defaultSessionId}
|
|
||||||
>
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
value={NEW_SESSION_ID}
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
key={session.id}
|
|
||||||
value={session.id}
|
|
||||||
title={session.name}
|
|
||||||
icon={
|
|
||||||
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Form.Dropdown>
|
|
||||||
{entityTypes.length > 0 ? (
|
{entityTypes.length > 0 ? (
|
||||||
<Form.TagPicker
|
<Form.TagPicker
|
||||||
id="entityTypes"
|
id="entityTypes"
|
||||||
|
|||||||
121
src/quick.ts
121
src/quick.ts
@@ -1,121 +0,0 @@
|
|||||||
import { Clipboard, showHUD, showToast, Toast } from "@raycast/api";
|
|
||||||
import { getPreferences } from "./preferences";
|
|
||||||
import {
|
|
||||||
getActiveSession,
|
|
||||||
resolveDefaultSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
|
||||||
import type { VelumSession } from "./types";
|
|
||||||
import { localDepseudonymize, pseudonymize } from "./velum";
|
|
||||||
|
|
||||||
export async function pseudonymizeQuickText(
|
|
||||||
text: string,
|
|
||||||
source: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const trimmed = text.trim();
|
|
||||||
if (!trimmed) {
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Failure,
|
|
||||||
title: `Kein Text in ${source} gefunden`,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const toast = await showToast({
|
|
||||||
style: Toast.Style.Animated,
|
|
||||||
title: "Pseudonymisiere…",
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const session = await resolveDefaultSession();
|
|
||||||
const result = await pseudonymize(
|
|
||||||
trimmed,
|
|
||||||
session.mapping,
|
|
||||||
session.entityTypes,
|
|
||||||
);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
result.mapping,
|
|
||||||
result.selected_entity_types,
|
|
||||||
);
|
|
||||||
await writeQuickOutput(
|
|
||||||
result.pseudonymized_text,
|
|
||||||
updatedSession,
|
|
||||||
"Pseudonymisierten Text",
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
|
||||||
toast.title = "Pseudonymisiert";
|
|
||||||
toast.message = `${result.entity_count} Zuordnungen in ${updatedSession.name}`;
|
|
||||||
} catch (error) {
|
|
||||||
toast.style = Toast.Style.Failure;
|
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
|
||||||
toast.message = error instanceof Error ? error.message : String(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function depseudonymizeQuickText(
|
|
||||||
text: string,
|
|
||||||
source: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const trimmed = text.trim();
|
|
||||||
if (!trimmed) {
|
|
||||||
await showToast({
|
|
||||||
style: Toast.Style.Failure,
|
|
||||||
title: `Kein Text in ${source} gefunden`,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const toast = await showToast({
|
|
||||||
style: Toast.Style.Animated,
|
|
||||||
title: "Stelle wieder her…",
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const session = await getActiveSession();
|
|
||||||
if (Object.keys(session.mapping).length === 0) {
|
|
||||||
toast.style = Toast.Style.Failure;
|
|
||||||
toast.title = "Aktive Sitzung hat keine Zuordnungen";
|
|
||||||
toast.message = session.name;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = localDepseudonymize(trimmed, session.mapping);
|
|
||||||
if (result.replacements_made === 0) {
|
|
||||||
toast.style = Toast.Style.Failure;
|
|
||||||
toast.title = "Keine Platzhalter ersetzt";
|
|
||||||
toast.message = `Sitzung: ${session.name}`;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await writeQuickOutput(
|
|
||||||
result.original_text,
|
|
||||||
session,
|
|
||||||
"Wiederhergestellten Text",
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
|
||||||
toast.title = "Wiederhergestellt";
|
|
||||||
toast.message = `${result.replacements_made} Ersetzungen in ${session.name}`;
|
|
||||||
} catch (error) {
|
|
||||||
toast.style = Toast.Style.Failure;
|
|
||||||
toast.title = "Wiederherstellung fehlgeschlagen";
|
|
||||||
toast.message = error instanceof Error ? error.message : String(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function writeQuickOutput(
|
|
||||||
text: string,
|
|
||||||
session: VelumSession,
|
|
||||||
textKind: string,
|
|
||||||
): Promise<void> {
|
|
||||||
if (getPreferences().quickOutput === "paste") {
|
|
||||||
await Clipboard.paste(text);
|
|
||||||
await showHUD(`${textKind} eingefügt (${session.name})`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await Clipboard.copy(text);
|
|
||||||
await showHUD(`${textKind} kopiert (${session.name})`);
|
|
||||||
}
|
|
||||||
34
src/relocate-project.tsx
Normal file
34
src/relocate-project.tsx
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { Action, ActionPanel, Icon, List, showToast, Toast } from "@raycast/api";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { canonicalProjectPath, listAllRuns } from "./lib/velum-project";
|
||||||
|
import { RelocateProjectForm } from "./project-relocation-form";
|
||||||
|
|
||||||
|
export default function Command(props: { onMoved?: () => void } = {}) {
|
||||||
|
const [projects, setProjects] = useState<Array<{ path: string; name: string }>>([]);
|
||||||
|
const [busy, setBusy] = useState(true);
|
||||||
|
async function refresh() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const unique = new Map<string, string>();
|
||||||
|
for (const { run } of await listAllRuns()) {
|
||||||
|
const path = canonicalProjectPath(run.projectPath);
|
||||||
|
if (!unique.has(path)) unique.set(path, run.projectName);
|
||||||
|
}
|
||||||
|
setProjects([...unique].map(([path, name]) => ({ path, name })));
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Projekte nicht lesbar",
|
||||||
|
message: (error as Error).message });
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
useEffect(() => { void refresh(); }, []);
|
||||||
|
return <List isLoading={busy} navigationTitle="Projektordner ändern" searchBarPlaceholder="Projekt oder bisherigen Pfad suchen">
|
||||||
|
<List.EmptyView title="Noch keine gespeicherten Projekte" description="Zuerst ein Projekt mit Velum anlegen." />
|
||||||
|
{projects.map((project) => <List.Item key={project.path} icon={Icon.Folder}
|
||||||
|
title={project.name} subtitle={project.path} keywords={[project.path]}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action.Push title="Neuen Projektordner zuordnen" icon={Icon.Folder}
|
||||||
|
target={<RelocateProjectForm projectName={project.name} oldPath={project.path}
|
||||||
|
onMoved={async () => { await refresh(); props.onMoved?.(); }} />} />
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
@@ -11,12 +11,16 @@ import {
|
|||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { getSelectedTextSafely } from "./selection";
|
import { getSelectedTextSafely } from "./selection";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
CREATIVITY_OPTIONS,
|
CREATIVITY_OPTIONS,
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
getLastUsedModel,
|
getLastUsedModel,
|
||||||
MODEL_OPTIONS,
|
MODEL_OPTIONS,
|
||||||
|
resolveRaycastModel,
|
||||||
setLastUsedModel,
|
setLastUsedModel,
|
||||||
} from "./ai";
|
} from "./ai";
|
||||||
import { getPreferences } from "./preferences";
|
import { getPreferences } from "./preferences";
|
||||||
@@ -32,31 +36,23 @@ import {
|
|||||||
SIGN_OFF_OPTIONS,
|
SIGN_OFF_OPTIONS,
|
||||||
} from "./reply";
|
} from "./reply";
|
||||||
import {
|
import {
|
||||||
createSession,
|
|
||||||
getActiveSessionId,
|
getActiveSessionId,
|
||||||
getSession,
|
|
||||||
listSessions,
|
listSessions,
|
||||||
setActiveSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
} from "./sessions";
|
||||||
import type { Creativity } from "./summarize";
|
import type { Creativity } from "./summarize";
|
||||||
import type { EntityType, VelumSession } from "./types";
|
import type { EntityType, VelumSession } from "./types";
|
||||||
import {
|
import {
|
||||||
markdownCodeBlock,
|
markdownCodeBlock,
|
||||||
mappingDetailTable,
|
mappingDetailTable,
|
||||||
NEW_SESSION_ID,
|
|
||||||
sessionSubtitle,
|
sessionSubtitle,
|
||||||
} from "./ui";
|
} from "./ui";
|
||||||
import {
|
import {
|
||||||
getEntityTypes,
|
getEntityTypes,
|
||||||
localDepseudonymize,
|
localDepseudonymize,
|
||||||
normalizePseudonymizeResponse,
|
|
||||||
pseudonymize,
|
|
||||||
} from "./velum";
|
} from "./velum";
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = ContextFormValues & {
|
||||||
text: string;
|
text: string;
|
||||||
sessionId: string;
|
|
||||||
entityTypes: string[];
|
entityTypes: string[];
|
||||||
instructions: string;
|
instructions: string;
|
||||||
};
|
};
|
||||||
@@ -67,6 +63,7 @@ export default function Command() {
|
|||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
const [greeting, setGreeting] = useState("Lieber");
|
const [greeting, setGreeting] = useState("Lieber");
|
||||||
const [signOff, setSignOff] = useState("Alles Liebe,");
|
const [signOff, setSignOff] = useState("Alles Liebe,");
|
||||||
@@ -104,8 +101,9 @@ export default function Command() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const loadedEntityTypes = await getEntityTypes();
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
setEntityTypes(loadedEntityTypes);
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
setSelectedEntityTypes(loadedEntityTypes);
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
} catch {
|
} catch {
|
||||||
setEntityTypes([]);
|
setEntityTypes([]);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -133,11 +131,6 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadSelectedText() {
|
async function loadSelectedText() {
|
||||||
const selected = await getSelectedTextSafely();
|
const selected = await getSelectedTextSafely();
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@@ -194,41 +187,25 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const session =
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
values.sessionId === NEW_SESSION_ID
|
|
||||||
? await createSession()
|
|
||||||
: ((await getSession(values.sessionId)) ?? (await createSession()));
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
|
|
||||||
const rawResult = await pseudonymize(
|
|
||||||
input,
|
|
||||||
session.mapping,
|
|
||||||
values.entityTypes,
|
|
||||||
);
|
|
||||||
const pseudoResult = normalizePseudonymizeResponse(rawResult);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
pseudoResult.mapping,
|
|
||||||
pseudoResult.selected_entity_types,
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Pseudonymisiert";
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
toast.message = `${pseudoResult.entity_count} Zuordnungen`;
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
|
||||||
push(
|
push(
|
||||||
<ConfirmReply
|
<ConfirmReply
|
||||||
session={updatedSession}
|
session={updatedSession}
|
||||||
pseudonymizedText={pseudoResult.pseudonymized_text}
|
pseudonymizedText={pseudoResult.pseudonymized_text}
|
||||||
model={model}
|
model={model}
|
||||||
creativity={creativity}
|
creativity={creativity}
|
||||||
greeting={greeting}
|
greeting={greeting}
|
||||||
signOff={signOff}
|
signOff={signOff}
|
||||||
userFullName={userFullName}
|
userFullName={userFullName}
|
||||||
instructions={values.instructions}
|
instructions={values.instructions}
|
||||||
disclosure={disclosure}
|
disclosure={disclosure}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
}} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
@@ -324,27 +301,9 @@ export default function Command() {
|
|||||||
info="Listet am Ende der Email auf, welche Originalbegriffe vor dem KI-Aufruf lokal durch Platzhalter ersetzt wurden."
|
info="Listet am Ende der Email auf, welche Originalbegriffe vor dem KI-Aufruf lokal durch Platzhalter ersetzt wurden."
|
||||||
/>
|
/>
|
||||||
<Form.Separator />
|
<Form.Separator />
|
||||||
<Form.Dropdown
|
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||||
id="sessionId"
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
title="Sitzung"
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
defaultValue={defaultSessionId}
|
|
||||||
>
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
value={NEW_SESSION_ID}
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
key={session.id}
|
|
||||||
value={session.id}
|
|
||||||
title={session.name}
|
|
||||||
icon={
|
|
||||||
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Form.Dropdown>
|
|
||||||
{entityTypes.length > 0 ? (
|
{entityTypes.length > 0 ? (
|
||||||
<Form.TagPicker
|
<Form.TagPicker
|
||||||
id="entityTypes"
|
id="entityTypes"
|
||||||
@@ -473,7 +432,7 @@ function ConfirmReply(props: StageProps) {
|
|||||||
>
|
>
|
||||||
<Form.Description
|
<Form.Description
|
||||||
title="Bestätigen"
|
title="Bestätigen"
|
||||||
text={`Prüfe den pseudonymisierten Text vor dem KI-Aufruf. Die KI verfasst die Anrede mit dem passenden Platzhalter selbst — nur die Signatur wird lokal angefügt. Sitzung: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
|
text={`Prüfe den pseudonymisierten Text vor dem KI-Aufruf. Die KI verfasst die Anrede mit dem passenden Platzhalter selbst — nur die Signatur wird lokal angefügt. Kontext: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
|
||||||
/>
|
/>
|
||||||
<Form.TextArea
|
<Form.TextArea
|
||||||
id="pseudonymizedText"
|
id="pseudonymizedText"
|
||||||
@@ -602,7 +561,7 @@ function ReplyResult(props: StageProps) {
|
|||||||
instructions: props.instructions,
|
instructions: props.instructions,
|
||||||
});
|
});
|
||||||
const stream = AI.ask(prompt, {
|
const stream = AI.ask(prompt, {
|
||||||
model: props.model as AI.Model,
|
model: resolveRaycastModel(props.model),
|
||||||
creativity: props.creativity,
|
creativity: props.creativity,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
|
|||||||
569
src/restore-project-files.tsx
Normal file
569
src/restore-project-files.tsx
Normal file
@@ -0,0 +1,569 @@
|
|||||||
|
import { Action, ActionPanel, Alert, confirmAlert, Detail, Form, Icon, List, showInFinder, showToast, Toast, useNavigation } from "@raycast/api";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { basename, dirname, extname, join } from "node:path";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { depseudonymizeDocument } from "./velum";
|
||||||
|
import { restoreXlsxFile } from "./lib/xlsx-restoration";
|
||||||
|
import { addProjectMappingEntry, canonicalProjectPath, digest, isMarkdownFile, listAllRuns, mappingForMatchingSnapshots, resolveWithin, restorePath, restoreTextWithCount, runCopiesPath, scanRestorableCopyFiles, unresolvedPlaceholderIds, updateProjectMapping, withUnambiguousHistoricalMappings } from "./lib/velum-project";
|
||||||
|
import type { ProjectFile, ProjectRun } from "./lib/velum-project";
|
||||||
|
import type { MappingEntry, PlaceholderMapping } from "./types";
|
||||||
|
import { canonicalPerson, mergePeople } from "./lib/project-review";
|
||||||
|
import { planProjectRevision, reviseProjectRun } from "./lib/project-revision";
|
||||||
|
import { TranslationTable } from "./show-translation-tables";
|
||||||
|
import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "./lib/mapping-groups";
|
||||||
|
import { releaseProjectMapping } from "./project-mapping-actions";
|
||||||
|
import { projectMappingCreatedAt } from "./lib/mapping-created-at";
|
||||||
|
import { listRestorableFolders, selectRestorableFolder } from "./lib/restore-file-selection";
|
||||||
|
import type { RestorableFolder } from "./lib/restore-file-selection";
|
||||||
|
import { RelocateProjectForm } from "./project-relocation-form";
|
||||||
|
|
||||||
|
type SavedRun = { run: ProjectRun; directory: string };
|
||||||
|
type RestoreDecision = MappingEntry | null;
|
||||||
|
|
||||||
|
class UnresolvedRestoreError extends Error {
|
||||||
|
constructor(readonly file: string, readonly ids: string[]) {
|
||||||
|
super(`${file}: ${ids.length} Platzhalter benötigen eine Zuordnung.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function RestoreDecisionForm(props: { file: string; id: string; candidates: MappingEntry[];
|
||||||
|
onSave: (decision: RestoreDecision) => void }) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
async function save(values: { choice: string; original: string }) {
|
||||||
|
const original = values.original.trim();
|
||||||
|
const candidate = values.choice.startsWith("candidate:")
|
||||||
|
? props.candidates[Number(values.choice.slice("candidate:".length))] : undefined;
|
||||||
|
if (original) props.onSave({ original, type: candidate?.type ?? props.id.replace(/_\d+$/, "") });
|
||||||
|
else if (candidate) props.onSave(candidate);
|
||||||
|
else if (values.choice === "keep") props.onSave(null);
|
||||||
|
else {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Bitte einen Klartext wählen oder bewusst unverändert lassen" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pop();
|
||||||
|
}
|
||||||
|
return <Form navigationTitle={`${props.id} in ${props.file}`}
|
||||||
|
actions={<ActionPanel><Action.SubmitForm title="Entscheidung für diesen Export übernehmen" onSubmit={save} /></ActionPanel>}>
|
||||||
|
<Form.Description text={props.candidates.length > 1
|
||||||
|
? "Dieser Platzhalter hat in gespeicherten Projektständen unterschiedliche Bedeutungen. Wähle die passende Zuordnung für diese Datei."
|
||||||
|
: props.candidates.length === 1
|
||||||
|
? "Ein früherer Projektstand enthält diesen Eintrag. Prüfe, ob er zu dieser Datei gehört."
|
||||||
|
: "Für diesen Platzhalter gibt es in den gespeicherten Projektständen keine Zuordnung. Trage den Klartext ein oder bestätige, dass er absichtlich stehen bleiben soll."} />
|
||||||
|
<Form.Dropdown id="choice" title="Zuordnung" defaultValue="choose">
|
||||||
|
<Form.Dropdown.Item value="choose" title="Bitte auswählen" />
|
||||||
|
{props.candidates.map((entry, index) => <Form.Dropdown.Item key={index}
|
||||||
|
value={`candidate:${index}`} title={`${entry.original} · ${entry.type}`} />)}
|
||||||
|
<Form.Dropdown.Item value="keep" title="Platzhalter absichtlich unverändert lassen" />
|
||||||
|
</Form.Dropdown>
|
||||||
|
<Form.TextField id="original" title="Anderen Klartext eingeben" placeholder="Optional; überschreibt die Auswahl oben" />
|
||||||
|
</Form>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RevisionReview(props: { saved: SavedRun; onSaved: () => Promise<void> }) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
const { run, directory } = props.saved;
|
||||||
|
const [release, setRelease] = useState<Set<string>>(new Set());
|
||||||
|
const [merges, setMerges] = useState<Record<string, string>>({});
|
||||||
|
const [stage, setStage] = useState<"release" | "merge">("release");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const entries = Object.entries(run.mapping);
|
||||||
|
const rootOf = (key: string): string => {
|
||||||
|
let current = key;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
while (run.mapping[current]?.merged_into && !seen.has(current)) {
|
||||||
|
seen.add(current);
|
||||||
|
current = run.mapping[current].merged_into!;
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
};
|
||||||
|
const roots = entries.filter(([key]) => rootOf(key) === key);
|
||||||
|
const byType = new Map<string, typeof roots>();
|
||||||
|
for (const item of roots) {
|
||||||
|
const type = item[1].type;
|
||||||
|
if (!byType.has(type)) byType.set(type, []);
|
||||||
|
byType.get(type)!.push(item);
|
||||||
|
}
|
||||||
|
const people = roots.filter(([key, entry]) => entry.type === "PERSON" && !release.has(key));
|
||||||
|
const variants = (key: string) => entries.filter(([candidate]) => rootOf(candidate) === key)
|
||||||
|
.map(([, entry]) => entry.original);
|
||||||
|
function toggle(key: string) {
|
||||||
|
setRelease((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
if (next.has(key)) next.delete(key); else next.add(key);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
setMerges((current) => Object.fromEntries(Object.entries(current)
|
||||||
|
.filter(([source, target]) => source !== key && target !== key)));
|
||||||
|
}
|
||||||
|
async function apply() {
|
||||||
|
const plan = planProjectRevision(run.mapping, release, merges);
|
||||||
|
if (!plan.released.length && !plan.merged.length) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Keine Änderung ausgewählt" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const inPlace = Boolean(run.inPlace || run.sourceInPlace);
|
||||||
|
if (inPlace && !(await confirmAlert({
|
||||||
|
title: "Projektdateien aktualisieren?",
|
||||||
|
message: `Der vorhandene Projektordner wird mit dem neuen Stand aktualisiert. ${plan.released.length} Zuordnungen werden freigegeben. Vorher wird außerhalb des Projektordners eine Sicherung erstellt. Zwischenzeitlich geänderte Dateien werden nicht überschrieben.`,
|
||||||
|
primaryAction: { title: "Projekt aktualisieren", style: Alert.ActionStyle.Destructive },
|
||||||
|
}))) return;
|
||||||
|
setBusy(true);
|
||||||
|
const toast = await showToast({ style: Toast.Style.Animated, title: "Neuer Projektstand wird erstellt" });
|
||||||
|
try {
|
||||||
|
const result = await reviseProjectRun({ previous: run, previousDirectory: directory,
|
||||||
|
release, merges, rewriteDocument: depseudonymizeDocument });
|
||||||
|
await props.onSaved();
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = "Projektstand aktualisiert";
|
||||||
|
toast.message = `${plan.released.length} freigegeben · ${plan.merged.length} zusammengeführt`;
|
||||||
|
pop();
|
||||||
|
await showInFinder(inPlace ? run.projectPath : runCopiesPath(result.run, result.directory)).catch(() => undefined);
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Nachbearbeitung fehlgeschlagen";
|
||||||
|
toast.message = (error as Error).message;
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
if (stage === "release") return <List isLoading={busy} navigationTitle="Zuordnungen nachbearbeiten"
|
||||||
|
searchBarPlaceholder="Begriff, Typ oder Platzhalter suchen">
|
||||||
|
<List.Section title="Weiter">
|
||||||
|
<List.Item icon={Icon.ArrowRight} title="Personen zusammenführen und Änderungen anwenden"
|
||||||
|
subtitle={`${release.size} Begriffe oder Personengruppen freigeben`}
|
||||||
|
actions={<ActionPanel><Action title="Personen prüfen" onAction={() => setStage("merge")} /></ActionPanel>} />
|
||||||
|
</List.Section>
|
||||||
|
{[...byType].map(([type, items]) => <List.Section key={type}
|
||||||
|
title={`${type} · ${items.filter(([key]) => release.has(key)).length}/${items.length} freigeben`}>
|
||||||
|
{items.map(([key, entry]) => <List.Item key={key}
|
||||||
|
icon={release.has(key) ? Icon.CheckCircle : Icon.Circle}
|
||||||
|
title={entry.original} subtitle={`→ ${key}`}
|
||||||
|
accessories={[{ text: entry.type }, ...(entry.type === "PERSON" && variants(key).length > 1
|
||||||
|
? [{ text: `${variants(key).length} Varianten` }] : [])]}
|
||||||
|
keywords={[key, entry.type, ...variants(key)]}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title={release.has(key) ? "Freigabe zurücknehmen" : "In Klartext umwandeln und ausnehmen"}
|
||||||
|
onAction={() => toggle(key)} />
|
||||||
|
<Action title="Personen prüfen" onAction={() => setStage("merge")} />
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List.Section>)}
|
||||||
|
</List>;
|
||||||
|
return <List isLoading={busy} navigationTitle="Personen nachträglich zusammenführen"
|
||||||
|
searchBarPlaceholder="Person oder Platzhalter suchen">
|
||||||
|
<List.Section title="Abschluss">
|
||||||
|
<List.Item icon={Icon.Play} title="Neuen Projektstand erstellen"
|
||||||
|
subtitle={`${release.size} Freigaben · ${Object.keys(merges).length} Zusammenführungen`}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title="Änderungen anwenden" onAction={apply} />
|
||||||
|
<Action title="Zur Freigabe zurück" onAction={() => setStage("release")} />
|
||||||
|
</ActionPanel>} />
|
||||||
|
</List.Section>
|
||||||
|
<List.Section title="Personen · optional zusammenfassen">
|
||||||
|
{people.map(([key]) => {
|
||||||
|
const target = canonicalPerson(key, merges);
|
||||||
|
const targets = people.filter(([other]) => canonicalPerson(other, merges) !== target);
|
||||||
|
return <List.Item key={key} icon={Icon.Person} title={variants(key).join(" · ")}
|
||||||
|
subtitle={`→ ${target}`}
|
||||||
|
accessories={target !== key ? [{ text: "Zusammengeführt" }] : []}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
{targets.length > 0 && <ActionPanel.Submenu title="Mit Person zusammenfassen" icon={Icon.Link}>
|
||||||
|
{targets.map(([other]) => <Action key={other}
|
||||||
|
title={`${variants(other).join(" · ")} → ${canonicalPerson(other, merges)}`}
|
||||||
|
onAction={() => setMerges((current) => mergePeople(current, key, other))} />)}
|
||||||
|
</ActionPanel.Submenu>}
|
||||||
|
{target !== key && <Action title="Zusammenführung lösen" onAction={() => setMerges((current) => {
|
||||||
|
const next = { ...current }; delete next[key]; return next;
|
||||||
|
})} />}
|
||||||
|
<Action title="Änderungen anwenden" onAction={apply} />
|
||||||
|
</ActionPanel>} />;
|
||||||
|
})}
|
||||||
|
</List.Section>
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FolderPicker(props: { folders: RestorableFolder[]; onSelect: (folder: string, includeDocuments: boolean, restoreImmediately?: boolean) => void }) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
function choose(folder: string, includeDocuments: boolean, restoreImmediately = false) {
|
||||||
|
props.onSelect(folder, includeDocuments, restoreImmediately);
|
||||||
|
pop();
|
||||||
|
}
|
||||||
|
return <List navigationTitle="Nur einen Ordner wiederherstellen" searchBarPlaceholder="Ordner suchen">
|
||||||
|
<List.Section title="Ordner samt Unterordnern · Klartext-Kopien in Downloads/Velum">
|
||||||
|
{props.folders.map((folder) => <List.Item key={folder.path} icon={Icon.Folder}
|
||||||
|
title={folder.path} subtitle={`${folder.fileCount} Dateien · ${folder.textCount} Text · ${folder.documentCount} Office`}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title={folder.documentCount > 0 ? "Ordner inklusive Office wiederherstellen" : "Ordner wiederherstellen"}
|
||||||
|
icon={Icon.Download} onAction={() => choose(folder.path, true, true)} />
|
||||||
|
{folder.documentCount > 0 && folder.textCount > 0 && <Action title="Nur Textdateien wiederherstellen"
|
||||||
|
icon={Icon.Download} onAction={() => choose(folder.path, false, true)} />}
|
||||||
|
{folder.textCount > 0 && <Action title="Nur Textdateien dieses Ordners auswählen" icon={Icon.CheckCircle}
|
||||||
|
onAction={() => choose(folder.path, false)} />}
|
||||||
|
{folder.documentCount > 0 && <Action title="Diesen Ordner inklusive Office auswählen" icon={Icon.Folder}
|
||||||
|
onAction={() => choose(folder.path, true)} />}
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List.Section>
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function FilePicker(props: { run: ProjectRun; directory: string; historical?: boolean; earlierRuns: SavedRun[] }) {
|
||||||
|
const { push } = useNavigation();
|
||||||
|
const [files, setFiles] = useState<ProjectFile[]>([]);
|
||||||
|
const [sourceRoot, setSourceRoot] = useState("");
|
||||||
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
|
const [skipped, setSkipped] = useState(0);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [unresolved, setUnresolved] = useState<Array<{ file: string; id: string }>>([]);
|
||||||
|
const [exportError, setExportError] = useState<{ title: string; message: string }>();
|
||||||
|
const [decisions, setDecisions] = useState<Record<string, Record<string, RestoreDecision>>>({});
|
||||||
|
const mappings = [props.run.mapping, ...props.earlierRuns.map((entry) => entry.run.mapping)]
|
||||||
|
.map(mappingForRestoration);
|
||||||
|
const baseMapping = withUnambiguousHistoricalMappings(mappings[0], mappings.slice(1));
|
||||||
|
const candidatesFor = (id: string): MappingEntry[] => {
|
||||||
|
const unique = new Map<string, MappingEntry>();
|
||||||
|
for (const mapping of mappings) for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
if (key.toUpperCase() === id.toUpperCase()) unique.set(`${entry.type}\0${entry.original}`, entry);
|
||||||
|
}
|
||||||
|
return [...unique.values()];
|
||||||
|
};
|
||||||
|
function saveDecision(file: string, id: string, decision: RestoreDecision) {
|
||||||
|
setDecisions((current) => ({ ...current,
|
||||||
|
[file]: { ...current[file], [id.toUpperCase()]: decision },
|
||||||
|
}));
|
||||||
|
setUnresolved((current) => current.filter((item) => item.file !== file || item.id !== id));
|
||||||
|
}
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
async function load() {
|
||||||
|
const scan = await scanRestorableCopyFiles(props.run, props.directory, !props.historical);
|
||||||
|
if (!active) return;
|
||||||
|
setSourceRoot(scan.root);
|
||||||
|
setFiles(scan.files);
|
||||||
|
setSelected(new Set(scan.files.filter((file) => file.kind === "text").map((file) => file.relPath)));
|
||||||
|
setSkipped(scan.skipped);
|
||||||
|
}
|
||||||
|
load().catch((error: Error) => {
|
||||||
|
setExportError({ title: "Kopienordner nicht lesbar", message: error.message });
|
||||||
|
return showToast({ style: Toast.Style.Failure, title: "Kopienordner nicht lesbar", message: error.message });
|
||||||
|
});
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [props.run, props.directory, props.historical]);
|
||||||
|
function toggle(path: string) {
|
||||||
|
setSelected((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
if (next.has(path)) next.delete(path);
|
||||||
|
else next.add(path);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function exportFiles(selection = selected) {
|
||||||
|
if (busy) return;
|
||||||
|
if (!selection.size) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Keine Dateien ausgewählt" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!sourceRoot) return;
|
||||||
|
setBusy(true);
|
||||||
|
setExportError(undefined);
|
||||||
|
const toast = await showToast({ style: Toast.Style.Animated, title: "Klartext-Kopien werden erstellt" });
|
||||||
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||||
|
const parent = join(homedir(), "Downloads", "Velum");
|
||||||
|
let targetRoot: string | undefined;
|
||||||
|
let activeFile: string | undefined;
|
||||||
|
try {
|
||||||
|
if (!Object.keys(baseMapping).length && !Object.keys(decisions).length) {
|
||||||
|
throw new Error("Dieser Projektstand hat keine Übersetzungstabelle.");
|
||||||
|
}
|
||||||
|
const names = new Set<string>();
|
||||||
|
const planned = files.filter((item) => selection.has(item.relPath));
|
||||||
|
let renamedFiles = 0;
|
||||||
|
let contentReplacements = 0;
|
||||||
|
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
|
||||||
|
targetRoot = await fs.mkdtemp(join(parent, `${basename(props.run.projectName)}-${stamp}-`));
|
||||||
|
for (const file of planned) {
|
||||||
|
activeFile = file.relPath;
|
||||||
|
toast.title = "Datei wird wiederhergestellt";
|
||||||
|
toast.message = file.relPath;
|
||||||
|
const source = resolveWithin(sourceRoot, file.relPath);
|
||||||
|
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Datei: ${file.relPath}`);
|
||||||
|
const mapping: PlaceholderMapping = { ...baseMapping };
|
||||||
|
const manual = decisions[file.relPath] ?? {};
|
||||||
|
for (const [id, entry] of Object.entries(manual)) if (entry) mapping[id] = entry;
|
||||||
|
let restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
|
||||||
|
if (file.kind === "document" && extname(file.relPath).toLowerCase() === ".xlsx") {
|
||||||
|
if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`);
|
||||||
|
names.add(restoredName);
|
||||||
|
if (restoredName !== file.relPath) renamedFiles++;
|
||||||
|
const target = resolveWithin(targetRoot, restoredName);
|
||||||
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
|
const restored = await restoreXlsxFile(source, target, mapping, (percent) => {
|
||||||
|
toast.title = `Excel wird lokal wiederhergestellt · ${percent} %`;
|
||||||
|
toast.message = file.relPath;
|
||||||
|
});
|
||||||
|
contentReplacements += restored.replacements;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const data = await fs.readFile(source);
|
||||||
|
let result: Buffer;
|
||||||
|
if (file.kind === "document") {
|
||||||
|
result = await depseudonymizeDocument(basename(file.relPath), data, mapping);
|
||||||
|
} else {
|
||||||
|
const markdown = isMarkdownFile(file.relPath);
|
||||||
|
const text = data.toString("utf8");
|
||||||
|
let restored = restoreTextWithCount(text, mapping, props.run.matchModes, markdown);
|
||||||
|
if (markdown) {
|
||||||
|
let missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings)
|
||||||
|
.filter((id) => manual[id.toUpperCase()] !== null);
|
||||||
|
if (missing.length) {
|
||||||
|
const exactMapping = await mappingForMatchingSnapshots(file.relPath, digest(data), props.earlierRuns);
|
||||||
|
for (const id of missing) {
|
||||||
|
const match = Object.entries(exactMapping).find(([key]) => key.toUpperCase() === id.toUpperCase());
|
||||||
|
if (match && !Object.keys(mapping).some((key) => key.toUpperCase() === id.toUpperCase())) {
|
||||||
|
mapping[match[0]] = match[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
restoredName = restorePath(file.relPath, mapping, props.run.matchModes);
|
||||||
|
restored = restoreTextWithCount(text, mapping, props.run.matchModes, true);
|
||||||
|
missing = unresolvedPlaceholderIds(`${restoredName}\n${restored.text}`, mappings)
|
||||||
|
.filter((id) => manual[id.toUpperCase()] !== null);
|
||||||
|
}
|
||||||
|
if (missing.length) throw new UnresolvedRestoreError(file.relPath, missing);
|
||||||
|
}
|
||||||
|
contentReplacements += restored.replacements;
|
||||||
|
result = Buffer.from(restored.text, "utf8");
|
||||||
|
}
|
||||||
|
if (names.has(restoredName)) throw new Error(`Mehrdeutiger Ausgabename: ${restoredName}`);
|
||||||
|
names.add(restoredName);
|
||||||
|
if (restoredName !== file.relPath) renamedFiles++;
|
||||||
|
const target = resolveWithin(targetRoot, restoredName);
|
||||||
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.writeFile(target, result, { flag: "wx", mode: 0o600 });
|
||||||
|
}
|
||||||
|
if (!renamedFiles && !contentReplacements && planned.every((file) => file.kind === "text")
|
||||||
|
&& !planned.some((file) => Object.values(decisions[file.relPath] ?? {}).includes(null))) {
|
||||||
|
throw new Error("Keine passenden Velum-Platzhalter in den ausgewählten Textdateien oder Dateinamen gefunden. Bitte Quelle und Projektstand prüfen.");
|
||||||
|
}
|
||||||
|
setUnresolved([]);
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = `${selection.size} Klartext-Dateien in Downloads`;
|
||||||
|
const deliberatelyKept = planned.reduce((count, file) => count
|
||||||
|
+ Object.values(decisions[file.relPath] ?? {}).filter((entry) => entry === null).length, 0);
|
||||||
|
toast.message = `${contentReplacements} Textersetzungen · ${renamedFiles} Dateinamen geändert`
|
||||||
|
+ (deliberatelyKept ? ` · ${deliberatelyKept} Platzhalter bewusst belassen` : "")
|
||||||
|
+ (planned.some((file) => file.kind === "document" && extname(file.relPath).toLowerCase() !== ".xlsx") ? " · DOCX/PPTX-Inhalte nicht gezählt" : "");
|
||||||
|
await showInFinder(targetRoot).catch(() => undefined);
|
||||||
|
} catch (error) {
|
||||||
|
if (targetRoot) await fs.rm(targetRoot, { recursive: true, force: true });
|
||||||
|
if (error instanceof UnresolvedRestoreError) setUnresolved(error.ids.map((id) => ({ file: error.file, id })));
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = error instanceof UnresolvedRestoreError ? "Platzhalter zuordnen" : "Klartext-Export fehlgeschlagen";
|
||||||
|
toast.message = error instanceof UnresolvedRestoreError
|
||||||
|
? `${error.file}: ${error.ids.join(", ")}. Bitte die Einträge unten klären und den Export erneut starten.`
|
||||||
|
: `${activeFile ? activeFile + ": " : ""}${error instanceof Error ? error.message : String(error)}`;
|
||||||
|
setExportError({ title: toast.title, message: toast.message });
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
const textFiles = files.filter((file) => file.kind === "text");
|
||||||
|
const complexFiles = files.filter((file) => file.kind === "document");
|
||||||
|
const folders = listRestorableFolders(files);
|
||||||
|
const allSelected = files.length > 0 && selected.size === files.length;
|
||||||
|
const selectOnlyFolder = (folder: string, includeDocuments = false, restoreImmediately = false) => {
|
||||||
|
const selection = selectRestorableFolder(files, folder, includeDocuments);
|
||||||
|
setSelected(selection);
|
||||||
|
if (restoreImmediately) void exportFiles(selection);
|
||||||
|
};
|
||||||
|
const openFolderPicker = () => push(<FolderPicker folders={folders} onSelect={selectOnlyFolder} />);
|
||||||
|
const selectionActions = () => <ActionPanel.Section title="Dateiauswahl">
|
||||||
|
<Action title={allSelected ? "Alle Dateien abwählen" : "Alle Dateien auswählen (inklusive Office)"}
|
||||||
|
shortcut={{ modifiers: ["cmd", "shift"], key: "a" }}
|
||||||
|
onAction={() => setSelected((current) => current.size === files.length
|
||||||
|
? new Set() : new Set(files.map((file) => file.relPath)))} />
|
||||||
|
<Action title="Nur Textdateien auswählen" onAction={() => setSelected(new Set(textFiles.map((item) => item.relPath)))} />
|
||||||
|
<Action title="Keine auswählen" onAction={() => setSelected(new Set())} />
|
||||||
|
{folders.length > 0 && <Action title="Nur einen Ordner auswählen" icon={Icon.Folder}
|
||||||
|
shortcut={{ modifiers: ["cmd", "shift"], key: "o" }} onAction={openFolderPicker} />}
|
||||||
|
</ActionPanel.Section>;
|
||||||
|
const sourceLabel = props.historical ? "Gespeicherter Projektstand"
|
||||||
|
: props.run.inPlace || props.run.sourceInPlace ? "Aktueller Projektordner" : "Pseudonymisierte Kopien";
|
||||||
|
const renderFile = (file: ProjectFile) => {
|
||||||
|
const fileFolder = folders.find((folder) => folder.path === dirname(file.relPath));
|
||||||
|
const displayMapping: PlaceholderMapping = { ...baseMapping };
|
||||||
|
for (const [id, entry] of Object.entries(decisions[file.relPath] ?? {})) if (entry) displayMapping[id] = entry;
|
||||||
|
return <List.Item key={file.relPath}
|
||||||
|
icon={selected.has(file.relPath) ? Icon.CheckCircle : Icon.Circle}
|
||||||
|
title={restorePath(file.relPath, displayMapping, props.run.matchModes)} subtitle={file.relPath}
|
||||||
|
accessories={file.kind === "document" ? [{ text: "Office · manuell auswählen" }] : []}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title={selected.has(file.relPath) ? "Datei abwählen" : "Datei auswählen"} onAction={() => toggle(file.relPath)} />
|
||||||
|
<Action title="Auswahl nach Downloads wiederherstellen" icon={Icon.Download} onAction={() => exportFiles()} />
|
||||||
|
{fileFolder && <Action title={fileFolder.textCount > 0
|
||||||
|
? "Nur Textdateien dieses Ordners auswählen" : "Diesen Ordner inklusive Office auswählen"}
|
||||||
|
icon={Icon.Folder} onAction={() => selectOnlyFolder(fileFolder.path, fileFolder.textCount === 0)} />}
|
||||||
|
{selectionActions()}
|
||||||
|
</ActionPanel>} />;
|
||||||
|
};
|
||||||
|
return <List isLoading={busy || (!sourceRoot && !exportError)} navigationTitle={`${props.run.projectName}: Dateien für Klartext wählen`}
|
||||||
|
searchBarPlaceholder="Dateien filtern">
|
||||||
|
<List.Section title={`${selected.size} von ${files.length} Dateien ausgewählt · ${skipped} übersprungen`}>
|
||||||
|
<List.Item key="export" icon={Icon.Download} title="Ausgewählte Dateien wiederherstellen"
|
||||||
|
subtitle="Klartext-Kopien in Downloads/Velum erstellen · Office-Dateien nur nach Auswahl"
|
||||||
|
actions={<ActionPanel><Action title="Auswahl nach Downloads wiederherstellen"
|
||||||
|
icon={Icon.Download} onAction={() => exportFiles()} />{selectionActions()}</ActionPanel>} />
|
||||||
|
{folders.length > 0 && <List.Item key="folders" icon={Icon.Folder}
|
||||||
|
title="Einzelnen Ordner wiederherstellen"
|
||||||
|
subtitle={`${folders.length} Ordner · jeweils inklusive Unterordnern`}
|
||||||
|
actions={<ActionPanel><Action title="Ordner zur Wiederherstellung wählen" icon={Icon.Folder}
|
||||||
|
onAction={openFolderPicker} />{selectionActions()}</ActionPanel>} />}
|
||||||
|
<List.Item key="source" icon={Icon.Folder} title={sourceLabel} subtitle={sourceRoot}
|
||||||
|
actions={<ActionPanel><Action title="Quellordner im Finder anzeigen" onAction={() => showInFinder(sourceRoot)} />
|
||||||
|
{selectionActions()}</ActionPanel>} />
|
||||||
|
</List.Section>
|
||||||
|
{exportError && <List.Section title={exportError.title}>
|
||||||
|
<List.Item icon={Icon.ExclamationMark} title="Fehlerdetails anzeigen" subtitle={exportError.message}
|
||||||
|
keywords={files.map((file) => file.relPath)} actions={<ActionPanel>
|
||||||
|
<Action.Push title="Fehlerdetails anzeigen" target={<Detail markdown={exportError.message.replace(/</g, "<")} />} />
|
||||||
|
<Action.CopyToClipboard title="Fehlermeldung kopieren" content={exportError.message} />
|
||||||
|
<Action title="Wiederherstellung erneut starten" icon={Icon.Download} onAction={() => exportFiles()} />
|
||||||
|
</ActionPanel>} />
|
||||||
|
</List.Section>}
|
||||||
|
{unresolved.some((item) => selected.has(item.file)) && <List.Section title="Platzhalter für diesen Export klären">
|
||||||
|
{unresolved.filter((item) => selected.has(item.file)).map(({ file, id }) => {
|
||||||
|
const candidates = candidatesFor(id);
|
||||||
|
return <List.Item key={`${file}:${id}`} icon={Icon.ExclamationMark}
|
||||||
|
title={id} subtitle={file}
|
||||||
|
accessories={[{ text: candidates.length > 1 ? `${candidates.length} verschiedene alte Zuordnungen`
|
||||||
|
: candidates.length ? "Gespeicherter Eintrag – bitte prüfen" : "Kein gespeicherter Eintrag" }]}
|
||||||
|
actions={<ActionPanel><Action title="Zuordnung festlegen" icon={Icon.Pencil}
|
||||||
|
onAction={() => push(<RestoreDecisionForm file={file} id={id} candidates={candidates}
|
||||||
|
onSave={(decision) => saveDecision(file, id, decision)} />)} />{selectionActions()}</ActionPanel>} />;
|
||||||
|
})}
|
||||||
|
</List.Section>}
|
||||||
|
<List.Section title={`Textdateien · ${textFiles.length} · standardmäßig ausgewählt`}>
|
||||||
|
{textFiles.map(renderFile)}
|
||||||
|
</List.Section>
|
||||||
|
<List.Section title={`Office-Dateien · ${complexFiles.length} · bewusst auswählen`}>
|
||||||
|
{complexFiles.map(renderFile)}
|
||||||
|
</List.Section>
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectHistory(props: { projectName: string; entries: SavedRun[] }) {
|
||||||
|
const { push } = useNavigation();
|
||||||
|
return <List navigationTitle={`${props.projectName}: frühere Stände`}
|
||||||
|
searchBarPlaceholder="Stand suchen">
|
||||||
|
<List.Section title="Frühere Stände · nur für Klartext-Export">
|
||||||
|
{props.entries.map(({ run, directory }, index) => <List.Item key={run.id} icon={Icon.Clock}
|
||||||
|
title={new Date(run.createdAt).toLocaleString("de-AT")}
|
||||||
|
subtitle={`${run.files.length} Dateien`}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title="Gespeicherten Stand wiederherstellen" icon={Icon.Download}
|
||||||
|
onAction={() => push(<FilePicker run={run} directory={directory} historical
|
||||||
|
earlierRuns={props.entries.slice(index + 1)} />)} />
|
||||||
|
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
|
||||||
|
target={<TranslationTable title={`${props.projectName} · ${new Date(run.createdAt).toLocaleString("de-AT")}`}
|
||||||
|
mapping={run.mapping}
|
||||||
|
createdAtByKey={projectMappingCreatedAt(props.entries.slice(index).map((entry) => entry.run), run.mapping)} />} />
|
||||||
|
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
|
||||||
|
onAction={() => showInFinder(runCopiesPath(run, directory))} />
|
||||||
|
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
|
||||||
|
{run.copyPath && <Action title="Aktuelle Dateien dieses Kopienordners wiederherstellen" icon={Icon.Download}
|
||||||
|
onAction={() => push(<FilePicker run={run} directory={directory}
|
||||||
|
earlierRuns={props.entries.slice(index + 1)} />)} />}
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List.Section>
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
const { push } = useNavigation();
|
||||||
|
const [runs, setRuns] = useState<SavedRun[]>([]);
|
||||||
|
const [busy, setBusy] = useState(true);
|
||||||
|
useEffect(() => {
|
||||||
|
listAllRuns().then(setRuns).catch((error: Error) => showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Projektstände nicht lesbar", message: error.message })).finally(() => setBusy(false));
|
||||||
|
}, []);
|
||||||
|
async function refresh() { setRuns(await listAllRuns()); }
|
||||||
|
async function repairMergedPeople(saved: SavedRun) {
|
||||||
|
const { run, directory } = saved;
|
||||||
|
const inPlace = Boolean(run.inPlace || run.sourceInPlace);
|
||||||
|
if (inPlace && !(await confirmAlert({
|
||||||
|
title: "Zusammengeführte Personen in Projektdateien reparieren?",
|
||||||
|
message: "Der aktuelle Projektordner wird aktualisiert. Vorher erstellt Velum außerhalb des Projektordners eine Sicherung. Zwischenzeitlich geänderte Dateien werden nicht überschrieben.",
|
||||||
|
primaryAction: { title: "Projektdateien reparieren", style: Alert.ActionStyle.Destructive },
|
||||||
|
}))) return;
|
||||||
|
setBusy(true);
|
||||||
|
const toast = await showToast({ style: Toast.Style.Animated, title: "Personenplatzhalter werden bereinigt" });
|
||||||
|
try {
|
||||||
|
const result = await reviseProjectRun({ previous: run, previousDirectory: directory,
|
||||||
|
release: new Set(), merges: {}, reapplyMerges: true, rewriteDocument: depseudonymizeDocument });
|
||||||
|
await refresh();
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = "Projektstand repariert";
|
||||||
|
toast.message = "Zusammengeführte Personen wurden in Dateien und Dateinamen erneut angewendet.";
|
||||||
|
await showInFinder(inPlace ? run.projectPath : runCopiesPath(result.run, result.directory)).catch(() => undefined);
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Reparatur fehlgeschlagen";
|
||||||
|
toast.message = (error as Error).message;
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
const projects = new Map<string, SavedRun[]>();
|
||||||
|
for (const entry of runs) {
|
||||||
|
const path = canonicalProjectPath(entry.run.projectPath);
|
||||||
|
if (!projects.has(path)) projects.set(path, []);
|
||||||
|
projects.get(path)!.push(entry);
|
||||||
|
}
|
||||||
|
return <List isLoading={busy} navigationTitle="Projekte nachbearbeiten oder rückübersetzen" searchBarPlaceholder="Projekt suchen">
|
||||||
|
<List.EmptyView title="Noch keine Projektstände" description="Zuerst Dateien mit Velum pseudonymisieren." />
|
||||||
|
{[...projects].map(([path, entries]) => {
|
||||||
|
const [{ run, directory }] = entries;
|
||||||
|
return <List.Item key={path} icon={Icon.Folder}
|
||||||
|
title={run.projectName} subtitle={path}
|
||||||
|
accessories={[{ text: `${run.files.length} Dateien` }, { text: new Date(run.createdAt).toLocaleString("de-AT") },
|
||||||
|
...(entries.length > 1 ? [{ text: `${entries.length} Stände` }] : [])]}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action title="Projektdateien als Klartext wiederherstellen" icon={Icon.Download}
|
||||||
|
onAction={() => push(<FilePicker run={run} directory={directory}
|
||||||
|
earlierRuns={entries.slice(1)} />)} />
|
||||||
|
<Action.Push title="Übersetzungstabelle anzeigen" icon={Icon.List}
|
||||||
|
target={<TranslationTable title={run.projectName} mapping={run.mapping}
|
||||||
|
createdAtByKey={projectMappingCreatedAt(entries.map((entry) => entry.run), run.mapping)}
|
||||||
|
onAdd={async (input) => {
|
||||||
|
const updated = await addProjectMappingEntry(run.projectPath, input);
|
||||||
|
await refresh();
|
||||||
|
return updated.mapping;
|
||||||
|
}}
|
||||||
|
onMerge={async (from, into) => {
|
||||||
|
const updated = await updateProjectMapping(run.projectPath,
|
||||||
|
(current) => mergeMappingGroups(current, from, into));
|
||||||
|
await refresh();
|
||||||
|
return updated.mapping;
|
||||||
|
}}
|
||||||
|
onDetach={async (key) => {
|
||||||
|
const updated = await updateProjectMapping(run.projectPath,
|
||||||
|
(current) => detachMappingGroup(current, key));
|
||||||
|
await refresh();
|
||||||
|
return updated.mapping;
|
||||||
|
}}
|
||||||
|
removeDescription="Die gesamte Gruppe wird als Projektausnahme gespeichert. Auch zwischenzeitlich bearbeitete Projektdateien werden anhand ihres aktuellen Stands korrigiert und vorher gesichert."
|
||||||
|
onRemove={async (root) => {
|
||||||
|
const revised = await releaseProjectMapping(run.projectPath, root);
|
||||||
|
await refresh();
|
||||||
|
return revised.run.mapping;
|
||||||
|
}} />} />
|
||||||
|
<Action title="Pseudonymisierte Kopien im Finder anzeigen" icon={Icon.Folder}
|
||||||
|
onAction={() => showInFinder(runCopiesPath(run, directory))} />
|
||||||
|
<Action.CopyToClipboard title="Speicherpfad kopieren" content={runCopiesPath(run, directory)} />
|
||||||
|
<Action title="Aktuellen Stand nachbearbeiten" icon={Icon.Pencil}
|
||||||
|
onAction={() => push(<RevisionReview saved={{ run, directory }} onSaved={refresh} />)} />
|
||||||
|
<Action title="Projektordner ändern" icon={Icon.Folder}
|
||||||
|
onAction={() => push(<RelocateProjectForm projectName={run.projectName}
|
||||||
|
oldPath={path} onMoved={refresh} />)} />
|
||||||
|
{Object.values(run.mapping).some((entry) => entry.type === "PERSON" && entry.merged_into)
|
||||||
|
&& <Action title="Zusammengeführte Personen in Dateien reparieren" icon={Icon.Pencil}
|
||||||
|
onAction={() => repairMergedPeople({ run, directory })} />}
|
||||||
|
{entries.length > 1 && <Action title="Frühere Stände anzeigen" icon={Icon.Clock}
|
||||||
|
onAction={() => push(<ProjectHistory projectName={run.projectName} entries={entries.slice(1)} />)} />}
|
||||||
|
</ActionPanel>} />;
|
||||||
|
})}
|
||||||
|
</List>;
|
||||||
|
}
|
||||||
72
src/rich-clipboard.ts
Normal file
72
src/rich-clipboard.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import { Clipboard, closeMainWindow } from "@raycast/api";
|
||||||
|
import { execFile, spawn } from "node:child_process";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
|
// Raycast 2.0 Beta writes only plain text for Clipboard.copy({ html, text }).
|
||||||
|
// Set both pasteboard types directly; environment variables avoid shell quoting.
|
||||||
|
const RICH_COPY_SCRIPT = [
|
||||||
|
"ObjC.import('AppKit');",
|
||||||
|
"const env = $.NSProcessInfo.processInfo.environment;",
|
||||||
|
"const html = env.objectForKey('VELUM_HTML');",
|
||||||
|
"const text = env.objectForKey('VELUM_TEXT');",
|
||||||
|
"const pb = $.NSPasteboard.generalPasteboard;",
|
||||||
|
"pb.clearContents;",
|
||||||
|
"pb.setStringForType(html, 'public.html');",
|
||||||
|
"pb.setStringForType(text, 'public.utf8-plain-text');",
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
const RICH_READ_SCRIPT = [
|
||||||
|
"ObjC.import('AppKit');",
|
||||||
|
"const pb = $.NSPasteboard.generalPasteboard;",
|
||||||
|
"const html = pb.stringForType('public.html') || pb.stringForType('text/html');",
|
||||||
|
"const rtf = html ? null : pb.dataForType('public.rtf');",
|
||||||
|
"JSON.stringify({ html: html ? ObjC.unwrap(html) : null, rtf: rtf ? ObjC.unwrap(rtf.base64EncodedStringWithOptions(0)) : null });",
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
async function htmlFromRtf(encoded: string): Promise<string | undefined> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const child = spawn("textutil", ["-convert", "html", "-stdin", "-stdout"]);
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||||
|
child.on("error", () => resolve(undefined));
|
||||||
|
child.on("close", (code) => resolve(code === 0 ? Buffer.concat(chunks).toString("utf8") : undefined));
|
||||||
|
child.stdin.on("error", () => undefined);
|
||||||
|
child.stdin.end(Buffer.from(encoded, "base64"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Raycast's clipboard reader can omit HTML/RTF from app selections such as Teams. */
|
||||||
|
export async function readRichClipboardHtml(): Promise<string | undefined> {
|
||||||
|
const raycast = await Clipboard.read().catch(() => undefined);
|
||||||
|
if (raycast?.html) return raycast.html;
|
||||||
|
try {
|
||||||
|
const { stdout } = await execFileAsync("osascript", ["-l", "JavaScript", "-e", RICH_READ_SCRIPT],
|
||||||
|
{ maxBuffer: 16 * 1024 * 1024 });
|
||||||
|
const native = JSON.parse(stdout.trim()) as { html: string | null; rtf: string | null };
|
||||||
|
if (native.html) return native.html;
|
||||||
|
if (native.rtf) return await htmlFromRtf(native.rtf);
|
||||||
|
} catch {
|
||||||
|
// Plain text remains available even if macOS cannot expose the rich pasteboard types.
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function copyRichText(html: string, text: string): Promise<void> {
|
||||||
|
await execFileAsync(
|
||||||
|
"osascript",
|
||||||
|
["-l", "JavaScript", "-e", RICH_COPY_SCRIPT],
|
||||||
|
{
|
||||||
|
env: { ...process.env, VELUM_HTML: html, VELUM_TEXT: text },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Paste the rich pasteboard data without Raycast replacing it with plain text. */
|
||||||
|
export async function pasteRichText(html: string, text: string): Promise<void> {
|
||||||
|
await copyRichText(html, text);
|
||||||
|
await closeMainWindow();
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||||
|
await execFileAsync("osascript", ["-e", 'tell application "System Events" to keystroke "v" using command down']);
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
import { LocalStorage } from "@raycast/api";
|
import { LocalStorage } from "@raycast/api";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { getPreferences } from "./preferences";
|
import { getPreferences } from "./preferences";
|
||||||
import type { PlaceholderMapping, SessionMode, VelumSession } from "./types";
|
import type { PlaceholderMapping, VelumSession } from "./types";
|
||||||
|
import { mappingRoot } from "./lib/mapping-groups";
|
||||||
|
import { whitelistKey } from "./lib/project-whitelist";
|
||||||
|
|
||||||
const SESSIONS_STORAGE_KEY = "velum.sessions.v1";
|
const SESSIONS_STORAGE_KEY = "velum.sessions.v1";
|
||||||
const ACTIVE_SESSION_STORAGE_KEY = "velum.sessions.active.v1";
|
const ACTIVE_SESSION_STORAGE_KEY = "velum.sessions.active.v1";
|
||||||
@@ -10,14 +12,25 @@ function nowIso(): string {
|
|||||||
return new Date().toISOString();
|
return new Date().toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function dayKey(date = new Date()): string {
|
|
||||||
return date.toISOString().slice(0, 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
function sessionSort(a: VelumSession, b: VelumSession): number {
|
function sessionSort(a: VelumSession, b: VelumSession): number {
|
||||||
return Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
|
return Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mappingDates(previous: VelumSession | undefined, mapping: PlaceholderMapping,
|
||||||
|
timestamp: string): Record<string, string> {
|
||||||
|
const dates: Record<string, string> = {};
|
||||||
|
const previousKeys = new Map(Object.entries(previous?.mapping ?? {})
|
||||||
|
.map(([key, entry]) => [key.replace(/^<|>$/g, ""), { key, entry }]));
|
||||||
|
for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
const prior = previousKeys.get(key.replace(/^<|>$/g, ""));
|
||||||
|
if (prior && prior.entry.type === entry.type && prior.entry.original === entry.original) {
|
||||||
|
const originalDate = previous?.mappingCreatedAt?.[prior.key];
|
||||||
|
if (originalDate) dates[key] = originalDate;
|
||||||
|
} else dates[key] = timestamp;
|
||||||
|
}
|
||||||
|
return dates;
|
||||||
|
}
|
||||||
|
|
||||||
async function saveSessions(sessions: VelumSession[]): Promise<void> {
|
async function saveSessions(sessions: VelumSession[]): Promise<void> {
|
||||||
const maxSessions = getPreferences().maxSessions;
|
const maxSessions = getPreferences().maxSessions;
|
||||||
const pruned = [...sessions].sort(sessionSort).slice(0, maxSessions);
|
const pruned = [...sessions].sort(sessionSort).slice(0, maxSessions);
|
||||||
@@ -52,14 +65,17 @@ export async function setActiveSession(id: string): Promise<void> {
|
|||||||
await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id);
|
await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createSession(name?: string): Promise<VelumSession> {
|
export async function createSession(name?: string,
|
||||||
|
initial?: Pick<VelumSession, "mapping" | "entityTypes" | "excludedTerms" | "customTerms">): Promise<VelumSession> {
|
||||||
const timestamp = nowIso();
|
const timestamp = nowIso();
|
||||||
const session: VelumSession = {
|
const session: VelumSession = {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
name: name || `Sitzung ${new Date().toLocaleString()}`,
|
name: name?.trim() || `Sitzung ${new Date().toLocaleString()}`,
|
||||||
createdAt: timestamp,
|
createdAt: timestamp,
|
||||||
updatedAt: timestamp,
|
updatedAt: timestamp,
|
||||||
mapping: {},
|
mapping: {},
|
||||||
|
...initial,
|
||||||
|
...(initial && { mappingCreatedAt: mappingDates(undefined, initial.mapping, timestamp) }),
|
||||||
};
|
};
|
||||||
|
|
||||||
const sessions = await listSessions();
|
const sessions = await listSessions();
|
||||||
@@ -85,36 +101,12 @@ export async function getActiveSession(): Promise<VelumSession> {
|
|||||||
return createSession();
|
return createSession();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveSessionForMode(
|
|
||||||
mode: SessionMode,
|
|
||||||
): Promise<VelumSession> {
|
|
||||||
if (mode === "new-each-request") {
|
|
||||||
return createSession(`Anfrage ${new Date().toLocaleString()}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mode === "daily") {
|
|
||||||
const name = `Tag ${dayKey()}`;
|
|
||||||
const existing = (await listSessions()).find(
|
|
||||||
(session) => session.name === name,
|
|
||||||
);
|
|
||||||
if (existing) {
|
|
||||||
await setActiveSession(existing.id);
|
|
||||||
return existing;
|
|
||||||
}
|
|
||||||
return createSession(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
return getActiveSession();
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function resolveDefaultSession(): Promise<VelumSession> {
|
|
||||||
return resolveSessionForMode(getPreferences().sessionMode);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateSessionMapping(
|
export async function updateSessionMapping(
|
||||||
id: string,
|
id: string,
|
||||||
mapping: PlaceholderMapping,
|
mapping: PlaceholderMapping,
|
||||||
entityTypes?: string[],
|
entityTypes?: string[],
|
||||||
|
excludedTerms?: VelumSession["excludedTerms"],
|
||||||
|
customTerms?: VelumSession["customTerms"],
|
||||||
): Promise<VelumSession> {
|
): Promise<VelumSession> {
|
||||||
const sessions = await listSessions();
|
const sessions = await listSessions();
|
||||||
const timestamp = nowIso();
|
const timestamp = nowIso();
|
||||||
@@ -128,6 +120,9 @@ export async function updateSessionMapping(
|
|||||||
updatedAt: timestamp,
|
updatedAt: timestamp,
|
||||||
mapping,
|
mapping,
|
||||||
entityTypes,
|
entityTypes,
|
||||||
|
excludedTerms,
|
||||||
|
customTerms,
|
||||||
|
mappingCreatedAt: mappingDates(undefined, mapping, timestamp),
|
||||||
};
|
};
|
||||||
await saveSessions([created, ...sessions]);
|
await saveSessions([created, ...sessions]);
|
||||||
return created;
|
return created;
|
||||||
@@ -137,6 +132,9 @@ export async function updateSessionMapping(
|
|||||||
...sessions[index],
|
...sessions[index],
|
||||||
mapping,
|
mapping,
|
||||||
entityTypes,
|
entityTypes,
|
||||||
|
excludedTerms: excludedTerms ?? sessions[index].excludedTerms,
|
||||||
|
customTerms: customTerms ?? sessions[index].customTerms,
|
||||||
|
mappingCreatedAt: mappingDates(sessions[index], mapping, timestamp),
|
||||||
updatedAt: timestamp,
|
updatedAt: timestamp,
|
||||||
};
|
};
|
||||||
const next = [...sessions];
|
const next = [...sessions];
|
||||||
@@ -145,6 +143,18 @@ export async function updateSessionMapping(
|
|||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function releaseSessionMappingGroup(id: string, root: string): Promise<VelumSession> {
|
||||||
|
const session = await getSession(id);
|
||||||
|
if (!session) throw new Error("Sitzung nicht gefunden.");
|
||||||
|
if (!session.mapping[root]) throw new Error("Zuordnung nicht gefunden. Bitte die Ansicht aktualisieren.");
|
||||||
|
const removed = Object.keys(session.mapping).filter((key) => mappingRoot(key, session.mapping) === root);
|
||||||
|
const mapping = Object.fromEntries(Object.entries(session.mapping).filter(([key]) => !removed.includes(key)));
|
||||||
|
const excludedTerms = [...new Map([...(session.excludedTerms ?? []),
|
||||||
|
...removed.map((key) => ({ type: session.mapping[key].type, original: session.mapping[key].original }))]
|
||||||
|
.map((entry) => [whitelistKey(entry), entry])).values()];
|
||||||
|
return updateSessionMapping(id, mapping, session.entityTypes, excludedTerms);
|
||||||
|
}
|
||||||
|
|
||||||
export async function renameSession(id: string, name: string): Promise<void> {
|
export async function renameSession(id: string, name: string): Promise<void> {
|
||||||
const sessions = await listSessions();
|
const sessions = await listSessions();
|
||||||
await saveSessions(
|
await saveSessions(
|
||||||
@@ -161,7 +171,7 @@ export async function clearSessionMapping(id: string): Promise<void> {
|
|||||||
await saveSessions(
|
await saveSessions(
|
||||||
sessions.map((session) =>
|
sessions.map((session) =>
|
||||||
session.id === id
|
session.id === id
|
||||||
? { ...session, mapping: {}, updatedAt: nowIso() }
|
? { ...session, mapping: {}, mappingCreatedAt: {}, updatedAt: nowIso() }
|
||||||
: session,
|
: session,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -186,7 +196,3 @@ export async function deleteAllSessions(): Promise<void> {
|
|||||||
await LocalStorage.removeItem(SESSIONS_STORAGE_KEY);
|
await LocalStorage.removeItem(SESSIONS_STORAGE_KEY);
|
||||||
await LocalStorage.removeItem(ACTIVE_SESSION_STORAGE_KEY);
|
await LocalStorage.removeItem(ACTIVE_SESSION_STORAGE_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function countMappingEntries(mapping: PlaceholderMapping): number {
|
|
||||||
return Object.keys(mapping).length;
|
|
||||||
}
|
|
||||||
|
|||||||
516
src/show-translation-tables.tsx
Normal file
516
src/show-translation-tables.tsx
Normal file
@@ -0,0 +1,516 @@
|
|||||||
|
import {
|
||||||
|
Action,
|
||||||
|
ActionPanel,
|
||||||
|
Alert,
|
||||||
|
confirmAlert,
|
||||||
|
Detail,
|
||||||
|
Form,
|
||||||
|
Icon,
|
||||||
|
List,
|
||||||
|
showToast,
|
||||||
|
showInFinder,
|
||||||
|
Toast,
|
||||||
|
useNavigation,
|
||||||
|
} from "@raycast/api";
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry, updateProjectMapping } from "./lib/velum-project";
|
||||||
|
import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
|
||||||
|
import {
|
||||||
|
clearSessionMapping,
|
||||||
|
createSession,
|
||||||
|
deleteAllSessions,
|
||||||
|
deleteSession,
|
||||||
|
getActiveSessionId,
|
||||||
|
getSession,
|
||||||
|
listSessions,
|
||||||
|
releaseSessionMappingGroup,
|
||||||
|
renameSession,
|
||||||
|
setActiveSession,
|
||||||
|
updateSessionMapping,
|
||||||
|
} from "./sessions";
|
||||||
|
import type { PlaceholderMapping, VelumSession } from "./types";
|
||||||
|
import { mappingSummary, sessionSubtitle } from "./ui";
|
||||||
|
import { releaseProjectMapping } from "./project-mapping-actions";
|
||||||
|
import { projectMappingCreatedAt, sortMappingRowsByCreatedAt } from "./lib/mapping-created-at";
|
||||||
|
import type { ProjectRun } from "./lib/velum-project";
|
||||||
|
import { RelocateProjectForm } from "./project-relocation-form";
|
||||||
|
|
||||||
|
import { writeMappingExport } from "./lib/mapping-export";
|
||||||
|
import type { MappingExportKind } from "./lib/mapping-export";
|
||||||
|
|
||||||
|
type TableSource = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
subtitle: string;
|
||||||
|
mapping: PlaceholderMapping;
|
||||||
|
createdAtByKey: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ManualEntry = { original: string; type: string; placeholder?: string };
|
||||||
|
const EMPTY_DATES: Record<string, string> = {};
|
||||||
|
|
||||||
|
function AddMappingForm(props: { onAdd: (input: ManualEntry) => Promise<PlaceholderMapping>;
|
||||||
|
onSaved: (mapping: PlaceholderMapping) => void }) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
async function save(values: { original: string; type: string; placeholder: string }) {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const type = values.type.trim() || /^([A-ZÄÖÜ][A-ZÄÖÜ0-9_]*)_\d+$/iu.exec(values.placeholder.trim())?.[1] || "BEGRIFF";
|
||||||
|
const mapping = await props.onAdd({ ...values, type });
|
||||||
|
props.onSaved(mapping);
|
||||||
|
await showToast({ style: Toast.Style.Success, title: "Zuordnung gespeichert" });
|
||||||
|
pop();
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Zuordnung nicht gespeichert",
|
||||||
|
message: (error as Error).message });
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
return <Form isLoading={busy} navigationTitle="Zuordnung ergänzen"
|
||||||
|
actions={<ActionPanel><Action.SubmitForm title="Zuordnung speichern" onSubmit={save} /></ActionPanel>}>
|
||||||
|
<Form.Description text="Der Eintrag wird zur Wiederherstellung verwendet. Für eine garantierte Maskierung bei künftigen Projektläufen zusätzlich eine Projektregel anlegen." />
|
||||||
|
<Form.TextField id="original" title="Klartext-Begriff" placeholder="Originalwert" />
|
||||||
|
<Form.TextField id="type" title="Kategorie (optional)" placeholder="Aus Platzhalter ableiten; sonst BEGRIFF" />
|
||||||
|
<Form.TextField id="placeholder" title="Platzhalter (optional)" placeholder="z. B. PERSON_61; leer = nächste freie Nummer" />
|
||||||
|
</Form>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TranslationTable({
|
||||||
|
title,
|
||||||
|
mapping,
|
||||||
|
createdAtByKey = EMPTY_DATES,
|
||||||
|
onAdd,
|
||||||
|
onMerge,
|
||||||
|
onDetach,
|
||||||
|
onRemove,
|
||||||
|
removeDescription,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
mapping: PlaceholderMapping;
|
||||||
|
createdAtByKey?: Record<string, string>;
|
||||||
|
onAdd?: (input: ManualEntry) => Promise<PlaceholderMapping>;
|
||||||
|
onMerge?: (source: string, target: string) => Promise<PlaceholderMapping>;
|
||||||
|
onDetach?: (key: string) => Promise<PlaceholderMapping>;
|
||||||
|
onRemove?: (root: string) => Promise<PlaceholderMapping>;
|
||||||
|
removeDescription?: string;
|
||||||
|
}) {
|
||||||
|
const { push, pop } = useNavigation();
|
||||||
|
const [visibleMapping, setVisibleMapping] = useState(mapping);
|
||||||
|
const [visibleDates, setVisibleDates] = useState(createdAtByKey);
|
||||||
|
const [sortOrder, setSortOrder] = useState<"category" | "created-desc">("category");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
useEffect(() => { setVisibleMapping(mapping); setVisibleDates(createdAtByKey); }, [mapping, createdAtByKey]);
|
||||||
|
function showMapping(next: PlaceholderMapping) {
|
||||||
|
setVisibleDates((current) => {
|
||||||
|
const dates: Record<string, string> = {};
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
for (const key of Object.keys(next)) {
|
||||||
|
const date = current[key] ?? createdAtByKey[key];
|
||||||
|
if (date) dates[key] = date;
|
||||||
|
else if (!(key in visibleMapping)) dates[key] = now;
|
||||||
|
}
|
||||||
|
return dates;
|
||||||
|
});
|
||||||
|
setVisibleMapping(next);
|
||||||
|
}
|
||||||
|
const groups = new Map<string, Map<string, string[]>>();
|
||||||
|
for (const [key, entry] of Object.entries(visibleMapping).sort(([a], [b]) => a.localeCompare(b))) {
|
||||||
|
const type = entry.type || "Sonstige";
|
||||||
|
if (!groups.has(type)) groups.set(type, new Map());
|
||||||
|
const root = mappingRoot(key, visibleMapping);
|
||||||
|
const members = groups.get(type)!.get(root) ?? [];
|
||||||
|
members.push(key);
|
||||||
|
groups.get(type)!.set(root, members);
|
||||||
|
}
|
||||||
|
const rows = [...groups].flatMap(([type, roots]) => [...roots].map(([placeholder, members]) => ({
|
||||||
|
type, placeholder, members,
|
||||||
|
})));
|
||||||
|
async function change(action: () => Promise<PlaceholderMapping>, success: string): Promise<boolean> {
|
||||||
|
if (busy) return false;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
showMapping(await action());
|
||||||
|
await showToast({ style: Toast.Style.Success, title: success });
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Zuordnungen nicht geändert",
|
||||||
|
message: (error as Error).message });
|
||||||
|
return false;
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
async function remove(root: string, members: string[]) {
|
||||||
|
if (!onRemove || !(await confirmAlert({
|
||||||
|
title: `${members.length} Zuordnung${members.length === 1 ? "" : "en"} als False Positive freigeben?`,
|
||||||
|
message: removeDescription ?? "Diese Zuordnungen werden entfernt und als Ausnahmen gespeichert.",
|
||||||
|
primaryAction: { title: "Freigeben", style: Alert.ActionStyle.Destructive },
|
||||||
|
}))) return;
|
||||||
|
await change(() => onRemove(root), "False Positive freigegeben");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exportTable(kind: MappingExportKind) {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
const toast = await showToast({ style: Toast.Style.Animated, title: "Textdatei wird exportiert" });
|
||||||
|
try {
|
||||||
|
const result = await writeMappingExport(title, visibleMapping, kind);
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = kind === "terms" ? "Begriffe exportiert" : "Ersetzungen exportiert";
|
||||||
|
toast.message = `${result.count} Einträge · Downloads/Velum`;
|
||||||
|
await showInFinder(result.path).catch(() => undefined);
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Export fehlgeschlagen";
|
||||||
|
toast.message = (error as Error).message;
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
function exportActions() {
|
||||||
|
return <ActionPanel.Section title="Textdatei exportieren">
|
||||||
|
<Action title="Begriffe als Textdatei exportieren" icon={Icon.Download} onAction={() => exportTable("terms")} />
|
||||||
|
<Action title="Ersetzungen als Textdatei exportieren" icon={Icon.Download} onAction={() => exportTable("replacements")} />
|
||||||
|
</ActionPanel.Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderRow(type: string, placeholder: string, members: string[]) {
|
||||||
|
const roots = groups.get(type)!;
|
||||||
|
const date = visibleDates[placeholder];
|
||||||
|
const orderedMembers = sortOrder === "created-desc"
|
||||||
|
? sortMappingRowsByCreatedAt(members.map((key) => ({ type, placeholder: key })), visibleDates)
|
||||||
|
.map((item) => item.placeholder)
|
||||||
|
: members;
|
||||||
|
return <List.Item key={placeholder} icon={Icon.ArrowRight} title={placeholder}
|
||||||
|
subtitle={visibleMapping[placeholder].original}
|
||||||
|
keywords={[type, ...members.flatMap((key) => [key, visibleMapping[key].original])]}
|
||||||
|
accessories={[
|
||||||
|
...(members.length > 1 ? [{ text: `${members.length} Zuordnungen` }] : []),
|
||||||
|
...(sortOrder === "created-desc" ? [{ text: date
|
||||||
|
? `Angelegt ${new Date(date).toLocaleString("de-AT")}` : "Datum unbekannt · nach Nummer" }] : []),
|
||||||
|
]}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
<Action.Push title="Gruppe und Varianten anzeigen" icon={Icon.Eye}
|
||||||
|
target={<List navigationTitle={`${type} · ${placeholder}`} searchBarPlaceholder="Variante suchen">
|
||||||
|
{orderedMembers.map((key) => <List.Item key={key} title={key}
|
||||||
|
subtitle={visibleMapping[key].original}
|
||||||
|
accessories={[
|
||||||
|
key === placeholder ? { text: "Hauptbegriff" } : { text: `→ ${placeholder}` },
|
||||||
|
...(sortOrder === "created-desc" ? [{ text: visibleDates[key]
|
||||||
|
? new Date(visibleDates[key]).toLocaleString("de-AT") : "Datum unbekannt" }] : []),
|
||||||
|
]}
|
||||||
|
actions={<ActionPanel>
|
||||||
|
{key !== placeholder && onDetach && <Action title="Aus Gruppe lösen" icon={Icon.ArrowLeft}
|
||||||
|
onAction={async () => { if (await change(() => onDetach(key), "Zuordnung aus Gruppe gelöst")) pop(); }} />}
|
||||||
|
<Action.CopyToClipboard title="Platzhalter kopieren" content={key} />
|
||||||
|
<Action.CopyToClipboard title="Klartext kopieren" content={visibleMapping[key].original} />
|
||||||
|
</ActionPanel>} />)}
|
||||||
|
</List>} />
|
||||||
|
{onMerge && roots.size > 1 && <ActionPanel.Submenu title="Mit Hauptbegriff zusammenfassen" icon={Icon.Link}>
|
||||||
|
{[...roots.keys()].filter((target) => target !== placeholder).map((target) =>
|
||||||
|
<Action key={target} title={`${visibleMapping[target].original} · ${target}`}
|
||||||
|
onAction={() => change(() => onMerge(placeholder, target), "Zuordnungen zusammengefasst")} />)}
|
||||||
|
</ActionPanel.Submenu>}
|
||||||
|
{onRemove && <Action title="False Positive freigeben" icon={Icon.XMarkCircle}
|
||||||
|
onAction={() => remove(placeholder, members)} />}
|
||||||
|
<Action.CopyToClipboard title="Platzhalter kopieren" content={placeholder} />
|
||||||
|
<Action.CopyToClipboard title="Klartext kopieren" content={visibleMapping[placeholder].original} />
|
||||||
|
{exportActions()}
|
||||||
|
</ActionPanel>} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<List
|
||||||
|
isLoading={busy}
|
||||||
|
navigationTitle={`Übersetzungstabelle · ${title}`}
|
||||||
|
searchBarPlaceholder="Platzhalter oder Klartext suchen"
|
||||||
|
searchBarAccessory={<List.Dropdown tooltip="Sortierung" value={sortOrder} onChange={(value) => setSortOrder(value as "category" | "created-desc")}>
|
||||||
|
<List.Dropdown.Item value="category" title="Kategorie und Platzhalter (Standard)" />
|
||||||
|
<List.Dropdown.Item value="created-desc" title="Anlagedatum · neueste zuerst" />
|
||||||
|
</List.Dropdown>}
|
||||||
|
>
|
||||||
|
<List.EmptyView
|
||||||
|
title="Keine Zuordnungen"
|
||||||
|
description="Für diesen Stand sind noch keine Übersetzungen gespeichert."
|
||||||
|
/>
|
||||||
|
{onAdd && <List.Section title="Pflege">
|
||||||
|
<List.Item icon={Icon.Plus} title="Begriff oder fehlenden Platzhalter hinzufügen"
|
||||||
|
subtitle="Neuer Eintrag für diese Übersetzungstabelle"
|
||||||
|
actions={<ActionPanel><Action title="Zuordnung hinzufügen" icon={Icon.Plus}
|
||||||
|
onAction={() => push(<AddMappingForm onAdd={onAdd} onSaved={showMapping} />)} />
|
||||||
|
{Object.keys(visibleMapping).length > 0 && exportActions()}</ActionPanel>} />
|
||||||
|
</List.Section>}
|
||||||
|
{Object.keys(visibleMapping).length > 0 && <List.Section title="Export">
|
||||||
|
<List.Item icon={Icon.Download} title="Übersetzungstabelle exportieren"
|
||||||
|
subtitle="Alle Begriffe oder Original → Platzhalter als UTF-8-Textdatei"
|
||||||
|
keywords={["export", "txt", "begriffe", "ersetzungen"]}
|
||||||
|
actions={<ActionPanel>{exportActions()}</ActionPanel>} />
|
||||||
|
</List.Section>}
|
||||||
|
{sortOrder === "category" ? [...groups]
|
||||||
|
.sort(([a], [b]) => a.localeCompare(b))
|
||||||
|
.map(([type, roots]) => (
|
||||||
|
<List.Section key={type} title={`${type} · ${roots.size} Gruppen / ${[...roots.values()].reduce((n, members) => n + members.length, 0)} Zuordnungen`}>
|
||||||
|
{[...roots].map(([placeholder, members]) => renderRow(type, placeholder, members))}
|
||||||
|
</List.Section>
|
||||||
|
)) : <List.Section title="Anlagedatum · neueste zuerst">
|
||||||
|
{sortMappingRowsByCreatedAt(rows, visibleDates)
|
||||||
|
.map(({ type, placeholder, members }) => renderRow(type, placeholder, members))}
|
||||||
|
</List.Section>}
|
||||||
|
</List>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
const [projects, setProjects] = useState<TableSource[]>([]);
|
||||||
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
|
const [busy, setBusy] = useState(true);
|
||||||
|
|
||||||
|
const refreshProjects = useCallback(async () => {
|
||||||
|
const history = new Map<string, ProjectRun[]>();
|
||||||
|
for (const { run } of await listAllRuns()) {
|
||||||
|
const path = canonicalProjectPath(run.projectPath);
|
||||||
|
if (!history.has(path)) history.set(path, []);
|
||||||
|
history.get(path)!.push(run);
|
||||||
|
}
|
||||||
|
setProjects([...history].map(([path, entries]) => {
|
||||||
|
const latest = entries[0];
|
||||||
|
return { id: path, title: latest.projectName,
|
||||||
|
subtitle: `${path} · ${new Date(latest.createdAt).toLocaleString("de-AT")}`,
|
||||||
|
mapping: latest.mapping,
|
||||||
|
createdAtByKey: projectMappingCreatedAt(entries, latest.mapping) };
|
||||||
|
}).sort((a, b) => a.title.localeCompare(b.title)));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const refreshSessions = useCallback(async () => {
|
||||||
|
const [saved, active] = await Promise.all([listSessions(), getActiveSessionId()]);
|
||||||
|
setSessions(saved);
|
||||||
|
setActiveSessionId(active);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void Promise.allSettled([refreshProjects(), refreshSessions()]).then((results) => {
|
||||||
|
setBusy(false);
|
||||||
|
const failed = results.find((result) => result.status === "rejected");
|
||||||
|
if (failed) void showToast({ style: Toast.Style.Failure,
|
||||||
|
title: "Übersetzungstabellen konnten nicht vollständig geladen werden",
|
||||||
|
message: String(failed.reason) });
|
||||||
|
});
|
||||||
|
}, [refreshProjects, refreshSessions]);
|
||||||
|
|
||||||
|
async function changeSessions(action: () => Promise<void>, title: string) {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
await refreshSessions();
|
||||||
|
await showToast({ style: Toast.Style.Success, title });
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Sitzung konnte nicht geändert werden",
|
||||||
|
message: error instanceof Error ? error.message : String(error) });
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmSessionChange(title: string, message: string, action: () => Promise<void>, success: string) {
|
||||||
|
if (busy) return;
|
||||||
|
if (await confirmAlert({ title: `${title}?`, message,
|
||||||
|
primaryAction: { title, style: Alert.ActionStyle.Destructive } })) {
|
||||||
|
await changeSessions(action, success);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const newSessionAction = <Action.Push title="Neue Sitzung" icon={Icon.Plus}
|
||||||
|
target={<SessionNameForm onSaved={refreshSessions} />} />;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<List
|
||||||
|
isLoading={busy}
|
||||||
|
navigationTitle="Übersetzungstabellen"
|
||||||
|
searchBarPlaceholder="Projekt oder Sitzung suchen"
|
||||||
|
>
|
||||||
|
<List.EmptyView
|
||||||
|
title="Keine passende Tabelle"
|
||||||
|
actions={<ActionPanel>{newSessionAction}</ActionPanel>}
|
||||||
|
/>
|
||||||
|
<List.Section title="Projekte">
|
||||||
|
{projects.map((source) => (
|
||||||
|
<List.Item
|
||||||
|
key={source.id}
|
||||||
|
icon={Icon.Folder}
|
||||||
|
title={source.title}
|
||||||
|
subtitle={source.subtitle}
|
||||||
|
accessories={[
|
||||||
|
{ text: `${Object.keys(source.mapping).length} Zuordnungen` },
|
||||||
|
]}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
<Action.Push
|
||||||
|
title="Übersetzungstabelle anzeigen"
|
||||||
|
icon={Icon.List}
|
||||||
|
target={
|
||||||
|
<TranslationTable
|
||||||
|
title={source.title}
|
||||||
|
mapping={source.mapping}
|
||||||
|
createdAtByKey={source.createdAtByKey}
|
||||||
|
onAdd={async (input) => {
|
||||||
|
const run = await addProjectMappingEntry(source.id, input);
|
||||||
|
await refreshProjects();
|
||||||
|
return run.mapping;
|
||||||
|
}}
|
||||||
|
onMerge={async (from, into) => {
|
||||||
|
const run = await updateProjectMapping(source.id,
|
||||||
|
(current) => mergeMappingGroups(current, from, into));
|
||||||
|
await refreshProjects();
|
||||||
|
return run.mapping;
|
||||||
|
}}
|
||||||
|
onDetach={async (key) => {
|
||||||
|
const run = await updateProjectMapping(source.id,
|
||||||
|
(current) => detachMappingGroup(current, key));
|
||||||
|
await refreshProjects();
|
||||||
|
return run.mapping;
|
||||||
|
}}
|
||||||
|
removeDescription="Die gesamte Gruppe wird als Projektausnahme gespeichert. Auch zwischenzeitlich bearbeitete Projektdateien werden anhand ihres aktuellen Stands korrigiert und vorher gesichert."
|
||||||
|
onRemove={async (root) => {
|
||||||
|
const revised = await releaseProjectMapping(source.id, root);
|
||||||
|
await refreshProjects();
|
||||||
|
return revised.run.mapping;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Action.Push title="Projektordner ändern" icon={Icon.Folder}
|
||||||
|
target={<RelocateProjectForm projectName={source.title} oldPath={source.id} onMoved={refreshProjects} />} />
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</List.Section>
|
||||||
|
<List.Section title="Sitzungen">
|
||||||
|
{sessions.map((source) => (
|
||||||
|
<List.Item
|
||||||
|
key={source.id}
|
||||||
|
id={source.id}
|
||||||
|
icon={source.id === activeSessionId ? Icon.CheckCircle : Icon.Person}
|
||||||
|
title={source.name}
|
||||||
|
subtitle={sessionSubtitle(source)}
|
||||||
|
accessories={source.id === activeSessionId ? [{ text: "Aktiv" }] : []}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
<Action.Push
|
||||||
|
title="Übersetzungstabelle anzeigen"
|
||||||
|
icon={Icon.List}
|
||||||
|
target={
|
||||||
|
<TranslationTable
|
||||||
|
title={source.name}
|
||||||
|
mapping={source.mapping}
|
||||||
|
createdAtByKey={source.mappingCreatedAt}
|
||||||
|
onAdd={async (input) => {
|
||||||
|
const session = await getSession(source.id);
|
||||||
|
if (!session) throw new Error("Sitzung nicht gefunden.");
|
||||||
|
const normalized = Object.fromEntries(Object.entries(session.mapping)
|
||||||
|
.map(([key, entry]) => [key.replace(/^<|>$/g, ""), entry]));
|
||||||
|
const { placeholder, entry } = prepareManualMappingEntry(normalized, [], input);
|
||||||
|
const bracketed = Object.keys(session.mapping).some((key) => key.startsWith("<"));
|
||||||
|
const key = bracketed ? `<${placeholder}>` : placeholder;
|
||||||
|
const updated = await updateSessionMapping(session.id,
|
||||||
|
{ ...session.mapping, [key]: entry }, session.entityTypes);
|
||||||
|
await refreshSessions();
|
||||||
|
return updated.mapping;
|
||||||
|
}}
|
||||||
|
onMerge={async (from, into) => {
|
||||||
|
const session = await getSession(source.id);
|
||||||
|
if (!session) throw new Error("Sitzung nicht gefunden.");
|
||||||
|
const updated = await updateSessionMapping(session.id,
|
||||||
|
mergeMappingGroups(session.mapping, from, into), session.entityTypes);
|
||||||
|
await refreshSessions();
|
||||||
|
return updated.mapping;
|
||||||
|
}}
|
||||||
|
onDetach={async (key) => {
|
||||||
|
const session = await getSession(source.id);
|
||||||
|
if (!session) throw new Error("Sitzung nicht gefunden.");
|
||||||
|
const updated = await updateSessionMapping(session.id,
|
||||||
|
detachMappingGroup(session.mapping, key), session.entityTypes);
|
||||||
|
await refreshSessions();
|
||||||
|
return updated.mapping;
|
||||||
|
}}
|
||||||
|
removeDescription="Die gesamte Gruppe wird aus der Sitzung entfernt und künftig dort nicht mehr vorgeschlagen. Bereits kopierte oder eingefügte Texte werden nicht rückwirkend geändert."
|
||||||
|
onRemove={async (root) => {
|
||||||
|
const updated = await releaseSessionMappingGroup(source.id, root);
|
||||||
|
await refreshSessions();
|
||||||
|
return updated.mapping;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<ActionPanel.Section title="Sitzung">
|
||||||
|
{source.id !== activeSessionId && <Action title="Als aktive Sitzung setzen" icon={Icon.CheckCircle}
|
||||||
|
onAction={() => changeSessions(() => setActiveSession(source.id), "Aktive Sitzung geändert")} />}
|
||||||
|
<Action.Push title="Sitzungsdetails anzeigen" icon={Icon.Info}
|
||||||
|
target={<SessionDetail session={source} />} />
|
||||||
|
<Action.Push title="Sitzung umbenennen" icon={Icon.Pencil}
|
||||||
|
target={<SessionNameForm session={source} onSaved={refreshSessions} />} />
|
||||||
|
{newSessionAction}
|
||||||
|
</ActionPanel.Section>
|
||||||
|
<ActionPanel.Section>
|
||||||
|
<Action title="Zuordnungen leeren" icon={Icon.XMarkCircle} style={Action.Style.Destructive}
|
||||||
|
onAction={() => confirmSessionChange("Zuordnungen leeren",
|
||||||
|
`Alle Platzhalter-Zuordnungen aus „${source.name}“ werden gelöscht.`,
|
||||||
|
() => clearSessionMapping(source.id), "Zuordnungen geleert")} />
|
||||||
|
<Action title="Sitzung löschen" icon={Icon.Trash} style={Action.Style.Destructive}
|
||||||
|
onAction={() => confirmSessionChange("Sitzung löschen",
|
||||||
|
`„${source.name}“ und ihre Zuordnungen werden gelöscht.`,
|
||||||
|
() => deleteSession(source.id), "Sitzung gelöscht")} />
|
||||||
|
<Action title="Alle Sitzungen löschen" icon={Icon.Trash} style={Action.Style.Destructive}
|
||||||
|
onAction={() => confirmSessionChange("Alle Sitzungen löschen",
|
||||||
|
"Alle gespeicherten Sitzungen und ihre Zuordnungen werden gelöscht.",
|
||||||
|
deleteAllSessions, "Alle Sitzungen gelöscht")} />
|
||||||
|
</ActionPanel.Section>
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<List.Item id="new-session" icon={Icon.Plus} title="Neue Sitzung"
|
||||||
|
actions={<ActionPanel>{newSessionAction}</ActionPanel>} />
|
||||||
|
</List.Section>
|
||||||
|
</List>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SessionNameForm({ session, onSaved }: { session?: VelumSession; onSaved: () => Promise<void> }) {
|
||||||
|
const { pop } = useNavigation();
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const title = session ? "Sitzung umbenennen" : "Sitzung anlegen";
|
||||||
|
|
||||||
|
async function save({ name }: { name: string }) {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
if (session) await renameSession(session.id, name);
|
||||||
|
else await createSession(name);
|
||||||
|
await onSaved();
|
||||||
|
await showToast({ style: Toast.Style.Success, title: session ? "Sitzung umbenannt" : "Sitzung angelegt" });
|
||||||
|
pop();
|
||||||
|
} catch (error) {
|
||||||
|
await showToast({ style: Toast.Style.Failure, title: "Sitzung konnte nicht gespeichert werden",
|
||||||
|
message: error instanceof Error ? error.message : String(error) });
|
||||||
|
} finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Form navigationTitle={title} isLoading={busy}
|
||||||
|
actions={<ActionPanel><Action.SubmitForm title={title} onSubmit={save} /></ActionPanel>}>
|
||||||
|
<Form.TextField id="name" title="Sitzungsname" defaultValue={session?.name}
|
||||||
|
placeholder={session ? undefined : "Leer lassen für einen automatisch vergebenen Namen"} />
|
||||||
|
</Form>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SessionDetail({ session }: { session: VelumSession }) {
|
||||||
|
const markdown = [
|
||||||
|
sessionSubtitle(session),
|
||||||
|
"",
|
||||||
|
`Erstellt am ${new Date(session.createdAt).toLocaleString()}`,
|
||||||
|
"",
|
||||||
|
"## Zuordnungen",
|
||||||
|
mappingSummary(session.mapping),
|
||||||
|
"",
|
||||||
|
"## Platzhalter",
|
||||||
|
...Object.entries(session.mapping).sort(([a], [b]) => a.localeCompare(b))
|
||||||
|
.map(([placeholder, entry]) => `- \`${placeholder}\` · ${entry.type}`),
|
||||||
|
].join("\n");
|
||||||
|
return <Detail navigationTitle={session.name} markdown={markdown} />;
|
||||||
|
}
|
||||||
@@ -11,22 +11,23 @@ import {
|
|||||||
Toast,
|
Toast,
|
||||||
useNavigation,
|
useNavigation,
|
||||||
} from "@raycast/api";
|
} from "@raycast/api";
|
||||||
import { copyRichText, markdownToHtml, maybeCloseRaycast } from "./ai-views";
|
import { markdownToHtml, maybeCloseRaycast } from "./ai-views";
|
||||||
|
import { copyRichText } from "./rich-clipboard";
|
||||||
import { getSelectedTextSafely } from "./selection";
|
import { getSelectedTextSafely } from "./selection";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
createSession,
|
|
||||||
getActiveSessionId,
|
getActiveSessionId,
|
||||||
getSession,
|
|
||||||
listSessions,
|
listSessions,
|
||||||
setActiveSession,
|
|
||||||
updateSessionMapping,
|
|
||||||
} from "./sessions";
|
} from "./sessions";
|
||||||
import {
|
import {
|
||||||
CREATIVITY_OPTIONS,
|
CREATIVITY_OPTIONS,
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
getLastUsedModel,
|
getLastUsedModel,
|
||||||
MODEL_OPTIONS,
|
MODEL_OPTIONS,
|
||||||
|
resolveRaycastModel,
|
||||||
setLastUsedModel,
|
setLastUsedModel,
|
||||||
} from "./ai";
|
} from "./ai";
|
||||||
import { buildSummaryPrompt, type Creativity } from "./summarize";
|
import { buildSummaryPrompt, type Creativity } from "./summarize";
|
||||||
@@ -34,19 +35,15 @@ import type { EntityType, VelumSession } from "./types";
|
|||||||
import {
|
import {
|
||||||
markdownCodeBlock,
|
markdownCodeBlock,
|
||||||
mappingDetailTable,
|
mappingDetailTable,
|
||||||
NEW_SESSION_ID,
|
|
||||||
sessionSubtitle,
|
sessionSubtitle,
|
||||||
} from "./ui";
|
} from "./ui";
|
||||||
import {
|
import {
|
||||||
getEntityTypes,
|
getEntityTypes,
|
||||||
localDepseudonymize,
|
localDepseudonymize,
|
||||||
normalizePseudonymizeResponse,
|
|
||||||
pseudonymize,
|
|
||||||
} from "./velum";
|
} from "./velum";
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = ContextFormValues & {
|
||||||
text: string;
|
text: string;
|
||||||
sessionId: string;
|
|
||||||
entityTypes: string[];
|
entityTypes: string[];
|
||||||
model: string;
|
model: string;
|
||||||
creativity: Creativity;
|
creativity: Creativity;
|
||||||
@@ -58,6 +55,7 @@ export default function Command() {
|
|||||||
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
const [activeSessionId, setActiveSessionId] = useState<string>();
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
@@ -81,8 +79,9 @@ export default function Command() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const loadedEntityTypes = await getEntityTypes();
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
setEntityTypes(loadedEntityTypes);
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
setSelectedEntityTypes(loadedEntityTypes);
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
} catch {
|
} catch {
|
||||||
setEntityTypes([]);
|
setEntityTypes([]);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -92,11 +91,6 @@ export default function Command() {
|
|||||||
load();
|
load();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const defaultSessionId = useMemo(
|
|
||||||
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
|
|
||||||
[activeSessionId, sessions],
|
|
||||||
);
|
|
||||||
|
|
||||||
async function loadSelectedText() {
|
async function loadSelectedText() {
|
||||||
const selected = await getSelectedTextSafely();
|
const selected = await getSelectedTextSafely();
|
||||||
if (!selected) {
|
if (!selected) {
|
||||||
@@ -139,37 +133,21 @@ export default function Command() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const session =
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
values.sessionId === NEW_SESSION_ID
|
|
||||||
? await createSession()
|
|
||||||
: ((await getSession(values.sessionId)) ?? (await createSession()));
|
|
||||||
await setActiveSession(session.id);
|
|
||||||
|
|
||||||
const rawResult = await pseudonymize(
|
|
||||||
input,
|
|
||||||
session.mapping,
|
|
||||||
values.entityTypes,
|
|
||||||
);
|
|
||||||
const pseudoResult = normalizePseudonymizeResponse(rawResult);
|
|
||||||
const updatedSession = await updateSessionMapping(
|
|
||||||
session.id,
|
|
||||||
pseudoResult.mapping,
|
|
||||||
pseudoResult.selected_entity_types,
|
|
||||||
);
|
|
||||||
|
|
||||||
toast.style = Toast.Style.Success;
|
toast.style = Toast.Style.Success;
|
||||||
toast.title = "Pseudonymisiert";
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
toast.message = `${pseudoResult.entity_count} Zuordnungen`;
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
|
||||||
push(
|
push(
|
||||||
<ConfirmPseudonymized
|
<ConfirmPseudonymized
|
||||||
session={updatedSession}
|
session={updatedSession}
|
||||||
pseudonymizedText={pseudoResult.pseudonymized_text}
|
pseudonymizedText={pseudoResult.pseudonymized_text}
|
||||||
model={values.model}
|
model={values.model}
|
||||||
creativity={values.creativity}
|
creativity={values.creativity}
|
||||||
instructions={values.instructions}
|
instructions={values.instructions}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
}} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.style = Toast.Style.Failure;
|
toast.style = Toast.Style.Failure;
|
||||||
toast.title = "Pseudonymisierung fehlgeschlagen";
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
@@ -207,27 +185,9 @@ export default function Command() {
|
|||||||
onChange={setText}
|
onChange={setText}
|
||||||
placeholder="Email-Konversation einfügen oder laden"
|
placeholder="Email-Konversation einfügen oder laden"
|
||||||
/>
|
/>
|
||||||
<Form.Dropdown
|
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||||
id="sessionId"
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
title="Sitzung"
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
defaultValue={defaultSessionId}
|
|
||||||
>
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
value={NEW_SESSION_ID}
|
|
||||||
title="Neue Sitzung"
|
|
||||||
icon={Icon.Plus}
|
|
||||||
/>
|
|
||||||
{sessions.map((session) => (
|
|
||||||
<Form.Dropdown.Item
|
|
||||||
key={session.id}
|
|
||||||
value={session.id}
|
|
||||||
title={session.name}
|
|
||||||
icon={
|
|
||||||
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</Form.Dropdown>
|
|
||||||
{entityTypes.length > 0 ? (
|
{entityTypes.length > 0 ? (
|
||||||
<Form.TagPicker
|
<Form.TagPicker
|
||||||
id="entityTypes"
|
id="entityTypes"
|
||||||
@@ -329,7 +289,7 @@ function ConfirmPseudonymized({
|
|||||||
>
|
>
|
||||||
<Form.Description
|
<Form.Description
|
||||||
title="Bestätigen"
|
title="Bestätigen"
|
||||||
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Platzhalter wie <PERSON_1> werden nach der Zusammenfassung wiederhergestellt. Sitzung: ${session.name} · ${Object.keys(session.mapping).length} Zuordnungen.`}
|
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Platzhalter wie <PERSON_1> werden nach der Zusammenfassung wiederhergestellt. Kontext: ${session.name} · ${Object.keys(session.mapping).length} Zuordnungen.`}
|
||||||
/>
|
/>
|
||||||
<Form.TextArea
|
<Form.TextArea
|
||||||
id="pseudonymizedText"
|
id="pseudonymizedText"
|
||||||
@@ -395,7 +355,7 @@ function SummarizeEmailResult({
|
|||||||
try {
|
try {
|
||||||
const prompt = buildSummaryPrompt(pseudonymizedText, instructions);
|
const prompt = buildSummaryPrompt(pseudonymizedText, instructions);
|
||||||
const stream = AI.ask(prompt, {
|
const stream = AI.ask(prompt, {
|
||||||
model: model as AI.Model,
|
model: resolveRaycastModel(model),
|
||||||
creativity,
|
creativity,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
|
|||||||
293
src/summarize-meeting-notes.tsx
Normal file
293
src/summarize-meeting-notes.tsx
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
import {
|
||||||
|
Action,
|
||||||
|
ActionPanel,
|
||||||
|
Clipboard,
|
||||||
|
Form,
|
||||||
|
Icon,
|
||||||
|
showToast,
|
||||||
|
Toast,
|
||||||
|
useNavigation,
|
||||||
|
} from "@raycast/api";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import {
|
||||||
|
type Creativity,
|
||||||
|
CREATIVITY_OPTIONS,
|
||||||
|
DEFAULT_MODEL,
|
||||||
|
getLastUsedModel,
|
||||||
|
MODEL_OPTIONS,
|
||||||
|
setLastUsedModel,
|
||||||
|
STRICT_PLACEHOLDER_RULE,
|
||||||
|
} from "./ai";
|
||||||
|
import { PseudonymizationConfirm } from "./ai-views";
|
||||||
|
import { getSelectedTextSafely } from "./selection";
|
||||||
|
import { ContextPicker, type ContextFormValues } from "./context-picker";
|
||||||
|
import { prepareTextInContext } from "./text-context";
|
||||||
|
import { TextHitReview } from "./text-hit-review";
|
||||||
|
import {
|
||||||
|
getActiveSessionId,
|
||||||
|
listSessions,
|
||||||
|
} from "./sessions";
|
||||||
|
import type { EntityType, VelumSession } from "./types";
|
||||||
|
import {
|
||||||
|
getEntityTypes,
|
||||||
|
} from "./velum";
|
||||||
|
|
||||||
|
function buildMeetingNotesPrompt(
|
||||||
|
pseudonymizedText: string,
|
||||||
|
instructions: string,
|
||||||
|
): string {
|
||||||
|
const extra = instructions.trim()
|
||||||
|
? `\n\nZusätzliche Anweisungen des Nutzers:\n${instructions.trim()}`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
return [
|
||||||
|
"Du erhältst pseudonymisierte Meeting-Notizen als FLIESSTEXT / PROSA.",
|
||||||
|
"Personenbezogene Daten wurden bereits durch Platzhalter wie <PERSON_1>, <ORG_2>, <DATE_3>, <EMAIL_4> ersetzt.",
|
||||||
|
"",
|
||||||
|
STRICT_PLACEHOLDER_RULE,
|
||||||
|
"",
|
||||||
|
"Aufgabe: Verwandle den Fließtext in eine SAUBER STRUKTURIERTE, deutschsprachige Meeting-Zusammenfassung in Markdown.",
|
||||||
|
"Ziehe Struktur, Verantwortlichkeiten, Entscheidungen und Aufgaben aus der Prosa heraus — verdichte, ohne Inhalte zu erfinden.",
|
||||||
|
"",
|
||||||
|
"Verwende GENAU diese Abschnitte in dieser Reihenfolge:",
|
||||||
|
"",
|
||||||
|
"## Kontext",
|
||||||
|
"Ein kurzer Absatz (2–4 Sätze): Worum ging es im Meeting, Anlass, Rahmen. Datum/Ort nur, wenn aus dem Text ableitbar (sonst weglassen).",
|
||||||
|
"",
|
||||||
|
"## Teilnehmer",
|
||||||
|
"- Stichpunktliste der beteiligten Platzhalter, jeweils mit Rolle/Funktion (falls aus dem Text ableitbar).",
|
||||||
|
"- Format pro Zeile: `- <PERSON_X> — Rolle/Funktion`",
|
||||||
|
"",
|
||||||
|
"## Themen & Diskussion",
|
||||||
|
"Pro behandeltem Thema ein eigener Unter-Absatz:",
|
||||||
|
"### <Themenbezeichnung in 3–6 Wörtern>",
|
||||||
|
"Ein kurzer Absatz (2–5 Sätze), der Kernaussagen, Positionen und Argumente verdichtet. Wer hat was gesagt — nur wenn relevant. Keine wörtlichen Zitate, außer sie sind im Quelltext markiert.",
|
||||||
|
"",
|
||||||
|
"## Entscheidungen",
|
||||||
|
"- Eine Stichpunktliste mit jeweils einer klar formulierten Entscheidung pro Zeile.",
|
||||||
|
"- Nur tatsächlich getroffene Entscheidungen; keine Vorschläge oder Überlegungen.",
|
||||||
|
"",
|
||||||
|
"## Action Items",
|
||||||
|
"Markdown-Tabelle mit GENAU dieser Kopfzeile:",
|
||||||
|
"| Aufgabe | Verantwortlich | Deadline | Status |",
|
||||||
|
"| --- | --- | --- | --- |",
|
||||||
|
"- Status MUSS gesetzt sein, genau einer von: „offen“, „abgeschlossen“. „abgeschlossen“ nur wenn der Text die Erledigung explizit beschreibt.",
|
||||||
|
"- Verantwortlich als Platzhalter (z. B. <PERSON_1>); wenn nicht ableitbar: „—“.",
|
||||||
|
"- Deadline nur, wenn ein konkretes Datum/Zeitraum genannt ist; sonst leer lassen. Niemals Deadlines erfinden.",
|
||||||
|
"- Wenn keine Action Items vorkommen, schreibe stattdessen die einzelne Zeile: „Keine Action Items.“",
|
||||||
|
"",
|
||||||
|
"## Offene Punkte",
|
||||||
|
"- Stichpunktliste der Themen, die NICHT abschließend geklärt wurden bzw. Klärungsbedarf haben.",
|
||||||
|
"",
|
||||||
|
"## Nächste Schritte",
|
||||||
|
"Ein kurzer Absatz (1–3 Sätze): Wie geht es nach diesem Meeting weiter? Nur wenn aus dem Text ableitbar.",
|
||||||
|
"",
|
||||||
|
"Regeln:",
|
||||||
|
'Wenn ein Abschnitt im Text nicht vorkommt, schreibe „—" als einzigen Inhalt darunter.',
|
||||||
|
"Nichts erfinden, nichts ausschmücken — strikt am Quelltext bleiben.",
|
||||||
|
"Antworte ausschließlich in Markdown, ohne einleitende Floskeln und ohne umschließende Code-Fences (keine ``` Zeilen am Anfang oder Ende).",
|
||||||
|
extra,
|
||||||
|
"",
|
||||||
|
"--- Meeting-Notizen (pseudonymisiert, Prosa) ---",
|
||||||
|
pseudonymizedText,
|
||||||
|
"--- Ende ---",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
type FormValues = ContextFormValues & {
|
||||||
|
text: string;
|
||||||
|
entityTypes: string[];
|
||||||
|
model: string;
|
||||||
|
creativity: Creativity;
|
||||||
|
instructions: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function Command() {
|
||||||
|
const [text, setText] = useState("");
|
||||||
|
const [sessions, setSessions] = useState<VelumSession[]>([]);
|
||||||
|
const [activeSessionId, setActiveSessionId] = useState<string>();
|
||||||
|
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
|
||||||
|
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
|
||||||
|
const [model, setModel] = useState<string>(DEFAULT_MODEL);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const { push } = useNavigation();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
async function load() {
|
||||||
|
const [loadedSessions, activeId, lastModel] = await Promise.all([
|
||||||
|
listSessions(),
|
||||||
|
getActiveSessionId(),
|
||||||
|
getLastUsedModel(),
|
||||||
|
]);
|
||||||
|
setSessions(loadedSessions);
|
||||||
|
setActiveSessionId(activeId);
|
||||||
|
setModel(lastModel);
|
||||||
|
|
||||||
|
const selection = await getSelectedTextSafely();
|
||||||
|
if (selection && selection.trim()) {
|
||||||
|
setText(selection);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const loadedEntityTypes = await getEntityTypes();
|
||||||
|
setEntityTypes(loadedEntityTypes.all);
|
||||||
|
setDefaultEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
setSelectedEntityTypes(loadedEntityTypes.defaults);
|
||||||
|
} catch {
|
||||||
|
setEntityTypes([]);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
load();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function loadSelectedText() {
|
||||||
|
const selected = await getSelectedTextSafely();
|
||||||
|
if (!selected) {
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title: "Kein markierter Text gefunden",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setText(selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadClipboardText() {
|
||||||
|
const clipboardText = await Clipboard.readText();
|
||||||
|
if (!clipboardText) {
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title: "Zwischenablage enthält keinen Text",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setText(clipboardText);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit(values: FormValues) {
|
||||||
|
const input = values.text.trim();
|
||||||
|
if (!input) {
|
||||||
|
await showToast({
|
||||||
|
style: Toast.Style.Failure,
|
||||||
|
title: "Meeting-Notizen eingeben",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setLastUsedModel(values.model);
|
||||||
|
|
||||||
|
const toast = await showToast({
|
||||||
|
style: Toast.Style.Animated,
|
||||||
|
title: "Pseudonymisiere…",
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const prepared = await prepareTextInContext(values, input, values.entityTypes);
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = "Treffer zur Prüfung bereit";
|
||||||
|
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
|
||||||
|
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
|
||||||
|
push(
|
||||||
|
<PseudonymizationConfirm
|
||||||
|
session={updatedSession}
|
||||||
|
pseudonymizedText={pseudoResult.pseudonymized_text}
|
||||||
|
model={values.model}
|
||||||
|
creativity={values.creativity}
|
||||||
|
instructions={values.instructions}
|
||||||
|
buildPrompt={buildMeetingNotesPrompt}
|
||||||
|
labels={{
|
||||||
|
pageHeading: "Meeting-Zusammenfassung",
|
||||||
|
runningLabel: "KI strukturiert Meeting-Notizen …",
|
||||||
|
failureTitle: "Zusammenfassung fehlgeschlagen",
|
||||||
|
copyTitle: "Zusammenfassung kopieren",
|
||||||
|
pasteTitle: "Zusammenfassung einfügen",
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}} />);
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Pseudonymisierung fehlgeschlagen";
|
||||||
|
toast.message = error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form
|
||||||
|
isLoading={isLoading}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
<Action.SubmitForm
|
||||||
|
title="Meeting-Notizen strukturieren"
|
||||||
|
icon={Icon.Document}
|
||||||
|
onSubmit={handleSubmit}
|
||||||
|
/>
|
||||||
|
<Action
|
||||||
|
title="Markierten Text übernehmen"
|
||||||
|
icon={Icon.TextSelection}
|
||||||
|
onAction={loadSelectedText}
|
||||||
|
/>
|
||||||
|
<Action
|
||||||
|
title="Zwischenablage übernehmen"
|
||||||
|
icon={Icon.Clipboard}
|
||||||
|
onAction={loadClipboardText}
|
||||||
|
/>
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Form.TextArea
|
||||||
|
id="text"
|
||||||
|
title="Meeting-Notizen (Prosa)"
|
||||||
|
value={text}
|
||||||
|
onChange={setText}
|
||||||
|
placeholder="Meeting-Notizen als Fließtext einfügen — z. B. handgeschriebene Protokollnotizen, ein diktiertes Transkript oder ein zusammenhängender Bericht."
|
||||||
|
/>
|
||||||
|
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
|
||||||
|
availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
|
||||||
|
onEntityTypesChange={setSelectedEntityTypes} />
|
||||||
|
{entityTypes.length > 0 ? (
|
||||||
|
<Form.TagPicker
|
||||||
|
id="entityTypes"
|
||||||
|
title="Entitätstypen"
|
||||||
|
value={selectedEntityTypes}
|
||||||
|
onChange={setSelectedEntityTypes}
|
||||||
|
>
|
||||||
|
{entityTypes.map((entityType) => (
|
||||||
|
<Form.TagPicker.Item
|
||||||
|
key={entityType}
|
||||||
|
value={entityType}
|
||||||
|
title={entityType}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Form.TagPicker>
|
||||||
|
) : null}
|
||||||
|
<Form.Dropdown
|
||||||
|
id="model"
|
||||||
|
title="KI-Modell"
|
||||||
|
value={model}
|
||||||
|
onChange={setModel}
|
||||||
|
>
|
||||||
|
{MODEL_OPTIONS.map((option) => (
|
||||||
|
<Form.Dropdown.Item
|
||||||
|
key={option.value}
|
||||||
|
value={option.value}
|
||||||
|
title={option.title}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Form.Dropdown>
|
||||||
|
<Form.Dropdown id="creativity" title="Kreativität" defaultValue="low">
|
||||||
|
{CREATIVITY_OPTIONS.map((value) => (
|
||||||
|
<Form.Dropdown.Item key={value} value={value} title={value} />
|
||||||
|
))}
|
||||||
|
</Form.Dropdown>
|
||||||
|
<Form.TextArea
|
||||||
|
id="instructions"
|
||||||
|
title="Zusätzliche Anweisungen"
|
||||||
|
placeholder="Optional: Fokus auf bestimmte Themen, Tonalität, Zielpublikum (z. B. „für Lenkungsausschuss verdichten“), …"
|
||||||
|
/>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { AI } from "@raycast/api";
|
import { AI } from "@raycast/api";
|
||||||
|
import { resolveRaycastModel } from "./ai";
|
||||||
|
|
||||||
export type Creativity = "none" | "low" | "medium" | "high";
|
export type Creativity = "none" | "low" | "medium" | "high";
|
||||||
|
|
||||||
@@ -54,7 +55,7 @@ export async function runSummaryStream(
|
|||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
let buffer = "";
|
let buffer = "";
|
||||||
const stream = AI.ask(options.prompt, {
|
const stream = AI.ask(options.prompt, {
|
||||||
model: options.model as AI.Model,
|
model: resolveRaycastModel(options.model),
|
||||||
creativity: options.creativity,
|
creativity: options.creativity,
|
||||||
signal: options.signal,
|
signal: options.signal,
|
||||||
});
|
});
|
||||||
|
|||||||
298
src/text-context.ts
Normal file
298
src/text-context.ts
Normal file
@@ -0,0 +1,298 @@
|
|||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
|
||||||
|
loadProjectWhitelist, replaceSpans, saveProjectRules, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping,
|
||||||
|
validCustomTerm, whitelistKey } from "./lib/velum-project";
|
||||||
|
import { mappingForRestoration, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
|
||||||
|
import type { ProjectWhitelistEntry } from "./lib/velum-project";
|
||||||
|
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values";
|
||||||
|
import { createSession, getSession, setActiveSession, updateSessionMapping } from "./sessions";
|
||||||
|
import type { CustomTerm, EntityType, PlaceholderMapping, PseudonymizeResponse, VelumSession } from "./types";
|
||||||
|
import { NEW_SESSION_ID } from "./ui";
|
||||||
|
import { normalizePseudonymizeResponse, pseudonymize } from "./velum";
|
||||||
|
|
||||||
|
export function bareMapping(mapping: PlaceholderMapping): PlaceholderMapping {
|
||||||
|
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [
|
||||||
|
key.replace(/^<|>$/g, ""),
|
||||||
|
{ ...entry, merged_into: entry.merged_into?.replace(/^<|>$/g, "") },
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function resultSession(path: string, name: string, mapping: PlaceholderMapping,
|
||||||
|
entityTypes: EntityType[]): VelumSession {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
return { id: `project:${path}`, name: `Projekt ${name}`, mapping,
|
||||||
|
entityTypes, createdAt: now, updatedAt: now };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function applyProjectWhitelist(text: string, response: PseudonymizeResponse,
|
||||||
|
previous: PlaceholderMapping, whitelist: ProjectWhitelistEntry[]): PseudonymizeResponse {
|
||||||
|
const excluded = new Set(whitelist.map(whitelistKey));
|
||||||
|
if (!excluded.size) return response;
|
||||||
|
return filterTextHits(text, response, previous, (span) => !excluded.has(whitelistKey(span)));
|
||||||
|
}
|
||||||
|
|
||||||
|
type TextSpan = PseudonymizeResponse["spans"][number];
|
||||||
|
|
||||||
|
function filterTextHits(text: string, response: PseudonymizeResponse, previous: PlaceholderMapping,
|
||||||
|
keep: (span: TextSpan) => boolean): PseudonymizeResponse {
|
||||||
|
const accepted = response.spans.filter(keep);
|
||||||
|
if (accepted.length === response.spans.length) return response;
|
||||||
|
const spans = toUtf16Offsets(text, accepted).map((span, index) => ({ ...span, id: String(index) }));
|
||||||
|
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
|
||||||
|
const known = new Set(Object.keys(previous).map((key) => key.replace(/^<|>$/g, "")));
|
||||||
|
return {
|
||||||
|
...response,
|
||||||
|
pseudonymized_text: replaceSpans(text, spans, new Set(spans.map((span) => span.id))),
|
||||||
|
spans: accepted,
|
||||||
|
entity_count: active.size,
|
||||||
|
mapping: Object.fromEntries(Object.entries(response.mapping).filter(([key]) =>
|
||||||
|
active.has(key.replace(/^<|>$/g, "")) || known.has(key.replace(/^<|>$/g, "")))),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PreparedText = {
|
||||||
|
text: string;
|
||||||
|
raw: PseudonymizeResponse;
|
||||||
|
previous: PlaceholderMapping;
|
||||||
|
exclusions: ProjectWhitelistEntry[];
|
||||||
|
customTerms: CustomTerm[];
|
||||||
|
addedTerms?: CustomTerm[];
|
||||||
|
selected: string;
|
||||||
|
newSessionName?: string;
|
||||||
|
projectPath?: string;
|
||||||
|
projectName?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function termKey(type: EntityType, value: string): string {
|
||||||
|
return whitelistKey({ type, original: value.replace(/\s+/gu, " ") });
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeCustomTerms(previous: CustomTerm[], additions: CustomTerm[]): CustomTerm[] {
|
||||||
|
const replaced = new Set(additions.map(({ value }) => termKey("", value)));
|
||||||
|
const combined = [...previous.filter(({ value }) => !replaced.has(termKey("", value))), ...additions];
|
||||||
|
if (combined.length > 500) throw new Error("Maximal 500 eigene Begriffe sind erlaubt.");
|
||||||
|
return combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function analyzeText(text: string, mapping: PlaceholderMapping, entityTypes: EntityType[],
|
||||||
|
customTerms: CustomTerm[], exclusions: ProjectWhitelistEntry[], request: typeof pseudonymize) {
|
||||||
|
const excluded = new Set(exclusions.map(({ type, original }) => termKey(type, original)));
|
||||||
|
const rules = customTerms.filter(({ type, value }) => !excluded.has(termKey(type, value)));
|
||||||
|
const effectiveTypes = [...new Set([...entityTypes, ...rules.map(({ type }) => type)])];
|
||||||
|
const response = await request(text, mapping, effectiveTypes, rules.length ? forceMasks(rules) : undefined);
|
||||||
|
if (!response.spans.length && response.pseudonymized_text !== text) {
|
||||||
|
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
|
||||||
|
}
|
||||||
|
const forced = new Set(rules.map(({ type, value }) => termKey(type, value)));
|
||||||
|
const automatic = new Set(entityTypes);
|
||||||
|
const filtered = filterTextHits(text, response, mapping, ({ type, original }) => {
|
||||||
|
const key = termKey(type, original);
|
||||||
|
return !excluded.has(key) && (automatic.has(type) || forced.has(key));
|
||||||
|
});
|
||||||
|
return { ...filtered, selected_entity_types: entityTypes };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addTextReviewTerm(prepared: PreparedText, term: CustomTerm,
|
||||||
|
selected: Set<number>, request: typeof pseudonymize = pseudonymize):
|
||||||
|
Promise<{ prepared: PreparedText; selected: Set<number> }> {
|
||||||
|
if (!validCustomTerm(term.value)) throw new Error("Bitte einen Begriff mit 2 bis 200 Zeichen eingeben.");
|
||||||
|
const addedTerms = mergeCustomTerms(prepared.addedTerms ?? [], [term]);
|
||||||
|
const explicit = new Set(addedTerms.map(({ type, value }) => termKey(type, value)));
|
||||||
|
const exclusions = prepared.exclusions.filter(({ type, original }) => !explicit.has(termKey(type, original)));
|
||||||
|
const raw = await analyzeText(prepared.text, { ...bareMapping(prepared.previous), ...bareMapping(prepared.raw.mapping) },
|
||||||
|
prepared.raw.selected_entity_types, mergeCustomTerms(prepared.customTerms, addedTerms), exclusions, request);
|
||||||
|
const key = termKey(term.type, term.value);
|
||||||
|
if (!raw.spans.some(({ type, original }) => termKey(type, original) === key)) {
|
||||||
|
throw new Error("Kein Treffer für diesen Begriff in der gewählten Kategorie. Prüfe die Schreibweise und mögliche Überschneidungen.");
|
||||||
|
}
|
||||||
|
const occurrenceKey = (span: TextSpan) => JSON.stringify([span.start, span.end, span.type]);
|
||||||
|
const rejected = new Set(prepared.raw.spans.filter((_, index) => !selected.has(index)).map(occurrenceKey));
|
||||||
|
const next = new Set<number>();
|
||||||
|
for (const [index, span] of raw.spans.entries()) {
|
||||||
|
if (termKey(span.type, span.original) === key || !rejected.has(occurrenceKey(span))) next.add(index);
|
||||||
|
}
|
||||||
|
return { prepared: { ...prepared, raw, addedTerms }, selected: next };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The local API may propose hits, but this step never stores mappings or starts a cloud request. */
|
||||||
|
export async function prepareTextInContext(values: ContextFormValues, text: string,
|
||||||
|
entityTypes: EntityType[], request: typeof pseudonymize = pseudonymize): Promise<PreparedText> {
|
||||||
|
const selected = values.sessionId;
|
||||||
|
if (!selected || selected === CHOOSE_CONTEXT_ID) throw new Error("Bitte ein Projekt oder eine Sitzung wählen.");
|
||||||
|
if (selected === NEW_PROJECT_ID || selected.startsWith("project:")) {
|
||||||
|
const folder = selected === NEW_PROJECT_ID ? values.newProjectPath?.[0] : selected.slice("project:".length);
|
||||||
|
// Existing projects use their saved mapping even when the source folder is unavailable.
|
||||||
|
if (!folder || (selected === NEW_PROJECT_ID && !(await fs.stat(folder).catch(() => undefined))?.isDirectory())) {
|
||||||
|
throw new Error("Bitte einen vorhandenen Projektordner wählen.");
|
||||||
|
}
|
||||||
|
const path = canonicalProjectPath(folder);
|
||||||
|
const latest = (await listRuns(path))[0];
|
||||||
|
if (selected === NEW_PROJECT_ID && latest) {
|
||||||
|
throw new Error("Für diesen Ordner besteht bereits ein Projekt. Bitte es in der Liste wählen.");
|
||||||
|
}
|
||||||
|
if (selected !== NEW_PROJECT_ID && !latest) throw new Error("Projektstand nicht gefunden. Bitte die Liste aktualisieren.");
|
||||||
|
const [customTerms, exclusions] = await Promise.all([loadProjectRules(path), loadProjectWhitelist(path)]);
|
||||||
|
const previous = latest?.run.mapping ?? {};
|
||||||
|
const raw = await analyzeText(text, previous, entityTypes, customTerms, exclusions, request);
|
||||||
|
return { text, raw, previous, exclusions, customTerms, selected, projectPath: path,
|
||||||
|
projectName: latest?.run.projectName ?? path.split("/").filter(Boolean).at(-1) ?? path };
|
||||||
|
}
|
||||||
|
const session = selected === NEW_SESSION_ID ? undefined : await getSession(selected);
|
||||||
|
if (selected !== NEW_SESSION_ID && !session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
|
||||||
|
const previous = session?.mapping ?? {};
|
||||||
|
const exclusions = session?.excludedTerms ?? [];
|
||||||
|
const customTerms = session?.customTerms ?? [];
|
||||||
|
const raw = await analyzeText(text, bareMapping(previous), entityTypes, customTerms, exclusions, request);
|
||||||
|
return { text, raw, previous, exclusions, customTerms, selected, newSessionName: values.newSessionName };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Commit only the explicitly selected hits; rejected terms become context-specific exceptions. */
|
||||||
|
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false,
|
||||||
|
personMerges: Record<string, string> = {}):
|
||||||
|
Promise<{ result: PseudonymizeResponse; session: VelumSession }> {
|
||||||
|
const accepted = prepared.raw.spans.filter((_, index) => selectedHits.has(index));
|
||||||
|
const rejected = prepared.raw.spans.filter((_, index) => !selectedHits.has(index));
|
||||||
|
const known = bareMapping(prepared.previous);
|
||||||
|
const preview = { ...known, ...bareMapping(prepared.raw.mapping) };
|
||||||
|
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
|
||||||
|
let mapping: PlaceholderMapping = { ...known };
|
||||||
|
for (const key of active) {
|
||||||
|
const entry = preview[key];
|
||||||
|
if (!entry) throw new Error(`Zuordnung für ${key} fehlt. Es wurde nichts gespeichert.`);
|
||||||
|
mapping[key] = entry;
|
||||||
|
if (entry.merged_into) {
|
||||||
|
const root = mappingRoot(key, preview);
|
||||||
|
mapping[key] = { ...entry, merged_into: root };
|
||||||
|
mapping[root] = preview[root];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const selectedPeople = new Set(accepted.filter((span) => span.type === "PERSON")
|
||||||
|
.map((span) => mappingRoot(span.placeholder.replace(/^<|>$/g, ""), mapping)));
|
||||||
|
for (const [source, target] of Object.entries(personMerges)) {
|
||||||
|
if (!selectedPeople.has(source) || mapping[target]?.type !== "PERSON") {
|
||||||
|
throw new Error("Bitte nur ausgewählte Personen mit vorhandenen Zuordnungen zusammenfassen.");
|
||||||
|
}
|
||||||
|
mapping = mergeMappingGroups(mapping, source, target);
|
||||||
|
}
|
||||||
|
const mergedSpans = accepted.map((span) => {
|
||||||
|
if (span.type !== "PERSON") return span;
|
||||||
|
const key = span.placeholder.replace(/^<|>$/g, "");
|
||||||
|
const root = mappingRoot(key, mapping);
|
||||||
|
if (root === key) return span;
|
||||||
|
return { ...span, placeholder: span.placeholder.startsWith("<") ? `<${root}>` : root };
|
||||||
|
});
|
||||||
|
const spans = toUtf16Offsets(prepared.text, mergedSpans).map((span, index) => ({ ...span, id: String(index) }));
|
||||||
|
const raw: PseudonymizeResponse = { ...prepared.raw, spans: mergedSpans,
|
||||||
|
mapping, entity_count: new Set(mergedSpans.map((span) => span.placeholder.replace(/^<|>$/g, ""))).size,
|
||||||
|
pseudonymized_text: replaceSpans(prepared.text, spans, new Set(spans.map((span) => span.id))) };
|
||||||
|
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
|
||||||
|
const acceptedKeys = new Set(accepted.map(({ type, original }) => termKey(type, original)));
|
||||||
|
const additions = rejected.filter(({ type, original }) => !acceptedKeys.has(termKey(type, original)))
|
||||||
|
.map(({ type, original }) => ({ type, original }));
|
||||||
|
const confirmedTerms = (prepared.addedTerms ?? []).filter(({ type, value }) => acceptedKeys.has(termKey(type, value)));
|
||||||
|
const confirmedKeys = new Set(confirmedTerms.map(({ type, value }) => termKey(type, value)));
|
||||||
|
const existingExclusions = prepared.exclusions.filter(({ type, original }) => !confirmedKeys.has(termKey(type, original)));
|
||||||
|
const exclusions = [...new Map([...existingExclusions, ...additions]
|
||||||
|
.map((item) => [whitelistKey(item), item])).values()];
|
||||||
|
if (prepared.projectPath) {
|
||||||
|
const path = prepared.projectPath;
|
||||||
|
const latest = (await listRuns(path))[0];
|
||||||
|
if (prepared.selected === NEW_PROJECT_ID ? Boolean(latest)
|
||||||
|
: !latest || JSON.stringify(latest.run.mapping) !== JSON.stringify(prepared.previous)) {
|
||||||
|
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
|
||||||
|
}
|
||||||
|
const updatedTerms = confirmedTerms.length ? mergeCustomTerms(await loadProjectRules(path), confirmedTerms) : undefined;
|
||||||
|
if (latest) {
|
||||||
|
await updateProjectMapping(path, (current) => {
|
||||||
|
if (JSON.stringify(current) !== JSON.stringify(prepared.previous)) {
|
||||||
|
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
|
||||||
|
}
|
||||||
|
return mapping;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const created = await createRun(path);
|
||||||
|
created.run.mapping = mapping;
|
||||||
|
await saveRun(created.directory, created.run);
|
||||||
|
}
|
||||||
|
if (updatedTerms) await saveProjectRules(path, updatedTerms);
|
||||||
|
if (additions.length || existingExclusions.length !== prepared.exclusions.length) {
|
||||||
|
await saveProjectWhitelist(path, exclusions);
|
||||||
|
}
|
||||||
|
return { result, session: resultSession(path, prepared.projectName ?? path,
|
||||||
|
mappingForRestoration(result.mapping), result.selected_entity_types) };
|
||||||
|
}
|
||||||
|
if (prepared.selected === NEW_SESSION_ID) {
|
||||||
|
const saved = await createSession(prepared.newSessionName, {
|
||||||
|
mapping: result.mapping, entityTypes: result.selected_entity_types, excludedTerms: exclusions, customTerms: confirmedTerms,
|
||||||
|
});
|
||||||
|
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
|
||||||
|
}
|
||||||
|
const session = await getSession(prepared.selected);
|
||||||
|
if (!session) throw new Error("Sitzung nicht gefunden. Bitte erneut analysieren.");
|
||||||
|
if (JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)
|
||||||
|
|| JSON.stringify(session.excludedTerms ?? []) !== JSON.stringify(prepared.exclusions)
|
||||||
|
|| JSON.stringify(session.customTerms ?? []) !== JSON.stringify(prepared.customTerms)) {
|
||||||
|
throw new Error("Die Sitzung wurde inzwischen geändert. Bitte erneut analysieren.");
|
||||||
|
}
|
||||||
|
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types, exclusions,
|
||||||
|
confirmedTerms.length ? mergeCustomTerms(prepared.customTerms, confirmedTerms) : undefined);
|
||||||
|
await setActiveSession(saved.id);
|
||||||
|
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A text command must use the context explicitly selected in its form. */
|
||||||
|
export async function pseudonymizeInContext(values: ContextFormValues, text: string,
|
||||||
|
entityTypes: EntityType[], forAi = false,
|
||||||
|
request: typeof pseudonymize = pseudonymize): Promise<{ result: PseudonymizeResponse; session: VelumSession }> {
|
||||||
|
const selected = values.sessionId;
|
||||||
|
if (!selected || selected === CHOOSE_CONTEXT_ID) {
|
||||||
|
throw new Error("Bitte ein Projekt oder eine Sitzung wählen.");
|
||||||
|
}
|
||||||
|
if (selected === NEW_PROJECT_ID || selected.startsWith("project:")) {
|
||||||
|
const folder = selected === NEW_PROJECT_ID ? values.newProjectPath?.[0] : selected.slice("project:".length);
|
||||||
|
// Existing projects use their saved mapping even when the source folder is unavailable.
|
||||||
|
if (!folder || (selected === NEW_PROJECT_ID && !(await fs.stat(folder).catch(() => undefined))?.isDirectory())) {
|
||||||
|
throw new Error("Bitte einen vorhandenen Projektordner wählen.");
|
||||||
|
}
|
||||||
|
const path = canonicalProjectPath(folder);
|
||||||
|
const latest = (await listRuns(path))[0];
|
||||||
|
if (selected === NEW_PROJECT_ID && latest) {
|
||||||
|
throw new Error("Für diesen Ordner besteht bereits ein Projekt. Bitte es in der Liste wählen.");
|
||||||
|
}
|
||||||
|
if (selected !== NEW_PROJECT_ID && !latest) {
|
||||||
|
throw new Error("Projektstand nicht gefunden. Bitte die Liste aktualisieren.");
|
||||||
|
}
|
||||||
|
const [rules, whitelist] = await Promise.all([loadProjectRules(path), loadProjectWhitelist(path)]);
|
||||||
|
const excluded = new Set(whitelist.map(whitelistKey));
|
||||||
|
const masks = forceMasks(rules.filter((rule) => !excluded.has(whitelistKey({
|
||||||
|
type: rule.type, original: rule.value,
|
||||||
|
}))));
|
||||||
|
const raw = applyProjectWhitelist(text,
|
||||||
|
await request(text, latest?.run.mapping ?? {}, entityTypes, masks), latest?.run.mapping ?? {}, whitelist);
|
||||||
|
const mapping = bareMapping(raw.mapping);
|
||||||
|
if (latest) {
|
||||||
|
await updateProjectMapping(path, (current) => {
|
||||||
|
if (JSON.stringify(current) !== JSON.stringify(latest.run.mapping)) {
|
||||||
|
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte den Befehl erneut öffnen.");
|
||||||
|
}
|
||||||
|
return mapping;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const created = await createRun(path);
|
||||||
|
created.run.mapping = mapping;
|
||||||
|
await saveRun(created.directory, created.run);
|
||||||
|
}
|
||||||
|
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
|
||||||
|
const resultMapping = forAi ? result.mapping : mapping;
|
||||||
|
return { result, session: resultSession(path, latest?.run.projectName ?? path.split("/").filter(Boolean).at(-1) ?? path,
|
||||||
|
mappingForRestoration(resultMapping), result.selected_entity_types) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = selected === NEW_SESSION_ID ? await createSession(values.newSessionName) : await getSession(selected);
|
||||||
|
if (!session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
|
||||||
|
await setActiveSession(session.id);
|
||||||
|
const raw = await request(text, bareMapping(session.mapping), entityTypes);
|
||||||
|
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
|
||||||
|
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types);
|
||||||
|
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
|
||||||
|
}
|
||||||
272
src/text-hit-review.tsx
Normal file
272
src/text-hit-review.tsx
Normal file
@@ -0,0 +1,272 @@
|
|||||||
|
import {
|
||||||
|
Action,
|
||||||
|
ActionPanel,
|
||||||
|
Icon,
|
||||||
|
List,
|
||||||
|
showToast,
|
||||||
|
Toast,
|
||||||
|
useNavigation,
|
||||||
|
} from "@raycast/api";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { CustomTermForm } from "./custom-term-form";
|
||||||
|
import { mappingRoot } from "./lib/mapping-groups";
|
||||||
|
import {
|
||||||
|
canonicalPerson,
|
||||||
|
groupReviewHits,
|
||||||
|
mergePeople,
|
||||||
|
textHitContexts,
|
||||||
|
} from "./lib/project-review";
|
||||||
|
import { PersonMergeTargets } from "./person-merge-targets";
|
||||||
|
import {
|
||||||
|
addTextReviewTerm,
|
||||||
|
bareMapping,
|
||||||
|
commitPreparedText,
|
||||||
|
type PreparedText,
|
||||||
|
} from "./text-context";
|
||||||
|
import type {
|
||||||
|
CustomTerm,
|
||||||
|
EntityType,
|
||||||
|
PseudonymizeResponse,
|
||||||
|
VelumSession,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
export function TextHitReview(props: {
|
||||||
|
prepared: PreparedText;
|
||||||
|
entityTypes: EntityType[];
|
||||||
|
forAi?: boolean;
|
||||||
|
onConfirmed: (
|
||||||
|
result: PseudonymizeResponse,
|
||||||
|
session: VelumSession,
|
||||||
|
) => Promise<void> | void;
|
||||||
|
}) {
|
||||||
|
const { push } = useNavigation();
|
||||||
|
const [prepared, setPrepared] = useState(props.prepared);
|
||||||
|
const [selected, setSelected] = useState<Set<number>>(
|
||||||
|
() => new Set(props.prepared.raw.spans.map((_, index) => index)),
|
||||||
|
);
|
||||||
|
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const { byType, people, personByHit } = useMemo(() => {
|
||||||
|
const { text, raw, previous } = prepared;
|
||||||
|
const contexts = textHitContexts(text, raw.spans);
|
||||||
|
const hits = raw.spans.map((span, index) => ({
|
||||||
|
...span,
|
||||||
|
id: String(index),
|
||||||
|
context: contexts[index],
|
||||||
|
}));
|
||||||
|
const groups = groupReviewHits(hits);
|
||||||
|
const byType = new Map<string, typeof groups>();
|
||||||
|
for (const group of groups) {
|
||||||
|
if (!byType.has(group.type)) byType.set(group.type, []);
|
||||||
|
byType.get(group.type)!.push(group);
|
||||||
|
}
|
||||||
|
|
||||||
|
const known = bareMapping(previous);
|
||||||
|
const mapping = { ...known, ...bareMapping(raw.mapping) };
|
||||||
|
const names = new Map<string, Set<string>>();
|
||||||
|
for (const [key, entry] of Object.entries(mapping)) {
|
||||||
|
if (entry.type !== "PERSON") continue;
|
||||||
|
const root = mappingRoot(key, mapping);
|
||||||
|
if (!names.has(root)) names.set(root, new Set([mapping[root].original]));
|
||||||
|
names.get(root)!.add(entry.original);
|
||||||
|
}
|
||||||
|
const personByHit = new Map<number, string>();
|
||||||
|
for (const [index, hit] of hits.entries()) {
|
||||||
|
if (hit.type !== "PERSON") continue;
|
||||||
|
const key = hit.placeholder.replace(/^<|>$/g, "");
|
||||||
|
if (!mapping[key]) continue;
|
||||||
|
const root = mappingRoot(key, mapping);
|
||||||
|
personByHit.set(index, root);
|
||||||
|
names.get(root)?.add(hit.original);
|
||||||
|
}
|
||||||
|
const people = [...names]
|
||||||
|
.map(([placeholder, originals]) => ({
|
||||||
|
placeholder,
|
||||||
|
originals: [...originals],
|
||||||
|
saved: Boolean(known[placeholder]),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.originals[0].localeCompare(b.originals[0]));
|
||||||
|
return { byType, people, personByHit };
|
||||||
|
}, [prepared]);
|
||||||
|
|
||||||
|
const selectedPeople = new Set(
|
||||||
|
[...personByHit]
|
||||||
|
.filter(([index]) => selected.has(index))
|
||||||
|
.map(([, person]) => person),
|
||||||
|
);
|
||||||
|
const availablePeople = people.filter(
|
||||||
|
(person) => person.saved || selectedPeople.has(person.placeholder),
|
||||||
|
);
|
||||||
|
const availablePlaceholders = new Set(
|
||||||
|
availablePeople.map((person) => person.placeholder),
|
||||||
|
);
|
||||||
|
const activeMerges = Object.fromEntries(
|
||||||
|
Object.entries(personMerges).filter(
|
||||||
|
([source, target]) =>
|
||||||
|
selectedPeople.has(source) && availablePlaceholders.has(target),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const mergeTargets = availablePeople.filter(
|
||||||
|
({ placeholder }) => !activeMerges[placeholder],
|
||||||
|
);
|
||||||
|
|
||||||
|
async function confirm() {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
const toast = await showToast({
|
||||||
|
style: Toast.Style.Animated,
|
||||||
|
title: "Auswahl wird übernommen",
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const { result, session } = await commitPreparedText(
|
||||||
|
prepared,
|
||||||
|
selected,
|
||||||
|
props.forAi,
|
||||||
|
activeMerges,
|
||||||
|
);
|
||||||
|
toast.style = Toast.Style.Success;
|
||||||
|
toast.title = "Auswahl übernommen";
|
||||||
|
toast.message = `${selected.size} Treffer bestätigt`;
|
||||||
|
await props.onConfirmed(result, session);
|
||||||
|
} catch (error) {
|
||||||
|
toast.style = Toast.Style.Failure;
|
||||||
|
toast.title = "Auswahl nicht übernommen";
|
||||||
|
toast.message = error instanceof Error ? error.message : String(error);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function toggle(ids: number[]) {
|
||||||
|
setSelected((current) => {
|
||||||
|
const next = new Set(current);
|
||||||
|
const all = ids.every((id) => next.has(id));
|
||||||
|
for (const id of ids) {
|
||||||
|
if (all) next.delete(id);
|
||||||
|
else next.add(id);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function addTerm(term: CustomTerm) {
|
||||||
|
const updated = await addTextReviewTerm(prepared, term, selected);
|
||||||
|
setPrepared(updated.prepared);
|
||||||
|
setSelected(updated.selected);
|
||||||
|
}
|
||||||
|
const addTermAction = (
|
||||||
|
<Action.Push
|
||||||
|
title="Eigenen Begriff hinzufügen"
|
||||||
|
icon={Icon.Plus}
|
||||||
|
target={
|
||||||
|
<CustomTermForm entityTypes={props.entityTypes} onAdd={addTerm} />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<List
|
||||||
|
isLoading={busy}
|
||||||
|
isShowingDetail
|
||||||
|
navigationTitle="Treffer vor Pseudonymisierung prüfen"
|
||||||
|
searchBarPlaceholder="Begriff, Kategorie oder Platzhalter suchen"
|
||||||
|
>
|
||||||
|
<List.Section title="Abschluss">
|
||||||
|
<List.Item
|
||||||
|
id="confirm"
|
||||||
|
icon={Icon.CheckCircle}
|
||||||
|
title="Auswahl bestätigen"
|
||||||
|
subtitle={`${selected.size} von ${prepared.raw.spans.length} Treffern werden maskiert · Abgewählte werden als Ausnahme gespeichert`}
|
||||||
|
detail={
|
||||||
|
<List.Item.Detail markdown="Wähle einen Begriff aus, um seine Vorkommen zu sehen. Fehlende Treffer kannst du über **Eigenen Begriff hinzufügen** ergänzen. Mit **Auswahl bestätigen** speicherst du deine Änderungen." />
|
||||||
|
}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
<Action
|
||||||
|
title="Auswahl bestätigen und fortfahren"
|
||||||
|
icon={Icon.CheckCircle}
|
||||||
|
onAction={confirm}
|
||||||
|
/>
|
||||||
|
{addTermAction}
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</List.Section>
|
||||||
|
{[...byType].map(([type, typeGroups]) => (
|
||||||
|
<List.Section
|
||||||
|
key={type}
|
||||||
|
title={`${type} · ${typeGroups.length} Begriffe`}
|
||||||
|
>
|
||||||
|
{typeGroups.map((group) => {
|
||||||
|
const ids = group.hits.map((hit) => Number(hit.id));
|
||||||
|
const all = ids.every((id) => selected.has(id));
|
||||||
|
const person = personByHit.get(ids[0]);
|
||||||
|
const canonical = person
|
||||||
|
? canonicalPerson(person, activeMerges)
|
||||||
|
: undefined;
|
||||||
|
return (
|
||||||
|
<List.Item
|
||||||
|
key={group.key}
|
||||||
|
id={`hit-${group.hits[0].start}-${group.hits[0].end}-${group.type}`}
|
||||||
|
icon={all ? Icon.CheckCircle : Icon.Circle}
|
||||||
|
title={`${group.original} → ${canonical ?? group.placeholder}`}
|
||||||
|
subtitle={
|
||||||
|
group.hits.length > 1
|
||||||
|
? `${group.hits.length} Vorkommen`
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
detail={
|
||||||
|
<List.Item.Detail
|
||||||
|
markdown={group.hits.map((hit) => hit.context).join("\n\n")}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
actions={
|
||||||
|
<ActionPanel>
|
||||||
|
<Action
|
||||||
|
title={all ? "Nicht maskieren" : "Maskieren"}
|
||||||
|
icon={all ? Icon.XMarkCircle : Icon.CheckCircle}
|
||||||
|
onAction={() => toggle(ids)}
|
||||||
|
/>
|
||||||
|
{person && all && mergeTargets.length > 1 && (
|
||||||
|
<Action
|
||||||
|
title="Mit Person zusammenfassen"
|
||||||
|
icon={Icon.Link}
|
||||||
|
onAction={() =>
|
||||||
|
push(
|
||||||
|
<PersonMergeTargets
|
||||||
|
people={mergeTargets.filter(
|
||||||
|
({ placeholder }) => placeholder !== canonical,
|
||||||
|
)}
|
||||||
|
onChoose={(target) =>
|
||||||
|
setPersonMerges(
|
||||||
|
mergePeople(activeMerges, person, target),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{person && activeMerges[person] && (
|
||||||
|
<Action
|
||||||
|
title="Zusammenführung lösen"
|
||||||
|
onAction={() => {
|
||||||
|
const next = { ...activeMerges };
|
||||||
|
delete next[person];
|
||||||
|
setPersonMerges(next);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<Action
|
||||||
|
title="Auswahl bestätigen und fortfahren"
|
||||||
|
icon={Icon.CheckCircle}
|
||||||
|
onAction={confirm}
|
||||||
|
/>
|
||||||
|
{addTermAction}
|
||||||
|
</ActionPanel>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</List.Section>
|
||||||
|
))}
|
||||||
|
</List>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
export type EntityType = string;
|
export type EntityType = string;
|
||||||
|
export type CustomTerm = { type: EntityType; value: string };
|
||||||
|
|
||||||
export type MappingEntry = {
|
export type MappingEntry = {
|
||||||
original: string;
|
original: string;
|
||||||
type: EntityType;
|
type: EntityType;
|
||||||
|
merged_into?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type PlaceholderMapping = Record<string, MappingEntry>;
|
export type PlaceholderMapping = Record<string, MappingEntry>;
|
||||||
@@ -34,9 +36,11 @@ export type VelumSession = {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
mapping: PlaceholderMapping;
|
mapping: PlaceholderMapping;
|
||||||
entityTypes?: EntityType[];
|
entityTypes?: EntityType[];
|
||||||
|
excludedTerms?: Array<{ type: string; original: string }>;
|
||||||
|
customTerms?: CustomTerm[];
|
||||||
|
mappingCreatedAt?: Record<string, string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SessionMode = "reuse-active" | "new-each-request" | "daily";
|
|
||||||
export type QuickOutput = "copy" | "paste";
|
export type QuickOutput = "copy" | "paste";
|
||||||
|
|
||||||
export type ExtensionPreferences = {
|
export type ExtensionPreferences = {
|
||||||
@@ -46,7 +50,6 @@ export type ExtensionPreferences = {
|
|||||||
serviceAccountUsername: string;
|
serviceAccountUsername: string;
|
||||||
serviceAccountPassword: string;
|
serviceAccountPassword: string;
|
||||||
scope?: string;
|
scope?: string;
|
||||||
sessionMode: SessionMode;
|
|
||||||
quickOutput: QuickOutput;
|
quickOutput: QuickOutput;
|
||||||
userFullName?: string;
|
userFullName?: string;
|
||||||
maxSessions: string;
|
maxSessions: string;
|
||||||
|
|||||||
116
src/velum.ts
116
src/velum.ts
@@ -1,4 +1,9 @@
|
|||||||
import { fetchWithAuth } from "./auth";
|
import { fetchWithAuth } from "./auth";
|
||||||
|
import { restoreXlsxBuffer } from "./lib/xlsx-restoration";
|
||||||
|
import { checkProjectCapabilities } from "./lib/project-capabilities";
|
||||||
|
import { entityTypeCatalog, type EntityTypeCatalog } from "./lib/entity-types";
|
||||||
|
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY } from "./lib/image-policy";
|
||||||
|
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
|
||||||
import { getPreferences } from "./preferences";
|
import { getPreferences } from "./preferences";
|
||||||
import type {
|
import type {
|
||||||
DepseudonymizeResponse,
|
DepseudonymizeResponse,
|
||||||
@@ -19,7 +24,10 @@ export function normalizePseudonymizeResponse(
|
|||||||
|
|
||||||
for (const [key, entry] of Object.entries(response.mapping)) {
|
for (const [key, entry] of Object.entries(response.mapping)) {
|
||||||
const stripped = key.replace(/[<>]/g, "");
|
const stripped = key.replace(/[<>]/g, "");
|
||||||
normalizedMapping[`<${stripped}>`] = entry;
|
normalizedMapping[`<${stripped}>`] = {
|
||||||
|
...entry,
|
||||||
|
merged_into: entry.merged_into ? `<${entry.merged_into.replace(/[<>]/g, "")}>` : entry.merged_into,
|
||||||
|
};
|
||||||
strippedKeys.add(stripped);
|
strippedKeys.add(stripped);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,20 +104,24 @@ async function parseJsonResponse<T>(response: Response): Promise<T> {
|
|||||||
return (await response.json()) as T;
|
return (await response.json()) as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getEntityTypes(): Promise<EntityType[]> {
|
export async function getEntityTypes(): Promise<EntityTypeCatalog> {
|
||||||
const response = await fetchWithAuth(apiUrl("/api/entity-types"));
|
const response = await fetchWithAuth(apiUrl("/api/entity-types"));
|
||||||
const payload = await parseJsonResponse<{ entity_types: EntityType[] }>(
|
const payload = await parseJsonResponse<{
|
||||||
response,
|
entity_types: EntityType[];
|
||||||
);
|
default_entity_types?: EntityType[];
|
||||||
return payload.entity_types;
|
}>(response);
|
||||||
|
return entityTypeCatalog(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function pseudonymize(
|
export async function pseudonymize(
|
||||||
text: string,
|
text: string,
|
||||||
mapping: PlaceholderMapping,
|
mapping: PlaceholderMapping,
|
||||||
entityTypes?: EntityType[],
|
entityTypes?: EntityType[],
|
||||||
|
forceMasks?: Record<string, string[]>,
|
||||||
|
signal?: AbortSignal,
|
||||||
): Promise<PseudonymizeResponse> {
|
): Promise<PseudonymizeResponse> {
|
||||||
const response = await fetchWithAuth(apiUrl("/api/pseudonymize"), {
|
const response = await fetchWithAuth(apiUrl("/api/pseudonymize"), {
|
||||||
|
signal,
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -117,14 +129,102 @@ export async function pseudonymize(
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
text,
|
text,
|
||||||
mapping,
|
mapping,
|
||||||
entity_types:
|
entity_types: entityTypes,
|
||||||
entityTypes && entityTypes.length > 0 ? entityTypes : undefined,
|
force_masks: forceMasks,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
return parseJsonResponse<PseudonymizeResponse>(response);
|
return parseJsonResponse<PseudonymizeResponse>(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function analyzeDocxSegments(
|
||||||
|
segments: Array<{ text: string; kind: "text" | "author" | "link" | "email" }>,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
entityTypes: EntityType[],
|
||||||
|
forceMasks: Record<string, string[]>,
|
||||||
|
): Promise<{ mapping: PlaceholderMapping; spans: PseudonymizeResponse["spans"][] }> {
|
||||||
|
const response = await fetchWithAuth(apiUrl("/api/docx/segments"), {
|
||||||
|
method: "POST",
|
||||||
|
signal: AbortSignal.timeout(120_000),
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ segments, mapping, entity_types: entityTypes, force_masks: forceMasks }),
|
||||||
|
});
|
||||||
|
if (response.status === 404 || response.status === 405) {
|
||||||
|
throw new Error("Velum unterstützt die lokale DOCX-Analyse noch nicht. Bitte das Backend aktualisieren.");
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Velum konnte das DOCX-Analysepaket nicht verarbeiten (HTTP ${response.status}).`);
|
||||||
|
}
|
||||||
|
return parseJsonResponse(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DocumentHit = {
|
||||||
|
id: string;
|
||||||
|
source: string;
|
||||||
|
context: string;
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
type: string;
|
||||||
|
score: number;
|
||||||
|
placeholder: string;
|
||||||
|
original: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function requireProjectCapabilities(documents = false): Promise<void> {
|
||||||
|
await checkProjectCapabilities(apiUrl("/api/project-capabilities"), documents, fetchWithAuth);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DocumentResult = DocumentImageReport & {
|
||||||
|
filename: string;
|
||||||
|
content_type: string;
|
||||||
|
file_base64: string;
|
||||||
|
mapping: PlaceholderMapping;
|
||||||
|
active_placeholders: string[];
|
||||||
|
hits: DocumentHit[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function pseudonymizeDocument(
|
||||||
|
filename: string,
|
||||||
|
data: Buffer,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
forceMasks: Record<string, string[]>,
|
||||||
|
acceptedHitIds?: string[],
|
||||||
|
entityTypes?: EntityType[],
|
||||||
|
analysisMapping?: PlaceholderMapping,
|
||||||
|
imagePolicy: ImagePolicy = DEFAULT_IMAGE_POLICY,
|
||||||
|
): Promise<DocumentResult> {
|
||||||
|
checkedImagePolicy(imagePolicy);
|
||||||
|
const form = new FormData();
|
||||||
|
form.set("file", new Blob([new Uint8Array(data)]), filename);
|
||||||
|
form.set("mapping", JSON.stringify(mapping));
|
||||||
|
form.set("force_masks", JSON.stringify(forceMasks));
|
||||||
|
form.set("image_policy", imagePolicy);
|
||||||
|
if (entityTypes !== undefined) form.set("entity_types", JSON.stringify(entityTypes));
|
||||||
|
if (acceptedHitIds) form.set("accepted_hit_ids", JSON.stringify(acceptedHitIds));
|
||||||
|
if (analysisMapping) form.set("analysis_mapping", JSON.stringify(analysisMapping));
|
||||||
|
const response = await fetchWithAuth(apiUrl("/api/pseudonymize-document"), {
|
||||||
|
method: "POST", body: form,
|
||||||
|
});
|
||||||
|
const result = await parseJsonResponse<DocumentResult>(response);
|
||||||
|
return { ...result, ...checkedImageReport(result, imagePolicy) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function depseudonymizeDocument(
|
||||||
|
filename: string,
|
||||||
|
data: Buffer,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
): Promise<Buffer> {
|
||||||
|
if (/\.xlsx$/i.test(filename)) return restoreXlsxBuffer(data, mapping);
|
||||||
|
const form = new FormData();
|
||||||
|
form.set("file", new Blob([new Uint8Array(data)]), filename);
|
||||||
|
form.set("mapping", JSON.stringify(mapping));
|
||||||
|
const response = await fetchWithAuth(apiUrl("/api/depseudonymize-document"), {
|
||||||
|
method: "POST", body: form,
|
||||||
|
});
|
||||||
|
const result = await parseJsonResponse<{ file_base64: string }>(response);
|
||||||
|
return Buffer.from(result.file_base64, "base64");
|
||||||
|
}
|
||||||
|
|
||||||
export async function depseudonymize(
|
export async function depseudonymize(
|
||||||
text: string,
|
text: string,
|
||||||
mapping: PlaceholderMapping,
|
mapping: PlaceholderMapping,
|
||||||
|
|||||||
22
tests/entity-types.test.ts
Normal file
22
tests/entity-types.test.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { entityTypeCatalog } from "../src/lib/entity-types";
|
||||||
|
|
||||||
|
const all = ["PERSON", "EMAIL", "REFERENZ", "ORT", "DATUM", "URL", "IP"];
|
||||||
|
|
||||||
|
it("uses the backend default selection when Velum reports one", () => {
|
||||||
|
expect(
|
||||||
|
entityTypeCatalog({
|
||||||
|
entity_types: all,
|
||||||
|
default_entity_types: ["PERSON", "IP", "UNBEKANNT"],
|
||||||
|
}),
|
||||||
|
).toEqual({ all, defaults: ["PERSON", "IP"] });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves IP, Datum and Referenz off for backends without a default list", () => {
|
||||||
|
expect(entityTypeCatalog({ entity_types: all }).defaults).toEqual([
|
||||||
|
"PERSON",
|
||||||
|
"EMAIL",
|
||||||
|
"ORT",
|
||||||
|
"URL",
|
||||||
|
]);
|
||||||
|
});
|
||||||
118
tests/image-policy.test.ts
Normal file
118
tests/image-policy.test.ts
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { createRequire } from "node:module";
|
||||||
|
import { zipSync, unzipSync, strToU8, strFromU8 } from "fflate";
|
||||||
|
import ts from "typescript";
|
||||||
|
import * as xlsxRestoration from "../src/lib/xlsx-restoration";
|
||||||
|
import * as imagePolicy from "../src/lib/image-policy";
|
||||||
|
import * as projectCapabilities from "../src/lib/project-capabilities";
|
||||||
|
import * as entityTypes from "../src/lib/entity-types";
|
||||||
|
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "../src/lib/image-policy";
|
||||||
|
|
||||||
|
const policies = ["placeholder", "remove", "keep"] as const;
|
||||||
|
function response(policy = "placeholder", changes: Record<string, unknown> = {}) {
|
||||||
|
return { image_policy: policy, images_replaced: 2, images_removed: 0,
|
||||||
|
media_parts_removed: 3, warnings: [], file_base64: "UFIDBA==", mapping: {}, hits: [], ...changes };
|
||||||
|
}
|
||||||
|
it("verwendet Platzhalter als sicheren Standard und lehnt unbekannte Optionen ab", () => {
|
||||||
|
expect(DEFAULT_IMAGE_POLICY).toBe("placeholder");
|
||||||
|
for (const policy of policies) expect(checkedImagePolicy(policy)).toBe(policy);
|
||||||
|
expect(() => checkedImagePolicy("unknown")).toThrow();
|
||||||
|
});
|
||||||
|
it("verarbeitet Dokumente alter Stände und bei geänderter Bildoption erneut", () => {
|
||||||
|
for (const selected of policies) {
|
||||||
|
expect(sameImagePolicyCoverage(undefined, selected)).toBe(false);
|
||||||
|
expect(sameImagePolicyCoverage({}, selected)).toBe(false);
|
||||||
|
for (const saved of policies) expect(sameImagePolicyCoverage({ imagePolicy: saved }, selected)).toBe(saved === selected);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("blockiert fehlende Bestätigung, ungültige Zähler und Warnungen", () => {
|
||||||
|
for (const changes of [{ image_policy: undefined }, { image_policy: "keep" },
|
||||||
|
{ images_removed: -1 }, { images_replaced: undefined }, { warnings: undefined }]) {
|
||||||
|
expect(() => checkedImageReport(response("placeholder", changes), "placeholder")).toThrow();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("speichert nur Bildzähler und Warnungen im Dateibericht", () => {
|
||||||
|
const checked = checkedImageReport(response(), "placeholder");
|
||||||
|
expect(Object.keys(checked).sort()).toEqual(["image_policy", "images_replaced", "images_removed", "media_parts_removed", "warnings"].sort());
|
||||||
|
expect("mapping" in checked).toBe(false);
|
||||||
|
expect("file_base64" in checked).toBe(false);
|
||||||
|
});
|
||||||
|
it("zeigt auch mit sonstigen Backend-Hinweisen bei keep eine Datenschutzwarnung", () => {
|
||||||
|
const report = checkedImageReport(response("keep", { warnings: ["Anderer Hinweis"] }), "keep");
|
||||||
|
expect(report.warnings).toEqual([KEEP_IMAGE_WARNING, "Anderer Hinweis"]);
|
||||||
|
expect(summarizeImages([{ imageReport: report }, { imageReport: report }])).toEqual({
|
||||||
|
replaced: 4, removed: 0, warnings: [KEEP_IMAGE_WARNING, "Anderer Hinweis"],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it("übermittelt dieselbe Bildoption in Vorschau, Anwendung und erneutem Abgleich", async () => {
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const code = ts.transpileModule(readFileSync(new URL("../src/velum.ts", import.meta.url), "utf8"), {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2023 },
|
||||||
|
}).outputText;
|
||||||
|
const calls: FormData[] = [];
|
||||||
|
let returnedPolicy = "placeholder";
|
||||||
|
let supportsImages = true;
|
||||||
|
const mocks: Record<string, unknown> = {
|
||||||
|
"./auth": { fetchWithAuth: async (url: string, init: RequestInit = {}) => {
|
||||||
|
if (url.endsWith("capabilities")) return Response.json({ request_force_masks: true,
|
||||||
|
document_hit_review: true, document_review_mapping: true, document_restoration: true,
|
||||||
|
comment_author_review: true, revision_author_review: true, document_image_policy: supportsImages });
|
||||||
|
calls.push(init.body as FormData);
|
||||||
|
return Response.json(response(returnedPolicy));
|
||||||
|
} },
|
||||||
|
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
|
||||||
|
"./lib/image-policy": imagePolicy,
|
||||||
|
"./lib/xlsx-restoration": xlsxRestoration,
|
||||||
|
"./lib/project-capabilities": projectCapabilities,
|
||||||
|
"./lib/entity-types": entityTypes,
|
||||||
|
};
|
||||||
|
const module = { exports: {} as { pseudonymizeDocument: (...args: unknown[]) => Promise<unknown>; requireProjectCapabilities: (images?: boolean) => Promise<void> } };
|
||||||
|
new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports);
|
||||||
|
const api = module.exports;
|
||||||
|
for (const policy of policies) {
|
||||||
|
returnedPolicy = policy;
|
||||||
|
for (const accepted of [undefined, ["hit-1"], undefined, ["new-hit-1"]]) {
|
||||||
|
await api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {}, accepted, ["PERSON"], {}, policy);
|
||||||
|
expect(calls.at(-1)!.get("image_policy")).toBe(policy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
returnedPolicy = "placeholder";
|
||||||
|
await api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {});
|
||||||
|
expect(calls.at(-1)!.get("image_policy")).toBe("placeholder");
|
||||||
|
returnedPolicy = "keep";
|
||||||
|
await expect(api.pseudonymizeDocument("report.docx", Buffer.from("zip"), {}, {})).rejects.toThrow("bestätigt");
|
||||||
|
supportsImages = false;
|
||||||
|
await expect(api.requireProjectCapabilities(true)).rejects.toThrow();
|
||||||
|
await api.requireProjectCapabilities(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
it("restores XLSX locally and keeps the API route for DOCX", async () => {
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const code = ts.transpileModule(readFileSync(new URL("../src/velum.ts", import.meta.url), "utf8"), {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2023 },
|
||||||
|
}).outputText;
|
||||||
|
let requests = 0;
|
||||||
|
const mocks: Record<string, unknown> = {
|
||||||
|
"./auth": { fetchWithAuth: async () => { requests++; return Response.json({ file_base64: Buffer.from("restored docx").toString("base64") }); } },
|
||||||
|
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
|
||||||
|
"./lib/image-policy": imagePolicy,
|
||||||
|
"./lib/project-capabilities": projectCapabilities,
|
||||||
|
"./lib/entity-types": entityTypes,
|
||||||
|
"./lib/xlsx-restoration": xlsxRestoration,
|
||||||
|
};
|
||||||
|
const module = { exports: {} as { depseudonymizeDocument: (name: string, data: Buffer, mapping: Record<string, { original: string; type: string }>) => Promise<Buffer> } };
|
||||||
|
new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports);
|
||||||
|
const zip = zipSync({
|
||||||
|
"[Content_Types].xml": strToU8('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'),
|
||||||
|
"xl/workbook.xml": strToU8('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheets><sheet name="PERSON_01"/></sheets></workbook>'),
|
||||||
|
});
|
||||||
|
const restored = await module.exports.depseudonymizeDocument("book.XLSX", Buffer.from(zip), {
|
||||||
|
PERSON_01: { original: "Anna", type: "PERSON" },
|
||||||
|
});
|
||||||
|
expect(requests).toBe(0);
|
||||||
|
expect(strFromU8(unzipSync(restored)["xl/workbook.xml"])).toContain('name="Anna"');
|
||||||
|
expect(await module.exports.depseudonymizeDocument("book.docx", Buffer.from("docx"), {})).toEqual(Buffer.from("restored docx"));
|
||||||
|
expect(requests).toBe(1);
|
||||||
|
});
|
||||||
50
tests/mapping-created-at.test.ts
Normal file
50
tests/mapping-created-at.test.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { projectMappingCreatedAt, sortMappingRowsByCreatedAt } from "../src/lib/mapping-created-at";
|
||||||
|
import type { ProjectRun } from "../src/lib/velum-project";
|
||||||
|
import type { PlaceholderMapping } from "../src/types";
|
||||||
|
|
||||||
|
function run(createdAt: string, mapping: PlaceholderMapping): ProjectRun {
|
||||||
|
return { version: 2, id: createdAt, projectPath: "/synthetic", projectName: "synthetic",
|
||||||
|
createdAt, mapping, files: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
it("ermittelt die erste gespeicherte Projektfassung je unveränderter Zuordnung", () => {
|
||||||
|
const earlier = run("2026-01-01T10:00:00.000Z", {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Beispiel Eins" },
|
||||||
|
ORG_01: { type: "ORG", original: "Frühere Organisation" },
|
||||||
|
});
|
||||||
|
const latest = run("2026-02-01T10:00:00.000Z", {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Beispiel Eins" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Beispiel Zwei" },
|
||||||
|
ORG_01: { type: "ORG", original: "Neue Organisation" },
|
||||||
|
});
|
||||||
|
expect(projectMappingCreatedAt([latest, earlier], latest.mapping)).toEqual({
|
||||||
|
PERSON_01: earlier.createdAt,
|
||||||
|
PERSON_02: latest.createdAt,
|
||||||
|
ORG_01: latest.createdAt,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sortiert datierte Zuordnungen zuerst, sonst Nummern je Kategorie absteigend", () => {
|
||||||
|
const rows = ["PERSON_02", "ORT_03", "PERSON_100", "ORT_20", "ORG_01", "PERSON_10"]
|
||||||
|
.map((placeholder) => ({ placeholder, type: placeholder.split("_")[0] }));
|
||||||
|
const sorted = sortMappingRowsByCreatedAt(rows, {
|
||||||
|
PERSON_02: "2026-05-01T00:00:00.000Z",
|
||||||
|
ORG_01: "2026-06-01T00:00:00.000Z",
|
||||||
|
});
|
||||||
|
expect(sorted.map((row) => row.placeholder))
|
||||||
|
.toEqual(["ORG_01", "PERSON_02", "ORT_20", "ORT_03", "PERSON_100", "PERSON_10"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("behandelt importierte Erststände ohne echtes Anlagedatum als Nummern-Fallback", () => {
|
||||||
|
const imported = { ...run("2026-01-01T10:00:00.000Z", {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Altbestand" },
|
||||||
|
}), origin: "imported" as const };
|
||||||
|
const later = { ...run("2026-02-01T10:00:00.000Z", {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Altbestand" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Neu" },
|
||||||
|
}), origin: "imported" as const, revisedFrom: imported.id };
|
||||||
|
expect(projectMappingCreatedAt([later, imported], later.mapping)).toEqual({
|
||||||
|
PERSON_02: later.createdAt,
|
||||||
|
});
|
||||||
|
});
|
||||||
92
tests/mapping-export.test.ts
Normal file
92
tests/mapping-export.test.ts
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import { afterEach, expect, it } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { basename, dirname, join } from "node:path";
|
||||||
|
import type { PlaceholderMapping } from "../src/types";
|
||||||
|
import { mappingExport, writeMappingExport } from "../src/lib/mapping-export";
|
||||||
|
|
||||||
|
const mapping: PlaceholderMapping = {
|
||||||
|
PERSON_02: { type: "PERSON", original: "Zweiter Name", merged_into: "PERSON_01" },
|
||||||
|
ORG_01: { type: "ORG", original: "Äpfel GmbH" },
|
||||||
|
PERSON_01: { type: "PERSON", original: "Anna Beispiel" },
|
||||||
|
PERSON_03: { type: "PERSON", original: "Anna Beispiel", merged_into: "PERSON_01" },
|
||||||
|
};
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => { await Promise.all(roots.splice(0).map((path) => fs.rm(path, { recursive: true, force: true }))); });
|
||||||
|
async function temporaryDirectory() {
|
||||||
|
const path = await fs.mkdtemp(join(tmpdir(), "velum-mapping-export-"));
|
||||||
|
roots.push(path);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("exportiert alle Originalbegriffe samt Varianten einmal und ohne Platzhalter", () => {
|
||||||
|
const snapshot = structuredClone(mapping);
|
||||||
|
expect(mappingExport(mapping, "terms")).toEqual({
|
||||||
|
text: "Anna Beispiel\nÄpfel GmbH\nZweiter Name\n", count: 3,
|
||||||
|
});
|
||||||
|
expect(mapping).toEqual(snapshot);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("exportiert jede wirksame Ersetzung und bewahrt unterschiedliche Platzhalter desselben Originals", () => {
|
||||||
|
const result = mappingExport({ ...mapping,
|
||||||
|
BEGRIFF_01: { type: "BEGRIFF", original: "Anna Beispiel" },
|
||||||
|
}, "replacements");
|
||||||
|
expect(result.count).toBe(4);
|
||||||
|
expect(result.text.split("\n").filter(Boolean)).toEqual([
|
||||||
|
"Anna Beispiel → BEGRIFF_01", "Anna Beispiel → PERSON_01",
|
||||||
|
"Äpfel GmbH → ORG_01", "Zweiter Name → PERSON_01",
|
||||||
|
]);
|
||||||
|
expect(result.text).not.toContain("→ PERSON_02");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("erhält Unicode, Klammer-Platzhalter sowie unterscheidbare Tabs und Zeilenumbrüche", () => {
|
||||||
|
const special = { "<PERSON_01>": { type: "PERSON", original: "Jörg\nMüller\r\nA\tB\\n" } };
|
||||||
|
expect(mappingExport(special, "terms").text).toBe("Jörg\\nMüller\\r\\nA\\tB\\\\n\n");
|
||||||
|
expect(mappingExport(special, "replacements").text).toBe("Jörg\\nMüller\\r\\nA\\tB\\\\n → <PERSON_01>\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("berücksichtigt den übergebenen aktuellen Stand einschließlich neuer und gelöster Zuordnungen", () => {
|
||||||
|
const current = { ...mapping,
|
||||||
|
PERSON_02: { ...mapping.PERSON_02, merged_into: undefined },
|
||||||
|
EMAIL_01: { type: "EMAIL", original: "neu@example.test" },
|
||||||
|
};
|
||||||
|
const text = mappingExport(current, "replacements").text;
|
||||||
|
expect(text).toContain("Zweiter Name → PERSON_02\n");
|
||||||
|
expect(text).toContain("neu@example.test → EMAIL_01\n");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("schreibt UTF-8 lokal mit privaten Rechten und überschreibt keine vorhandenen Exporte", async () => {
|
||||||
|
const directory = await temporaryDirectory();
|
||||||
|
const first = await writeMappingExport("Projekt", mapping, "terms", directory);
|
||||||
|
const second = await writeMappingExport("Projekt", mapping, "terms", directory);
|
||||||
|
const replacements = await writeMappingExport("Projekt", mapping, "replacements", directory);
|
||||||
|
expect(basename(first.path)).toBe("Projekt-begriffe.txt");
|
||||||
|
expect(basename(second.path)).toBe("Projekt-begriffe (2).txt");
|
||||||
|
expect(basename(replacements.path)).toBe("Projekt-ersetzungen.txt");
|
||||||
|
expect(await fs.readFile(first.path, "utf8")).toBe(mappingExport(mapping, "terms").text);
|
||||||
|
expect(await fs.readFile(replacements.path, "utf8")).toBe(mappingExport(mapping, "replacements").text);
|
||||||
|
for (const file of [first, second, replacements]) expect((await fs.stat(file.path)).mode & 0o777).toBe(0o600);
|
||||||
|
expect((await fs.readdir(directory)).length).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("begrenzt Dateinamen auf das Exportverzeichnis und bewahrt parallele Exporte", async () => {
|
||||||
|
const directory = await temporaryDirectory();
|
||||||
|
const exports = await Promise.all(Array.from({ length: 4 }, () =>
|
||||||
|
writeMappingExport("../../Projekt\\Datei\n" + "漢".repeat(200), mapping, "terms", directory)));
|
||||||
|
expect(new Set(exports.map((file) => file.path)).size).toBe(4);
|
||||||
|
for (const file of exports) {
|
||||||
|
expect(dirname(file.path)).toBe(directory);
|
||||||
|
expect(Buffer.byteLength(basename(file.path))).toBeLessThan(255);
|
||||||
|
expect(await fs.readFile(file.path, "utf8")).toBe(mappingExport(mapping, "terms").text);
|
||||||
|
}
|
||||||
|
expect((await fs.readdir(directory)).length).toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("erzeugt bei leerer Tabelle oder defekten Gruppen keine unvollständige Exportdatei", async () => {
|
||||||
|
const directory = await temporaryDirectory();
|
||||||
|
expect(mappingExport({}, "terms")).toEqual({ text: "", count: 0 });
|
||||||
|
await expect(writeMappingExport("Leer", {}, "terms", directory)).rejects.toThrow("keine Begriffe");
|
||||||
|
const broken = { PERSON_01: { type: "PERSON", original: "Name", merged_into: "PERSON_02" } };
|
||||||
|
await expect(writeMappingExport("Defekt", broken, "replacements", directory)).rejects.toThrow("Hauptbegriff");
|
||||||
|
expect(await fs.readdir(directory)).toEqual([]);
|
||||||
|
});
|
||||||
49
tests/mapping-groups.test.ts
Normal file
49
tests/mapping-groups.test.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { detachMappingGroup, mappingForRestoration, mergeMappingGroups } from "../src/lib/mapping-groups";
|
||||||
|
import type { PlaceholderMapping } from "../src/types";
|
||||||
|
|
||||||
|
describe("Zuordnungen gruppieren und wiederherstellen", () => {
|
||||||
|
const original: PlaceholderMapping = {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Franz F.", merged_into: "PERSON_01" },
|
||||||
|
PERSON_03: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_02" },
|
||||||
|
PERSON_04: { type: "PERSON", original: "Mara Muster" },
|
||||||
|
ORG_01: { type: "ORG", original: "Muster GmbH" },
|
||||||
|
};
|
||||||
|
|
||||||
|
it("verwendet für alle Verweise den Hauptbegriff ohne die gespeicherten Varianten zu ändern", () => {
|
||||||
|
const restored = mappingForRestoration(original);
|
||||||
|
expect(restored.PERSON_01.original).toBe("Franz Fuchs");
|
||||||
|
expect(restored.PERSON_02.original).toBe("Franz Fuchs");
|
||||||
|
expect(restored.PERSON_03.original).toBe("Franz Fuchs");
|
||||||
|
expect(restored.PERSON_03.merged_into).toBeUndefined();
|
||||||
|
expect(original.PERSON_03.original).toBe("Hr. Fuchs");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("fasst ganze Gruppen zusammen und kann einen einzelnen Verweis wieder lösen", () => {
|
||||||
|
const merged = mergeMappingGroups(original, "PERSON_02", "PERSON_04");
|
||||||
|
expect(merged.PERSON_01.merged_into).toBe("PERSON_04");
|
||||||
|
expect(merged.PERSON_02.merged_into).toBe("PERSON_04");
|
||||||
|
expect(merged.PERSON_03.merged_into).toBe("PERSON_04");
|
||||||
|
expect(mappingForRestoration(merged).PERSON_03.original).toBe("Mara Muster");
|
||||||
|
expect(detachMappingGroup(merged, "PERSON_03").PERSON_03.merged_into).toBeUndefined();
|
||||||
|
expect(original.PERSON_01.merged_into).toBeUndefined();
|
||||||
|
expect(() => mergeMappingGroups(original, "PERSON_01", "ORG_01")).toThrow("derselben Kategorie");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stoppt defekte oder zyklische Verweise vor dem Klartext-Export", () => {
|
||||||
|
expect(() => mappingForRestoration({ PERSON_01: { type: "PERSON", original: "A", merged_into: "PERSON_99" } }))
|
||||||
|
.toThrow("Ungültiger Hauptbegriff");
|
||||||
|
expect(() => mappingForRestoration({
|
||||||
|
PERSON_01: { type: "PERSON", original: "A", merged_into: "PERSON_02" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "B", merged_into: "PERSON_01" },
|
||||||
|
})).toThrow("Zyklische Zuordnung");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("löst ältere Sitzungsverweise mit geklammerten Schlüsseln auf", () => {
|
||||||
|
expect(mappingForRestoration({
|
||||||
|
"<PERSON_01>": { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
"<PERSON_02>": { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
|
||||||
|
})["<PERSON_02>"].original).toBe("Franz Fuchs");
|
||||||
|
});
|
||||||
|
});
|
||||||
98
tests/migration.test.ts
Normal file
98
tests/migration.test.ts
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
import { afterEach, expect, it, mock } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { migrate } from "../tools/migrate-ki-datenschutz.mjs";
|
||||||
|
|
||||||
|
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() },
|
||||||
|
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
|
||||||
|
LocalStorage: {}, getPreferenceValues: () => ({}) }));
|
||||||
|
const { restorePath, restoreText } = await import("../src/lib/velum-project");
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); });
|
||||||
|
|
||||||
|
it("migriert einen künstlichen Altbestand verlustarm ohne den Quellordner zu ändern", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-legacy-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const project = join(root, "Projekt");
|
||||||
|
const targetSupport = join(root, "VelumSupport");
|
||||||
|
const oldSupport = join(root, "OldSupport");
|
||||||
|
const previewFile = join(root, "Migrationsvorschau.md");
|
||||||
|
await fs.mkdir(project);
|
||||||
|
await fs.mkdir(join(oldSupport, "projects"), { recursive: true });
|
||||||
|
const legacyName = "KUNDE ALPHA.txt";
|
||||||
|
const legacyContent = "kundeAlphaService und KUNDE ALPHA";
|
||||||
|
await fs.writeFile(join(project, legacyName), legacyContent);
|
||||||
|
await fs.writeFile(join(project, "Handbuch.docx"), "office");
|
||||||
|
await fs.writeFile(join(project, "leer.txt"), "Ohne Platzhalter");
|
||||||
|
const projectId = createHash("sha1").update(project).digest("hex").slice(0, 16);
|
||||||
|
const manifestFile = join(oldSupport, "projects", `${projectId}.json`);
|
||||||
|
await fs.writeFile(manifestFile, JSON.stringify({
|
||||||
|
version: 1, projectPath: project, projectTerms: [{ id: "t1", term: "Müller GmbH", category: "Kunde", enabled: true, aliases: [] }],
|
||||||
|
variantTable: [
|
||||||
|
{ termId: "t1", termVariant: "Müller GmbH", placeholderVariant: "KUNDE ALPHA", style: "typed", boundary: "strict" },
|
||||||
|
{ termId: "t1", termVariant: "muellerGmbh", placeholderVariant: "kundeAlpha", style: "camel", boundary: "identifier" },
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
const preview = await migrate({ project, manifestFile, targetSupport, previewFile });
|
||||||
|
expect(preview.applied).toBe(false);
|
||||||
|
expect(preview.summary.files).toBe(2);
|
||||||
|
expect(preview.summary.skipped).toBe(1);
|
||||||
|
const report = await fs.readFile(previewFile, "utf8");
|
||||||
|
expect(report).toContain('"KUNDE ALPHA.txt"');
|
||||||
|
expect(report).toContain('"KUNDE_100001.txt"');
|
||||||
|
expect(report).toContain('"kundeAlpha" → "KUNDE_100002" (1×)');
|
||||||
|
expect(report).toContain('"Handbuch.docx": Office- oder PDF-Datei');
|
||||||
|
expect(report).toContain("Keine Änderung.");
|
||||||
|
expect(report).not.toContain("Müller GmbH");
|
||||||
|
expect((await fs.stat(previewFile)).mode & 0o777).toBe(0o600);
|
||||||
|
expect(await fs.readFile(join(project, legacyName), "utf8")).toBe(legacyContent);
|
||||||
|
expect(await fs.readdir(root)).not.toContain("VelumSupport");
|
||||||
|
await expect(migrate({ project, manifestFile, targetSupport, previewFile })).rejects.toMatchObject({ code: "EEXIST" });
|
||||||
|
await expect(migrate({ project, manifestFile, targetSupport, previewFile, apply: true })).rejects.toThrow();
|
||||||
|
await expect(migrate({ project, manifestFile, targetSupport,
|
||||||
|
previewFile: join(project, "vorschau.md") })).rejects.toThrow();
|
||||||
|
|
||||||
|
const result = await migrate({ project, manifestFile, targetSupport, apply: true });
|
||||||
|
expect(result.applied).toBe(true);
|
||||||
|
const run = JSON.parse(await fs.readFile(join(result.runDir!, "run.json"), "utf8"));
|
||||||
|
const file = run.files[0];
|
||||||
|
const content = await fs.readFile(join(result.runDir!, "files", file.output), "utf8");
|
||||||
|
expect(restoreText(content, run.mapping, run.matchModes)).toBe("muellerGmbhService und Müller GmbH");
|
||||||
|
expect(restorePath(file.output, run.mapping, run.matchModes)).toBe("Müller GmbH.txt");
|
||||||
|
expect(await fs.readFile(join(project, legacyName), "utf8")).toBe(legacyContent);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ersetzt Platzhalter hinter URL-kodierten Pfadtrennern im Dateinamen", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-encoded-name-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const project = join(root, "Projekt");
|
||||||
|
const targetSupport = join(root, "VelumSupport");
|
||||||
|
const manifestFile = join(root, "OldSupport", "projects", "manifest.json");
|
||||||
|
const previewFile = join(root, "Vorschau.md");
|
||||||
|
await fs.mkdir(join(project, "KUNDE_A"), { recursive: true });
|
||||||
|
await fs.mkdir(join(root, "OldSupport", "projects"), { recursive: true });
|
||||||
|
const source = "KUNDE_A/%2fkunde_a%2fzc.asddls";
|
||||||
|
await fs.writeFile(join(project, source), "Technischer Inhalt");
|
||||||
|
await fs.writeFile(manifestFile, JSON.stringify({
|
||||||
|
version: 1, projectPath: project,
|
||||||
|
projectTerms: [{ id: "t1", term: "Alpha GmbH", category: "Kunde", enabled: true, aliases: [] }],
|
||||||
|
variantTable: [
|
||||||
|
{ termId: "t1", termVariant: "Alpha GmbH", placeholderVariant: "KUNDE_A", style: "typed", boundary: "strict" },
|
||||||
|
{ termId: "t1", termVariant: "alpha_gmbh", placeholderVariant: "kunde_a", style: "snake", boundary: "strict" },
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
const preview = await migrate({ project, manifestFile, targetSupport, previewFile });
|
||||||
|
expect(preview.summary.replacements).toBe(2);
|
||||||
|
const report = await fs.readFile(previewFile, "utf8");
|
||||||
|
expect(report).toContain('"KUNDE_A/%2fkunde_a%2fzc.asddls"');
|
||||||
|
expect(report).toContain('"KUNDE_100001/%2fKUNDE_100002%2fzc.asddls"');
|
||||||
|
expect(report).not.toContain("Alpha GmbH");
|
||||||
|
|
||||||
|
const result = await migrate({ project, manifestFile, targetSupport, apply: true });
|
||||||
|
const run = JSON.parse(await fs.readFile(join(result.runDir!, "run.json"), "utf8"));
|
||||||
|
expect(restorePath(run.files[0].output, run.mapping, run.matchModes))
|
||||||
|
.toBe("Alpha GmbH/%2falpha_gmbh%2fzc.asddls");
|
||||||
|
expect(await fs.readFile(join(project, source), "utf8")).toBe("Technischer Inhalt");
|
||||||
|
});
|
||||||
88
tests/person-propagation.test.ts
Normal file
88
tests/person-propagation.test.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { propagateDocxPersons } from "../src/lib/person-propagation";
|
||||||
|
import type { Hit } from "../src/lib/project-work";
|
||||||
|
import type { PlaceholderMapping } from "../src/types";
|
||||||
|
|
||||||
|
// Synthetic names only. The model recognizes them in the introduction, but
|
||||||
|
// not in the later paragraphs (observed with de_core_news_lg).
|
||||||
|
const segments = [
|
||||||
|
{ text: "Projektleitung: Frau Jorinde Quastenberg, Fachbereich Planung.", source: "Absatz", kind: "text" },
|
||||||
|
{ text: "Grüße Talvin", source: "Absatz", kind: "text" },
|
||||||
|
...Array.from({ length: 26 }, () => [
|
||||||
|
{ text: "bei Quastenberg nachfragen", source: "Absatz", kind: "text" },
|
||||||
|
{ text: "Feedback Jorinde Quastenberg: passt. 😀 Quastenberg", source: "Absatz", kind: "text" },
|
||||||
|
]).flat(),
|
||||||
|
{ text: "Quastenbergstraße und Talvin bleiben", source: "Absatz", kind: "text" },
|
||||||
|
{ text: "Jorinde Quastenberg", source: "Kommentar-Link", kind: "link" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function hit(segment: number, start: number, original: string, placeholder: string, score = 0.85): Hit {
|
||||||
|
return { id: `a.docx:local-docx:${segment}:${start}:${start + original.length}`, file: "a.docx", source: "Absatz",
|
||||||
|
original, placeholder, type: "PERSON", score, context: "", start, end: start + original.length,
|
||||||
|
kind: "content", segment };
|
||||||
|
}
|
||||||
|
|
||||||
|
it("masks every occurrence of a recognized person name across DOCX segments", () => {
|
||||||
|
const mapping: PlaceholderMapping = {
|
||||||
|
PERSON_01: { original: "Jorinde Quastenberg", type: "PERSON" },
|
||||||
|
PERSON_02: { original: "Talvin", type: "PERSON" },
|
||||||
|
};
|
||||||
|
const detected = [hit(0, 21, "Jorinde Quastenberg", "PERSON_01"), hit(1, 6, "Talvin", "PERSON_02", 0.99)];
|
||||||
|
const result = propagateDocxPersons(segments, detected, mapping, "a.docx");
|
||||||
|
|
||||||
|
const masked = segments.map((segment, index) => {
|
||||||
|
const characters = Array.from(segment.text);
|
||||||
|
for (const found of result.hits.filter((entry) => entry.segment === index)) {
|
||||||
|
expect(characters.slice(found.start, found.end).join("")).toBe(found.original);
|
||||||
|
for (let position = found.start; position < found.end; position++) characters[position] = "#";
|
||||||
|
}
|
||||||
|
return characters.join("");
|
||||||
|
});
|
||||||
|
const remaining = masked.slice(0, -1).join("\n").match(/(?<![\p{L}])Quastenberg(?![\p{L}])/gu) ?? [];
|
||||||
|
expect(remaining).toHaveLength(0);
|
||||||
|
expect(result.hits).toHaveLength(2 + 26 * 3);
|
||||||
|
|
||||||
|
const surname = result.hits.find((entry) => entry.original === "Quastenberg")!;
|
||||||
|
expect(surname.placeholder).toBe("PERSON_03");
|
||||||
|
expect(result.mapping.PERSON_03).toEqual({ original: "Quastenberg", type: "PERSON" });
|
||||||
|
expect(result.hits.filter((entry) => entry.original === "Jorinde Quastenberg").every(
|
||||||
|
(entry) => entry.placeholder === "PERSON_01")).toBe(true);
|
||||||
|
// Unicode offsets count code points, like the Python codec.
|
||||||
|
expect(result.hits.find((entry) => entry.segment === 3 && entry.start > 30)!.start).toBe(39);
|
||||||
|
// No partial words, no lone first name without a full name, no link fields.
|
||||||
|
expect(masked[54]).toBe("Quastenbergstraße und Talvin bleiben");
|
||||||
|
expect(result.hits.some((entry) => entry.segment === 55)).toBe(false);
|
||||||
|
expect(mapping.PERSON_03).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not seed propagation from weak or merged-away hits", () => {
|
||||||
|
const mapping: PlaceholderMapping = {
|
||||||
|
PERSON_04: { original: "Jorinde Quastenberg", type: "PERSON" },
|
||||||
|
PERSON_07: { original: "Quastenberg", type: "PERSON", merged_into: "PERSON_04" },
|
||||||
|
};
|
||||||
|
const weak = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04", 0.6)], mapping, "a.docx");
|
||||||
|
expect(weak.hits).toHaveLength(1);
|
||||||
|
|
||||||
|
const merged = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04")], mapping, "a.docx");
|
||||||
|
expect(merged.hits.find((entry) => entry.original === "Quastenberg")!.placeholder).toBe("PERSON_04");
|
||||||
|
expect(Object.keys(merged.mapping)).toEqual(["PERSON_04", "PERSON_07"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("seeds from salutation hits without the salutation and keeps the genitive s", () => {
|
||||||
|
const texts = ["Projektleitung: Frau Jorinde Quastenberg, Planung.", "Dr. Ostermeier ist informiert.",
|
||||||
|
"Quastenbergs Bericht und Ostermeiers Notiz liegen vor.", "Frau und Herr bleiben Wörter.", "Ostermeierhof"];
|
||||||
|
const result = propagateDocxPersons(texts.map((text) => ({ text, source: "Absatz", kind: "text" })), [
|
||||||
|
hit(0, 16, "Frau Jorinde Quastenberg", "PERSON_01", 0.7),
|
||||||
|
hit(1, 0, "Dr. Ostermeier", "PERSON_02", 0.7),
|
||||||
|
], {
|
||||||
|
PERSON_01: { original: "Frau Jorinde Quastenberg", type: "PERSON" },
|
||||||
|
PERSON_02: { original: "Dr. Ostermeier", type: "PERSON" },
|
||||||
|
}, "a.docx");
|
||||||
|
const added = result.hits.filter((entry) => !["PERSON_01", "PERSON_02"].includes(entry.placeholder));
|
||||||
|
expect(added.map((entry) => [entry.segment, entry.original, texts[entry.segment!].slice(entry.start, entry.end)]))
|
||||||
|
.toEqual([[2, "Quastenberg", "Quastenberg"], [2, "Ostermeier", "Ostermeier"]]);
|
||||||
|
expect(result.hits.filter((entry) => entry.segment === 3 || entry.segment === 4)).toHaveLength(0);
|
||||||
|
expect(Object.values(result.mapping).map((entry) => entry.original)).toEqual([
|
||||||
|
"Frau Jorinde Quastenberg", "Dr. Ostermeier", "Quastenberg", "Ostermeier",
|
||||||
|
]);
|
||||||
|
});
|
||||||
162
tests/project-analysis.test.ts
Normal file
162
tests/project-analysis.test.ts
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import {
|
||||||
|
analyzeProjectBatch,
|
||||||
|
analyzeProjectTexts,
|
||||||
|
splitTextForAnalysis,
|
||||||
|
} from "../src/lib/project-analysis";
|
||||||
|
import { makeTextBatches, spansBySegment } from "../src/lib/project-review";
|
||||||
|
import type { PlaceholderMapping, PseudonymizeResponse } from "../src/types";
|
||||||
|
|
||||||
|
function response(
|
||||||
|
text: string,
|
||||||
|
mapping: PlaceholderMapping,
|
||||||
|
): PseudonymizeResponse {
|
||||||
|
const original = text.includes("Anna") ? "Anna" : "Berta";
|
||||||
|
const placeholder = original === "Anna" ? "PERSON_01" : "PERSON_02";
|
||||||
|
return {
|
||||||
|
pseudonymized_text: text.replace(original, placeholder),
|
||||||
|
selected_entity_types: ["PERSON"],
|
||||||
|
mapping: { ...mapping, [placeholder]: { original, type: "PERSON" } },
|
||||||
|
entity_count: 1,
|
||||||
|
spans: [
|
||||||
|
{
|
||||||
|
start: text.indexOf(original),
|
||||||
|
end: text.indexOf(original) + original.length,
|
||||||
|
original,
|
||||||
|
placeholder,
|
||||||
|
type: "PERSON",
|
||||||
|
score: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
it("zerlegt einen fehlgeschlagenen Analyseblock und erhält Dateigrenzen und Zuordnungen", async () => {
|
||||||
|
const [batch] = makeTextBatches([
|
||||||
|
{ key: "a.md", text: "Anna" },
|
||||||
|
{ key: "b.md", text: "Berta" },
|
||||||
|
]);
|
||||||
|
const calls: string[] = [];
|
||||||
|
const analyzed = await analyzeProjectBatch(
|
||||||
|
batch,
|
||||||
|
{},
|
||||||
|
["PERSON"],
|
||||||
|
{},
|
||||||
|
async (text, mapping) => {
|
||||||
|
calls.push(text);
|
||||||
|
if (text.includes("Anna") && text.includes("Berta"))
|
||||||
|
throw new Error("Velum API request failed: 500 Internal Server Error");
|
||||||
|
return response(text, mapping);
|
||||||
|
},
|
||||||
|
"Textdateien analysieren",
|
||||||
|
);
|
||||||
|
expect(calls).toHaveLength(3);
|
||||||
|
expect(Object.keys(analyzed.mapping)).toEqual(["PERSON_01", "PERSON_02"]);
|
||||||
|
expect(
|
||||||
|
analyzed.results.flatMap(({ batch: part, result }) => [
|
||||||
|
...spansBySegment(part, result.spans).keys(),
|
||||||
|
]),
|
||||||
|
).toEqual(["a.md", "b.md"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("nennt nach der Eingrenzung die fehlerhafte Datei", async () => {
|
||||||
|
const [batch] = makeTextBatches([
|
||||||
|
{ key: "a.md", text: "Anna" },
|
||||||
|
{ key: "b.md", text: "Berta" },
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
analyzeProjectBatch(
|
||||||
|
batch,
|
||||||
|
{},
|
||||||
|
["PERSON"],
|
||||||
|
{},
|
||||||
|
async (text, mapping) => {
|
||||||
|
if (text.includes("Berta"))
|
||||||
|
throw new Error(
|
||||||
|
"Velum API request failed: 500 Internal Server Error",
|
||||||
|
);
|
||||||
|
return response(text, mapping);
|
||||||
|
},
|
||||||
|
"Textdateien analysieren",
|
||||||
|
),
|
||||||
|
).rejects.toThrow(
|
||||||
|
"Textdateien analysieren: b.md: Velum API request failed: 500",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("analysiert eine große Textdatei abschnittsweise und ordnet Grenztreffer an der Originalposition zu", async () => {
|
||||||
|
const prefix = `😀${"x ".repeat(4999)}Max `;
|
||||||
|
const source = `${prefix}Mustermann ${"text ".repeat(3000)}`;
|
||||||
|
const requests: number[] = [];
|
||||||
|
const analyzed = await analyzeProjectTexts(
|
||||||
|
[{ key: "groß.txt", text: source }],
|
||||||
|
{},
|
||||||
|
["PERSON"],
|
||||||
|
{},
|
||||||
|
async (text, mapping) => {
|
||||||
|
requests.push(text.length);
|
||||||
|
const matches = [...text.matchAll(/Max Mustermann/g)].map((match) => {
|
||||||
|
const start = [...text.slice(0, match.index)].length;
|
||||||
|
return {
|
||||||
|
start,
|
||||||
|
end: start + 14,
|
||||||
|
type: "PERSON",
|
||||||
|
original: "Max Mustermann",
|
||||||
|
placeholder: "PERSON_01",
|
||||||
|
score: 1,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
pseudonymized_text: text,
|
||||||
|
selected_entity_types: ["PERSON"],
|
||||||
|
mapping: matches.length
|
||||||
|
? {
|
||||||
|
...mapping,
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
}
|
||||||
|
: mapping,
|
||||||
|
entity_count: matches.length ? 1 : 0,
|
||||||
|
spans: matches,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
|
expect(requests.length).toBeGreaterThan(1);
|
||||||
|
expect(Math.max(...requests)).toBeLessThan(24_000);
|
||||||
|
expect(analyzed.spansByFile.get("groß.txt")).toEqual([
|
||||||
|
{
|
||||||
|
start: prefix.length - 4,
|
||||||
|
end: prefix.length + 10,
|
||||||
|
type: "PERSON",
|
||||||
|
original: "Max Mustermann",
|
||||||
|
placeholder: "PERSON_01",
|
||||||
|
score: 1,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verweigert das stumme Zerschneiden eines überlangen Worts", () => {
|
||||||
|
expect(() => splitTextForAnalysis("x".repeat(100), 20, 5)).toThrow(
|
||||||
|
"ohne Trennstelle",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("zerlegt HTTP 413 ohne bestehende Zuordnungen oder Dateigrenzen zu verlieren", async () => {
|
||||||
|
const [batch] = makeTextBatches([{ key: "a", text: "Anna" }, { key: "b", text: "Berta" }]);
|
||||||
|
let calls = 0;
|
||||||
|
const result = await analyzeProjectBatch(batch, {}, ["PERSON"], {}, async (text, mapping) => {
|
||||||
|
calls++; if (text.includes("Anna") && text.includes("Berta")) throw new Error("Velum API request failed: 413 Payload Too Large");
|
||||||
|
return response(text, mapping);
|
||||||
|
}, "Test");
|
||||||
|
expect(calls).toBe(3); expect(Object.keys(result.mapping)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
it("wiederholt Authentifizierungs- und Validierungsfehler nicht", async () => {
|
||||||
|
const [batch] = makeTextBatches([{ key: "a", text: "Anna" }, { key: "b", text: "Berta" }]);
|
||||||
|
for (const status of [401, 403, 422]) {
|
||||||
|
let calls = 0;
|
||||||
|
await expect(analyzeProjectBatch(batch, {}, ["PERSON"], {}, async () => {
|
||||||
|
calls++; throw new Error(`Velum API request failed: ${status}`);
|
||||||
|
}, "Test")).rejects.toThrow(String(status));
|
||||||
|
expect(calls).toBe(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
42
tests/project-capabilities.test.ts
Normal file
42
tests/project-capabilities.test.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { checkProjectCapabilities, requiredProjectCapabilities } from "../src/lib/project-capabilities";
|
||||||
|
const url = "https://velum.invalid/api/project-capabilities";
|
||||||
|
const reply = (value: unknown) => async () => Response.json(value);
|
||||||
|
it("reproduziert die alte Meldung: Textprojekt benötigt keine Office-Fähigkeiten", async () => {
|
||||||
|
const olderBackend = { request_force_masks: true, document_hit_review: true, document_restoration: true };
|
||||||
|
await checkProjectCapabilities(url, false, reply(olderBackend));
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply(olderBackend))).rejects.toThrow("document_review_mapping");
|
||||||
|
});
|
||||||
|
it("prüft jede Office-Schutzfunktion strikt, einschließlich Bilder und Autoren", async () => {
|
||||||
|
const complete = Object.fromEntries(requiredProjectCapabilities(true).map((key) => [key, true]));
|
||||||
|
await checkProjectCapabilities(url, true, reply(complete));
|
||||||
|
for (const key of Object.keys(complete)) {
|
||||||
|
const missing = { ...complete }; delete missing[key];
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply(missing))).rejects.toThrow(key);
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply({ ...complete, [key]: "true" }))).rejects.toThrow(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
it("unterscheidet fehlende Endpunkte, Anmeldung, Größenlimits und Gateway-Fehler", async () => {
|
||||||
|
for (const status of [401, 403, 404, 405, 413, 502, 504]) {
|
||||||
|
await expect(checkProjectCapabilities(url, false, async () => new Response("", { status })))
|
||||||
|
.rejects.toThrow(`HTTP ${status}`);
|
||||||
|
}
|
||||||
|
await expect(checkProjectCapabilities(url, false, async () => new Response("Login", {
|
||||||
|
headers: { "content-type": "text/html" },
|
||||||
|
}))).rejects.toThrow("Keine JSON-Antwort");
|
||||||
|
});
|
||||||
|
it("meldet URL, fehlende Fähigkeit, ungültige Antwort und Zeitlimit", async () => {
|
||||||
|
await expect(checkProjectCapabilities(url, false, reply({}))).rejects.toThrow("request_force_masks");
|
||||||
|
for (const value of [null, [], true]) await expect(checkProjectCapabilities(url, false, reply(value)))
|
||||||
|
.rejects.toThrow("Ungültige Projektfähigkeiten");
|
||||||
|
await expect(checkProjectCapabilities(url, false, async (_url, init) => {
|
||||||
|
expect(init.signal).toBeDefined(); throw new DOMException("Deadline", "TimeoutError");
|
||||||
|
})).rejects.toThrow("Zeitlimit");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reproduziert die Live-API vom 8. November ohne document_image_policy", async () => {
|
||||||
|
const live = { request_force_masks: true, document_hit_review: true, document_review_mapping: true,
|
||||||
|
document_restoration: true, comment_author_review: true, revision_author_review: true };
|
||||||
|
await checkProjectCapabilities(url, false, reply(live));
|
||||||
|
await expect(checkProjectCapabilities(url, true, reply(live))).rejects.toThrow("document_image_policy");
|
||||||
|
});
|
||||||
73
tests/project-jobs.test.ts
Normal file
73
tests/project-jobs.test.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import { expect, test } from "bun:test";
|
||||||
|
import { execFile, spawn } from "node:child_process";
|
||||||
|
import { once } from "node:events";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join, resolve } from "node:path";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
|
||||||
|
const exec = promisify(execFile);
|
||||||
|
|
||||||
|
test("the saved project job survives termination of its launching process", async () => {
|
||||||
|
const temporary = await fs.mkdtemp(join(tmpdir(), "velum-worker-test-"));
|
||||||
|
const launcher = join(temporary, "launcher.cjs");
|
||||||
|
const assets = join(temporary, "assets");
|
||||||
|
const support = join(temporary, "support");
|
||||||
|
const root = join(temporary, "project");
|
||||||
|
await fs.mkdir(assets);
|
||||||
|
const runtime = resolve("src/lib/worker-runtime.ts");
|
||||||
|
const jobs = resolve("src/lib/project-jobs.ts");
|
||||||
|
let parent: ReturnType<typeof spawn> | undefined;
|
||||||
|
try {
|
||||||
|
await fs.writeFile(join(assets, "velum-project-worker.cjs"), `
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const path = require("node:path");
|
||||||
|
process.stdin.resume();
|
||||||
|
process.stdin.once("end", () => setTimeout(() => {
|
||||||
|
fs.writeFileSync(path.join(process.argv[2], "state.json"), JSON.stringify({ phase: "review" }), { mode: 0o600 });
|
||||||
|
}, 400));
|
||||||
|
`);
|
||||||
|
const entry = join(temporary, "launcher.ts");
|
||||||
|
await fs.writeFile(entry, `
|
||||||
|
import { configureWorker } from ${JSON.stringify(runtime)};
|
||||||
|
import { projectJobDirectory, startProjectAnalysis } from ${JSON.stringify(jobs)};
|
||||||
|
configureWorker({
|
||||||
|
assets: ${JSON.stringify(assets)}, support: ${JSON.stringify(support)},
|
||||||
|
preferences: { velumBaseUrl: "https://example.invalid", authentikTokenUrl: "https://example.invalid/token",
|
||||||
|
clientId: "test", serviceAccountUsername: "test", serviceAccountPassword: "synthetic-secret" },
|
||||||
|
});
|
||||||
|
const root = ${JSON.stringify(root)};
|
||||||
|
startProjectAnalysis({ root, files: [], rules: [], whitelist: [], entityTypes: ["PERSON"], skipped: [],
|
||||||
|
reanalyzeUnchanged: false, imagePolicy: "placeholder", fileSelectionChanged: false }).then(() => {
|
||||||
|
console.log(projectJobDirectory(root));
|
||||||
|
setInterval(() => {}, 1_000);
|
||||||
|
});
|
||||||
|
`);
|
||||||
|
await exec(resolve("node_modules/.bin/esbuild"), [entry, "--bundle", "--platform=node",
|
||||||
|
`--alias:@raycast/api=${runtime}`, `--outfile=${launcher}`]);
|
||||||
|
const child = spawn(process.execPath, [launcher], { stdio: ["ignore", "pipe", "inherit"] });
|
||||||
|
parent = child;
|
||||||
|
const terminated = once(child, "exit");
|
||||||
|
const [pending] = await Promise.race([
|
||||||
|
once(child.stdout, "data"),
|
||||||
|
terminated.then(() => { throw new Error("Projektauftrag konnte nicht gestartet werden."); }),
|
||||||
|
]);
|
||||||
|
const directory = String(pending).trim();
|
||||||
|
child.kill("SIGKILL");
|
||||||
|
await terminated;
|
||||||
|
const state = join(directory, "state.json");
|
||||||
|
let phase: string | undefined;
|
||||||
|
for (let attempt = 0; attempt < 50; attempt++) {
|
||||||
|
phase = JSON.parse(await fs.readFile(state, "utf8")).phase;
|
||||||
|
if (phase === "review") break;
|
||||||
|
await new Promise((done) => setTimeout(done, 40));
|
||||||
|
}
|
||||||
|
expect(phase).toBe("review");
|
||||||
|
const input = join(directory, "input.json");
|
||||||
|
expect(await fs.readFile(input, "utf8")).not.toContain("synthetic-secret");
|
||||||
|
expect((await fs.stat(input)).mode & 0o777).toBe(0o600);
|
||||||
|
} finally {
|
||||||
|
parent?.kill();
|
||||||
|
await fs.rm(temporary, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
136
tests/project-review.test.ts
Normal file
136
tests/project-review.test.ts
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import {
|
||||||
|
canonicalPerson, filenameScanText, groupReviewHits, highlightedReviewContext, literalReviewContext, makeTextBatches, mappingForSelection,
|
||||||
|
mergePeople, reconcileDocumentHitIds, spansBySegment, textHitContexts, withoutPlaceholderHits, withoutWhitelistedHits,
|
||||||
|
withoutWhitelistedRules,
|
||||||
|
} from "../src/lib/project-review";
|
||||||
|
|
||||||
|
it("liest Unterstriche in Namen als Leerzeichen und bewahrt bekannte Codebegriffe", () => {
|
||||||
|
expect(filenameScanText("Max_Mustermann_Abgabe", []))
|
||||||
|
.toBe("Max Mustermann Abgabe");
|
||||||
|
expect(filenameScanText("Max_Mustermann_KundenSuite_X", ["KundenSuite_X"]))
|
||||||
|
.toBe("Max Mustermann KundenSuite_X");
|
||||||
|
expect(filenameScanText("😀_Max_Mustermann", []))
|
||||||
|
.toBe("😀 Max Mustermann");
|
||||||
|
expect(filenameScanText("PERSON_01_Max_Mustermann", ["PERSON_01"]))
|
||||||
|
.toBe("PERSON_01 Max Mustermann");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ordnet gebündelte API-Treffer nach Unicode-Positionen den richtigen Dateien zu", () => {
|
||||||
|
const [batch] = makeTextBatches([
|
||||||
|
{ key: "eins.txt", text: "😀 Max" },
|
||||||
|
{ key: "zwei.txt", text: "Max und Max" },
|
||||||
|
]);
|
||||||
|
expect(batch.segments).toHaveLength(2);
|
||||||
|
const second = batch.segments[1];
|
||||||
|
const spans = spansBySegment(batch, [
|
||||||
|
{ start: 2, end: 5, original: "Max" },
|
||||||
|
{ start: second.start, end: second.start + 3, original: "Max" },
|
||||||
|
{ start: batch.segments[0].end, end: second.start + 1, original: "Grenztreffer" },
|
||||||
|
]);
|
||||||
|
expect(spans.get("eins.txt")).toEqual([{ start: 2, end: 5, original: "Max" }]);
|
||||||
|
expect(spans.get("zwei.txt")).toEqual([{ start: 0, end: 3, original: "Max" }]);
|
||||||
|
expect(makeTextBatches([{ key: "a", text: "abc" }, { key: "b", text: "def" }], 5)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("zeigt gleiche Zuordnungen einmal mit der Anzahl ihrer Vorkommen", () => {
|
||||||
|
const hits = [
|
||||||
|
{ id: "a", type: "PERSON", original: "Max", placeholder: "PERSON_01", file: "a.txt" },
|
||||||
|
{ id: "b", type: "PERSON", original: "Max", placeholder: "PERSON_01", file: "b.txt" },
|
||||||
|
{ id: "c", type: "PERSON", original: "Max", placeholder: "PERSON_02", file: "c.txt" },
|
||||||
|
{ id: "d", type: "ORT", original: "Max", placeholder: "ORT_01", file: "a.txt" },
|
||||||
|
];
|
||||||
|
const groups = groupReviewHits(hits);
|
||||||
|
expect(groups).toHaveLength(3);
|
||||||
|
expect(groups.find((group) => group.placeholder === "PERSON_01")?.hits).toHaveLength(2);
|
||||||
|
expect(groups.find((group) => group.placeholder === "PERSON_01")?.hits.map((hit) => hit.id)).toEqual(["a", "b"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ordnet E-Mail-Vorkommen nach Unicode-Position zu und markiert jeweils genau den ausgewählten Treffer", () => {
|
||||||
|
const [signature, sender, recipient] = textHitContexts("😀 Von: Max\nAn: Mia\nDanke, Max", [
|
||||||
|
{ start: 26, end: 29 }, { start: 7, end: 10 }, { start: 15, end: 18 },
|
||||||
|
]);
|
||||||
|
const max = String.raw`\(\textcolor{#dc2626}{\text{Max}}\)`;
|
||||||
|
const mia = String.raw`\(\textcolor{#dc2626}{\text{Mia}}\)`;
|
||||||
|
expect(signature).toContain("**Zeile 3**");
|
||||||
|
expect(signature).toContain(`Danke, ${max}`);
|
||||||
|
expect(sender).toContain("**Zeile 1**");
|
||||||
|
expect(sender).toContain(`😀 Von: ${max}`);
|
||||||
|
expect(recipient).toContain("**Zeile 2**");
|
||||||
|
expect(recipient).toContain(`An: ${mia}`);
|
||||||
|
const source = ["**Von:** <max@example.com>", "```", ""].join("\n");
|
||||||
|
expect(literalReviewContext(source)).toBe(["````", source, "````"].join("\n"));
|
||||||
|
expect(highlightedReviewContext("😀 Max, Max", 8, 3)).toBe(`😀 Max, ${max}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("zeigt Markdown-Sonderzeichen wörtlich und färbt mehrzeilige Treffer an ihrer Fundstelle", () => {
|
||||||
|
const before = "\n";
|
||||||
|
const match = String.raw`A\){#}&` + "\nB_20%";
|
||||||
|
const context = highlightedReviewContext(before + match, before.length, match.length);
|
||||||
|
expect(context).not.toContain("![");
|
||||||
|
expect(context).toContain(String.raw`\text{A\textbackslash{})\{\#\}\&}`);
|
||||||
|
expect(context).toContain(String.raw`\text{B\_20\%}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ordnet bestätigte Dokumenttreffer nach einem 409 nur bei identischem Vorkommen neu zu", () => {
|
||||||
|
const hit = { id: "alt", source: "Absatz 1", start: 4, end: 7, type: "PERSON",
|
||||||
|
original: "Max", context: "Herr Max antwortet" };
|
||||||
|
expect(reconcileDocumentHitIds([hit], ["alt"], [{ ...hit, id: "neu" }])).toEqual(["neu"]);
|
||||||
|
expect(reconcileDocumentHitIds([hit], ["alt"], [{ ...hit, id: "neu", original: "Mia" }])).toBeNull();
|
||||||
|
expect(reconcileDocumentHitIds([hit], ["alt"], [{ ...hit, id: "neu", start: 5 }])).toBeNull();
|
||||||
|
const duplicate = { ...hit, id: "alt2" };
|
||||||
|
expect(reconcileDocumentHitIds([hit, duplicate], ["alt"],
|
||||||
|
[{ ...hit, id: "neu" }, { ...duplicate, id: "neu2" }])).toBeNull();
|
||||||
|
expect(reconcileDocumentHitIds([hit, duplicate], ["alt", "alt2"],
|
||||||
|
[{ ...hit, id: "neu" }, { ...duplicate, id: "neu2" }])).toEqual(["neu", "neu2"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unterdrückt projektweit nur exakt abgewählte Begriffe samt erzwungener Regel", () => {
|
||||||
|
const whitelist = [{ type: "PERSON", original: " Max Muster " }];
|
||||||
|
const hits = [
|
||||||
|
{ id: "1", type: "PERSON", original: "max muster", placeholder: "PERSON_01" },
|
||||||
|
{ id: "2", type: "ORG", original: "Max Muster", placeholder: "ORG_01" },
|
||||||
|
{ id: "3", type: "PERSON", original: "Max Mustermann", placeholder: "PERSON_02" },
|
||||||
|
];
|
||||||
|
expect(withoutWhitelistedHits(hits, whitelist).map((hit) => hit.id)).toEqual(["2", "3"]);
|
||||||
|
expect(withoutWhitelistedRules([
|
||||||
|
{ type: "PERSON", value: "Max Muster" }, { type: "ORG", value: "Max Muster" },
|
||||||
|
], whitelist)).toEqual([{ type: "ORG", value: "Max Muster" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("zeigt beim erneuten Lauf keine Treffer, die einen bestehenden Platzhalter einschließen", () => {
|
||||||
|
const hits = [
|
||||||
|
{ type: "PERSON", original: "PERSON_39, Roman" },
|
||||||
|
{ type: "KUNDE", original: "KUNDE_100005" },
|
||||||
|
{ type: "PERSON", original: "Roman" },
|
||||||
|
{ type: "PERSON", original: "Anlage44" },
|
||||||
|
{ type: "PASSWORT", original: "ORT_08!" },
|
||||||
|
];
|
||||||
|
expect(withoutPlaceholderHits(hits)).toEqual(hits.slice(2));
|
||||||
|
expect(withoutPlaceholderHits([
|
||||||
|
{ type: "PERSON", original: "KUNDE_100005Service" },
|
||||||
|
{ type: "PERSON", original: "Roman" },
|
||||||
|
], ["KUNDE_100005"])).toEqual([{ type: "PERSON", original: "Roman" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("fasst ausgewählte Personen zu einem kanonischen Platzhalter zusammen und bewahrt alte Zuordnungen", () => {
|
||||||
|
let merges = mergePeople({}, "PERSON_02", "PERSON_01");
|
||||||
|
merges = mergePeople(merges, "PERSON_03", "PERSON_02");
|
||||||
|
expect(canonicalPerson("PERSON_03", merges)).toBe("PERSON_01");
|
||||||
|
const previous = { PERSON_09: { original: "Alt", type: "PERSON" } };
|
||||||
|
const preview = {
|
||||||
|
...previous,
|
||||||
|
PERSON_01: { original: "Franz Fuchs", type: "PERSON" },
|
||||||
|
PERSON_02: { original: "Franz", type: "PERSON" },
|
||||||
|
PERSON_03: { original: "Hr. Fuchs", type: "PERSON" },
|
||||||
|
PERSON_04: { original: "Fehlalarm", type: "PERSON" },
|
||||||
|
};
|
||||||
|
const accepted = ["PERSON_01", "PERSON_02", "PERSON_03"].map((placeholder) => ({
|
||||||
|
id: placeholder, type: "PERSON", original: preview[placeholder as keyof typeof preview].original, placeholder,
|
||||||
|
}));
|
||||||
|
const mapping = mappingForSelection(preview, previous, accepted, merges);
|
||||||
|
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
|
||||||
|
expect(mapping.PERSON_03.merged_into).toBe("PERSON_01");
|
||||||
|
expect(mapping.PERSON_09.original).toBe("Alt");
|
||||||
|
expect(mapping.PERSON_04).toBeUndefined();
|
||||||
|
});
|
||||||
284
tests/project-revision.test.ts
Normal file
284
tests/project-revision.test.ts
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
import { afterEach, describe, expect, it, mock } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() },
|
||||||
|
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
|
||||||
|
LocalStorage: {}, getPreferenceValues: () => ({}) }));
|
||||||
|
const project = await import("../src/lib/velum-project");
|
||||||
|
const revision = await import("../src/lib/project-revision");
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); });
|
||||||
|
|
||||||
|
describe("Nachbearbeitung von Projektständen", () => {
|
||||||
|
it("gibt eine Person frei und führt zwei andere nachträglich zusammen", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-revision-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.mapping = {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Falsch Positiv" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_03: { type: "PERSON", original: "Hr. Fuchs" },
|
||||||
|
PERSON_04: { type: "PERSON", original: "Franz F." },
|
||||||
|
};
|
||||||
|
saved.run.entityTypes = ["PERSON", "EMAIL"];
|
||||||
|
saved.run.files = [{ source: "Bericht.txt", output: "PERSON_01-PERSON_03.txt", kind: "text" }];
|
||||||
|
saved.run.sourceState = { "Bericht.txt": { hash: "synthetic-hash", output: "PERSON_01-PERSON_03.txt" } };
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "PERSON_01-PERSON_03.txt"),
|
||||||
|
"PERSON_01 traf PERSON_02 und PERSON_03. PERSON_04 blieb.");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const result = await revision.reviseProjectRun({
|
||||||
|
previous: saved.run, previousDirectory: saved.directory, support,
|
||||||
|
release: new Set(["PERSON_01"]), merges: { PERSON_03: "PERSON_02", PERSON_04: "PERSON_02" },
|
||||||
|
rewriteDocument: async () => { throw new Error("Unerwartetes Office-Dokument"); },
|
||||||
|
});
|
||||||
|
expect(result.run.files[0].output).toBe("Falsch Positiv-PERSON_02.txt");
|
||||||
|
expect(result.run.sourceState?.["Bericht.txt"]).toEqual({
|
||||||
|
hash: "synthetic-hash", output: "Falsch Positiv-PERSON_02.txt",
|
||||||
|
});
|
||||||
|
expect(await fs.readFile(join(result.directory, "files", result.run.files[0].output), "utf8"))
|
||||||
|
.toBe("Falsch Positiv traf PERSON_02 und PERSON_02. PERSON_02 blieb.");
|
||||||
|
expect(result.run.copyPath?.startsWith(join(root, "Quelle-Velum-"))).toBe(true);
|
||||||
|
expect(await fs.readFile(join(result.run.copyPath!, result.run.files[0].output), "utf8"))
|
||||||
|
.toBe("Falsch Positiv traf PERSON_02 und PERSON_02. PERSON_02 blieb.");
|
||||||
|
expect(result.run.mapping.PERSON_03.merged_into).toBe("PERSON_02");
|
||||||
|
expect(result.run.mapping.PERSON_04.merged_into).toBe("PERSON_02");
|
||||||
|
expect(result.run.mapping.PERSON_01).toBeUndefined();
|
||||||
|
expect(result.run.entityTypes).toEqual(["PERSON", "EMAIL"]);
|
||||||
|
expect(await project.loadProjectWhitelist(source, support))
|
||||||
|
.toEqual([{ type: "PERSON", original: "Falsch Positiv" }]);
|
||||||
|
expect(await fs.readFile(join(saved.directory, "files", "PERSON_01-PERSON_03.txt"), "utf8"))
|
||||||
|
.toContain("PERSON_03");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("gibt eine konsolidierte Person samt Varianten frei", () => {
|
||||||
|
const plan = revision.planProjectRevision({
|
||||||
|
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Franz F.", merged_into: "PERSON_01" },
|
||||||
|
PERSON_03: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
|
||||||
|
}, new Set(["PERSON_01"]), {});
|
||||||
|
expect(plan.released).toEqual(["PERSON_01", "PERSON_02", "PERSON_03"]);
|
||||||
|
expect(plan.whitelist.map((item) => item.original)).toEqual(["Franz Fuchs", "Franz F.", "Hr. Fuchs"]);
|
||||||
|
expect(plan.mapping).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("gibt auch gruppierte Begriffe samt Verweisen frei und verwendet den Hauptbegriff", () => {
|
||||||
|
const plan = revision.planProjectRevision({
|
||||||
|
BEGRIFF_01: { type: "BEGRIFF", original: "Kundensoftware" },
|
||||||
|
BEGRIFF_02: { type: "BEGRIFF", original: "Kunden-App", merged_into: "BEGRIFF_01" },
|
||||||
|
}, new Set(["BEGRIFF_02"]), {});
|
||||||
|
expect(plan.released).toEqual(["BEGRIFF_01", "BEGRIFF_02"]);
|
||||||
|
expect(plan.replacements.BEGRIFF_02.original).toBe("Kundensoftware");
|
||||||
|
expect(plan.mapping).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("repariert bereits gespeicherte Personen-Zusammenführungen in Inhalt und Dateiname", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-merge-repair-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.mapping = {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
|
||||||
|
};
|
||||||
|
saved.run.files = [{ source: "Bericht.md", output: "PERSON_02_Notiz.md", kind: "text" }];
|
||||||
|
expect(revision.planProjectRevision(saved.run.mapping, new Set(), {}).replacements)
|
||||||
|
.toEqual({ PERSON_02: { original: "PERSON_01", type: "PERSON" } });
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "PERSON_02_Notiz.md"),
|
||||||
|
"Kommentar PERSON_02 und `PERSON_02_Entwurf.docx`; PERSON_020 bleibt unberührt.");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const result = await revision.reviseProjectRun({
|
||||||
|
previous: saved.run, previousDirectory: saved.directory, support,
|
||||||
|
release: new Set(), merges: {}, reapplyMerges: true,
|
||||||
|
rewriteDocument: async () => { throw new Error("Unerwartetes Office-Dokument"); },
|
||||||
|
});
|
||||||
|
expect(result.run.mapping.PERSON_02.merged_into).toBe("PERSON_01");
|
||||||
|
expect(result.run.files[0].output).toBe("PERSON_01_Notiz.md");
|
||||||
|
expect(await fs.readFile(join(result.directory, "files", "PERSON_01_Notiz.md"), "utf8"))
|
||||||
|
.toBe("Kommentar PERSON_01 und `PERSON_01_Entwurf.docx`; PERSON_020 bleibt unberührt.");
|
||||||
|
expect(await fs.readFile(join(saved.directory, "files", "PERSON_02_Notiz.md"), "utf8"))
|
||||||
|
.toContain("PERSON_02_Entwurf.docx");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ersetzt einen vorhandenen Projektordner nur, wenn er noch dem letzten Stand entspricht", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-revision-place-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.mapping = { PERSON_01: { type: "PERSON", original: "Falscher Treffer" } };
|
||||||
|
saved.run.files = [{ source: "Notiz.txt", output: "PERSON_01.txt", kind: "text" }];
|
||||||
|
saved.run.inPlace = true;
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "PERSON_01.txt"), "PERSON_01");
|
||||||
|
await fs.writeFile(join(source, "PERSON_01.txt"), "PERSON_01");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
await fs.writeFile(join(source, "PERSON_01.txt"), "PERSON_01 mit lokaler Änderung");
|
||||||
|
await expect(revision.reviseProjectRun({ previous: saved.run, previousDirectory: saved.directory,
|
||||||
|
release: new Set(["PERSON_01"]), merges: {}, support,
|
||||||
|
rewriteDocument: async () => { throw new Error("Unerwartetes Office-Dokument"); },
|
||||||
|
})).rejects.toThrow("seit dem letzten Stand geändert");
|
||||||
|
expect((await project.listRuns(source, support)).length).toBe(1);
|
||||||
|
expect(await fs.readFile(join(source, "PERSON_01.txt"), "utf8"))
|
||||||
|
.toBe("PERSON_01 mit lokaler Änderung");
|
||||||
|
await fs.writeFile(join(source, "PERSON_01.txt"), "PERSON_01");
|
||||||
|
const result = await revision.reviseProjectRun({ previous: saved.run, previousDirectory: saved.directory,
|
||||||
|
release: new Set(["PERSON_01"]), merges: {}, support,
|
||||||
|
rewriteDocument: async () => { throw new Error("Unerwartetes Office-Dokument"); },
|
||||||
|
});
|
||||||
|
expect(await fs.readFile(join(source, "Falscher Treffer.txt"), "utf8")).toBe("Falscher Treffer");
|
||||||
|
expect(await fs.readFile(join(result.directory, "backup", "PERSON_01.txt"), "utf8")).toBe("PERSON_01");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("gibt einen Treffer in einer inzwischen bearbeiteten Projektdatei frei und bewahrt die Bearbeitung", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-revision-current-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.mapping = {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Fachbegriff" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Echte Person" },
|
||||||
|
};
|
||||||
|
saved.run.files = [{ source: "Notiz.md", output: "PERSON_01.md", kind: "text" }];
|
||||||
|
saved.run.inPlace = true;
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "PERSON_01.md"), "PERSON_01 und PERSON_02");
|
||||||
|
await fs.writeFile(join(source, "PERSON_01.md"), "PERSON_01 und PERSON_02; später ergänzt");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const result = await revision.reviseProjectRun({ previous: saved.run, previousDirectory: saved.directory,
|
||||||
|
release: new Set(["PERSON_01"]), merges: {}, support, useCurrentInPlaceFiles: true,
|
||||||
|
rewriteDocument: async () => { throw new Error("Unerwartetes Office-Dokument"); },
|
||||||
|
});
|
||||||
|
expect(await fs.readFile(join(source, "Fachbegriff.md"), "utf8"))
|
||||||
|
.toBe("Fachbegriff und PERSON_02; später ergänzt");
|
||||||
|
expect(result.run.sourceState?.["Fachbegriff.md"]).toEqual({
|
||||||
|
hash: project.digest(Buffer.from("Fachbegriff und PERSON_02; später ergänzt")),
|
||||||
|
output: "Fachbegriff.md",
|
||||||
|
});
|
||||||
|
expect(await fs.readFile(join(result.directory, "backup", "PERSON_01.md"), "utf8"))
|
||||||
|
.toBe("PERSON_01 und PERSON_02; später ergänzt");
|
||||||
|
expect(await fs.readFile(join(saved.directory, "files", "PERSON_01.md"), "utf8"))
|
||||||
|
.toBe("PERSON_01 und PERSON_02");
|
||||||
|
expect(result.run.mapping.PERSON_01).toBeUndefined();
|
||||||
|
expect(await project.loadProjectWhitelist(source, support))
|
||||||
|
.toEqual([{ type: "PERSON", original: "Fachbegriff" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bricht die Freigabe ab, wenn die aktuelle Datei während der Korrektur weiterbearbeitet wird", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-revision-race-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.mapping = { PERSON_01: { type: "PERSON", original: "Fachbegriff" } };
|
||||||
|
saved.run.files = [{ source: "Bericht.docx", output: "Bericht.docx", kind: "document" }];
|
||||||
|
saved.run.inPlace = true;
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "Bericht.docx"), "älterer Stand");
|
||||||
|
await fs.writeFile(join(source, "Bericht.docx"), "aktueller Stand");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
await expect(revision.reviseProjectRun({ previous: saved.run, previousDirectory: saved.directory,
|
||||||
|
release: new Set(["PERSON_01"]), merges: {}, support, useCurrentInPlaceFiles: true,
|
||||||
|
rewriteDocument: async () => {
|
||||||
|
await fs.writeFile(join(source, "Bericht.docx"), "nochmals geändert");
|
||||||
|
return Buffer.from("korrigiert");
|
||||||
|
},
|
||||||
|
})).rejects.toThrow("während der Freigabe erneut geändert");
|
||||||
|
expect(await fs.readFile(join(source, "Bericht.docx"), "utf8")).toBe("nochmals geändert");
|
||||||
|
expect(await project.listRuns(source, support)).toHaveLength(1);
|
||||||
|
expect(await project.loadProjectWhitelist(source, support)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("übergibt Office-Dateien mit einer gezielten Ersetzung an die Dokumentfunktion", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-revision-doc-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.mapping = {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Falscher Treffer" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Echte Person" },
|
||||||
|
};
|
||||||
|
saved.run.files = [{ source: "Bericht.docx", output: "Bericht.docx", kind: "document" }];
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "Bericht.docx"), "synthetic office bytes");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
let called = false;
|
||||||
|
const result = await revision.reviseProjectRun({ previous: saved.run, previousDirectory: saved.directory,
|
||||||
|
release: new Set(["PERSON_01"]), merges: {}, support,
|
||||||
|
rewriteDocument: async (filename, data, mapping) => {
|
||||||
|
called = true;
|
||||||
|
expect(filename).toBe("Bericht.docx");
|
||||||
|
expect(data.toString()).toBe("synthetic office bytes");
|
||||||
|
expect(Object.keys(mapping)).toEqual(["PERSON_01"]);
|
||||||
|
return Buffer.from("changed office bytes");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(called).toBe(true);
|
||||||
|
expect(await fs.readFile(join(result.directory, "files", "Bericht.docx"), "utf8"))
|
||||||
|
.toBe("changed office bytes");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("übergibt eine ältere Personen-Zusammenführung erneut an die Office-Wiederherstellung", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-merge-doc-repair-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.mapping = {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
|
||||||
|
};
|
||||||
|
saved.run.files = [{ source: "Bericht.docx", output: "PERSON_02_Bericht.docx", kind: "document" }];
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "PERSON_02_Bericht.docx"), "synthetic office bytes");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const result = await revision.reviseProjectRun({
|
||||||
|
previous: saved.run, previousDirectory: saved.directory, support,
|
||||||
|
release: new Set(), merges: {}, reapplyMerges: true,
|
||||||
|
rewriteDocument: async (filename, data, mapping) => {
|
||||||
|
expect(filename).toBe("PERSON_02_Bericht.docx");
|
||||||
|
expect(data.toString()).toBe("synthetic office bytes");
|
||||||
|
expect(mapping).toEqual({ PERSON_02: { original: "PERSON_01", type: "PERSON" } });
|
||||||
|
return Buffer.from("rewritten office bytes");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(result.run.files[0].output).toBe("PERSON_01_Bericht.docx");
|
||||||
|
expect(await fs.readFile(join(result.directory, "files", "PERSON_01_Bericht.docx"), "utf8"))
|
||||||
|
.toBe("rewritten office bytes");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("schützt längere importierte Platzhalter beim Freigeben eines Präfixes", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-revision-prefix-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, support);
|
||||||
|
saved.run.origin = "imported";
|
||||||
|
saved.run.mapping = {
|
||||||
|
BEGRIFF_100001: { type: "BEGRIFF", original: "Alpha" },
|
||||||
|
BEGRIFF_1000012: { type: "BEGRIFF", original: "Beta" },
|
||||||
|
};
|
||||||
|
saved.run.matchModes = { BEGRIFF_100001: "anywhere", BEGRIFF_1000012: "anywhere" };
|
||||||
|
saved.run.files = [{ source: "Code.txt", output: "BEGRIFF_1000012.txt", kind: "text" }];
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "BEGRIFF_1000012.txt"),
|
||||||
|
"xBEGRIFF_1000012 und xBEGRIFF_100001");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const result = await revision.reviseProjectRun({ previous: saved.run, previousDirectory: saved.directory,
|
||||||
|
release: new Set(["BEGRIFF_100001"]), merges: {}, support,
|
||||||
|
rewriteDocument: async () => { throw new Error("Unerwartetes Office-Dokument"); },
|
||||||
|
});
|
||||||
|
expect(result.run.origin).toBe("imported");
|
||||||
|
expect(result.run.files[0].output).toBe("BEGRIFF_1000012.txt");
|
||||||
|
expect(await fs.readFile(join(result.directory, "files", result.run.files[0].output), "utf8"))
|
||||||
|
.toBe("xBEGRIFF_1000012 und xAlpha");
|
||||||
|
});
|
||||||
|
});
|
||||||
78
tests/project-text-large.test.ts
Normal file
78
tests/project-text-large.test.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { analyzeProjectTextFiles } from "../src/lib/project-analysis";
|
||||||
|
import { projectTextAnalyzer } from "../src/lib/project-text-mapping";
|
||||||
|
import { hashProjectFile, writeReplacedTextFile } from "../src/lib/project-text-stream";
|
||||||
|
|
||||||
|
it("processes 27 MiB with over 50000 occurrences and over 5000 identities without changing unselected bytes", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-dense-"));
|
||||||
|
try {
|
||||||
|
const source = join(root, "27MiB.txt"), target = join(root, "masked.txt");
|
||||||
|
const handle = await fs.open(source, "w");
|
||||||
|
let bytes = 0, rows = 0;
|
||||||
|
const expected = createHash("sha256");
|
||||||
|
while (bytes < 27 * 1024 * 1024) {
|
||||||
|
let block = "";
|
||||||
|
for (let i = 0; i < 500; i++, rows++) {
|
||||||
|
const original = `customer${rows % 10_000}@example.invalid`;
|
||||||
|
const row = `😀 Max Mustermann; ${original}; 08.11.2026; ${"Protokolltext ".repeat(14)}\r\n`;
|
||||||
|
block += row;
|
||||||
|
// Only the first name is selected; every other byte must survive.
|
||||||
|
expected.update(row.replace("Max Mustermann", "PERSON_01"));
|
||||||
|
}
|
||||||
|
bytes += Buffer.byteLength(block);
|
||||||
|
await handle.writeFile(block);
|
||||||
|
}
|
||||||
|
await handle.close();
|
||||||
|
const hash = await hashProjectFile(source);
|
||||||
|
let requests = 0, maxRequestMapping = 0;
|
||||||
|
const analyze = projectTextAnalyzer({}, async (text, mapping, types) => {
|
||||||
|
requests++;
|
||||||
|
maxRequestMapping = Math.max(maxRequestMapping, Object.keys(mapping).length);
|
||||||
|
const responseMapping: Record<string, { original: string; type: string }> = {};
|
||||||
|
const local = new Map<string, string>(), counters: Record<string, number> = {};
|
||||||
|
const spans = [];
|
||||||
|
let previous = 0, position = 0;
|
||||||
|
for (const match of text.matchAll(/Max Mustermann|customer\d+@example\.invalid|08\.11\.2026/g)) {
|
||||||
|
const type = match[0] === "Max Mustermann" ? "PERSON" : match[0].includes("@") ? "EMAIL" : "DATUM";
|
||||||
|
let placeholder = local.get(match[0]);
|
||||||
|
if (!placeholder) {
|
||||||
|
counters[type] = (counters[type] ?? 0) + 1;
|
||||||
|
placeholder = `${type}_${String(counters[type]).padStart(2, "0")}`;
|
||||||
|
local.set(match[0], placeholder);
|
||||||
|
responseMapping[placeholder] = { original: match[0], type };
|
||||||
|
}
|
||||||
|
position += Array.from(text.slice(previous, match.index)).length;
|
||||||
|
previous = match.index;
|
||||||
|
const start = position;
|
||||||
|
spans.push({ start, end: start + match[0].length, original: match[0], type, placeholder, score: 1 });
|
||||||
|
}
|
||||||
|
return JSON.parse(JSON.stringify({ pseudonymized_text: text, selected_entity_types: types,
|
||||||
|
mapping: responseMapping, spans, entity_count: local.size }));
|
||||||
|
});
|
||||||
|
const result = await analyzeProjectTextFiles([{ key: "large.txt", path: source }], {},
|
||||||
|
["PERSON", "EMAIL", "DATUM"], {}, analyze, () => undefined);
|
||||||
|
const spans = result.spansByFile.get("large.txt")!;
|
||||||
|
if (spans.length !== rows * 3) throw Error(`Lost hits: ${spans.length}/${rows * 3}`);
|
||||||
|
if (Object.keys(result.mapping).length !== 10_002) throw Error("Lost project mapping");
|
||||||
|
if (maxRequestMapping > 5000) throw Error("API mapping limit exceeded");
|
||||||
|
const accepted = new Set<string>();
|
||||||
|
const selected = spans.filter((span) => span.type === "PERSON").map((span, index) => {
|
||||||
|
const id = String(index); accepted.add(id);
|
||||||
|
if (span.placeholder !== "PERSON_01") throw Error("Unstable person placeholder");
|
||||||
|
return { ...span, id };
|
||||||
|
});
|
||||||
|
const output = await writeReplacedTextFile(source, target, selected, accepted, hash);
|
||||||
|
if (output !== expected.digest("hex")) throw Error("Output bytes do not match approved replacements");
|
||||||
|
if (await hashProjectFile(source) !== hash) throw Error("Original modified");
|
||||||
|
expect(bytes).toBeGreaterThanOrEqual(27 * 1024 * 1024);
|
||||||
|
expect(spans.length).toBeGreaterThan(50_000);
|
||||||
|
expect(maxRequestMapping).toBeLessThanOrEqual(5000);
|
||||||
|
expect(requests).toBeGreaterThan(1000);
|
||||||
|
|
||||||
|
} finally { await fs.rm(root, { recursive: true, force: true }); }
|
||||||
|
|
||||||
|
}, 30_000);
|
||||||
82
tests/project-text-mapping.test.ts
Normal file
82
tests/project-text-mapping.test.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import { expect, it } from "bun:test";
|
||||||
|
import { projectTextAnalyzer } from "../src/lib/project-text-mapping";
|
||||||
|
import type { PlaceholderMapping } from "../src/types";
|
||||||
|
|
||||||
|
it("keeps more than 5000 project identities without sending historical NER mappings", async () => {
|
||||||
|
const previous: PlaceholderMapping = {};
|
||||||
|
for (let i = 1; i <= 6000; i++) previous[`PERSON_${i}`] = { original: `Person ${i}`, type: "PERSON" };
|
||||||
|
const analyze = projectTextAnalyzer(previous, async (text, mapping) => {
|
||||||
|
expect(Object.keys(mapping)).toHaveLength(0);
|
||||||
|
return { pseudonymized_text: "PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
|
||||||
|
mapping: { PERSON_01: { original: text, type: "PERSON" } },
|
||||||
|
spans: [{ start: 0, end: [...text].length, original: text, placeholder: "PERSON_01", type: "PERSON", score: 1 }] };
|
||||||
|
});
|
||||||
|
const first = await analyze("Anna Berger", previous, ["PERSON"], {});
|
||||||
|
expect(first.spans[0].placeholder).toBe("PERSON_6001");
|
||||||
|
const repeat = await analyze("Anna Berger", first.mapping, ["PERSON"], {});
|
||||||
|
expect(repeat.spans[0].placeholder).toBe("PERSON_6001");
|
||||||
|
const known = await analyze("Person 4321", repeat.mapping, ["PERSON"], {});
|
||||||
|
expect(known.spans[0].placeholder).toBe("PERSON_4321");
|
||||||
|
expect(Object.keys(known.mapping)).toHaveLength(6001);
|
||||||
|
expect(Object.keys(previous)).toHaveLength(6000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves custom terms and complete manual alias dependencies", async () => {
|
||||||
|
const previous: PlaceholderMapping = {
|
||||||
|
PERSON_90: { original: "Anna Berger", type: "PERSON" },
|
||||||
|
PERSON_91: { original: "Anna", type: "PERSON", merged_into: "PERSON_90" },
|
||||||
|
BEGRIFF_07: { original: "/CLIENT/ABC", type: "BEGRIFF" },
|
||||||
|
BEGRIFF_08: { original: "Other project", type: "BEGRIFF" },
|
||||||
|
};
|
||||||
|
const analyze = projectTextAnalyzer(previous, async (text, mapping, types) => {
|
||||||
|
expect(Object.keys(mapping).sort()).toEqual(["BEGRIFF_07", "PERSON_90", "PERSON_91"]);
|
||||||
|
return { pseudonymized_text: text, selected_entity_types: types, entity_count: 3, mapping,
|
||||||
|
spans: [{ start: 0, end: 4, original: "Anna", placeholder: "PERSON_90", type: "PERSON", score: 1 }] };
|
||||||
|
});
|
||||||
|
const result = await analyze("Anna nutzt /CLIENT/ABC", previous, ["PERSON", "BEGRIFF"], {});
|
||||||
|
expect(result.pseudonymized_text).toBe("PERSON_90 nutzt /CLIENT/ABC");
|
||||||
|
expect(result.mapping.PERSON_91.merged_into).toBe("PERSON_90");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves literal placeholders alone and rebuilds Unicode output from positions", async () => {
|
||||||
|
const previous = { PERSON_12: { original: "Berta", type: "PERSON" } };
|
||||||
|
const text = "😀 PERSON_01 Anna";
|
||||||
|
const analyze = projectTextAnalyzer(previous, async () => ({
|
||||||
|
pseudonymized_text: "😀 PERSON_01 PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
|
||||||
|
mapping: { PERSON_01: { original: "Anna", type: "PERSON" } },
|
||||||
|
spans: [{ start: 12, end: 16, original: "Anna", placeholder: "PERSON_01", type: "PERSON", score: 1 }],
|
||||||
|
}));
|
||||||
|
const result = await analyze(text, previous, ["PERSON"], {});
|
||||||
|
expect(result.pseudonymized_text).toBe("😀 PERSON_01 PERSON_13");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not retry authentication errors or keep results from a failed API call", async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const analyze = projectTextAnalyzer({}, async () => { calls++; throw Error("HTTP 403"); });
|
||||||
|
await expect(analyze("Anna", {}, ["PERSON"], {})).rejects.toThrow("403");
|
||||||
|
expect(calls).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
it("retains mappings added by another phase between text requests", async () => {
|
||||||
|
const analyze = projectTextAnalyzer({}, async (text) => ({
|
||||||
|
pseudonymized_text: "PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
|
||||||
|
mapping: { PERSON_01: { original: text, type: "PERSON" } },
|
||||||
|
spans: [{ start: 0, end: text.length, original: text, placeholder: "PERSON_01", type: "PERSON", score: 1 }],
|
||||||
|
}));
|
||||||
|
const first = await analyze("Anna", {}, ["PERSON"], {});
|
||||||
|
const withDocument = { ...first.mapping, PERSON_02: { original: "Berta", type: "PERSON" } };
|
||||||
|
const next = await analyze("Clara", withDocument, ["PERSON"], {});
|
||||||
|
expect(next.mapping.PERSON_02.original).toBe("Berta");
|
||||||
|
expect(next.spans[0].placeholder).toBe("PERSON_03");
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
it("passes known multiword terms across whitespace and line boundaries", async () => {
|
||||||
|
const previous = { BEGRIFF_01: { original: "Private Term", type: "BEGRIFF" } };
|
||||||
|
const analyze = projectTextAnalyzer(previous, async (text, mapping) => {
|
||||||
|
expect(mapping.BEGRIFF_01.original).toBe("Private Term");
|
||||||
|
return { pseudonymized_text: text, mapping, spans: [], entity_count: 1, selected_entity_types: ["BEGRIFF"] };
|
||||||
|
});
|
||||||
|
await analyze("Private\nTerm", previous, ["BEGRIFF"], {});
|
||||||
|
});
|
||||||
124
tests/project-text-stream.test.ts
Normal file
124
tests/project-text-stream.test.ts
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
import { afterEach, expect, it } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { analyzeProjectTextFiles } from "../src/lib/project-analysis";
|
||||||
|
import { decodedText, fileTextParts, hashProjectFile, inspectTextFile, textLines, writeReplacedTextFile } from "../src/lib/project-text-stream";
|
||||||
|
import type { PlaceholderMapping } from "../src/types";
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
|
||||||
|
async function fixture() { const root = await fs.mkdtemp(join(tmpdir(), "velum-stream-")); roots.push(root); return root; }
|
||||||
|
|
||||||
|
it("trennt vollständige Zeilen und bewahrt CRLF, CR, LF und die letzte Zeile", async () => {
|
||||||
|
async function* chunks() { yield "eins\r"; yield "\nzwei\rdr"; yield "ei\n😀Ende"; }
|
||||||
|
const lines = [];
|
||||||
|
for await (const line of textLines(chunks())) lines.push(line);
|
||||||
|
expect(lines).toEqual(["eins\r\n", "zwei\r", "drei\n", "😀Ende"]);
|
||||||
|
});
|
||||||
|
it("erhält auch bei byteweisen Lesevorgängen BOM, Umlaute und Emoji", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "unicode.txt");
|
||||||
|
await fs.writeFile(source, "\uFEFFÄ😀\r\nEnde");
|
||||||
|
let text = "";
|
||||||
|
for await (const part of decodedText(source, undefined, 1)) text += part;
|
||||||
|
expect(text).toBe("\uFEFFÄ😀\r\nEnde");
|
||||||
|
});
|
||||||
|
it("schneidet weder eine Zeile noch ein Wort an der Paketgrenze durch", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "lines.txt");
|
||||||
|
const text = "\uFEFF" + "Lange Füllzeile mit 😀.\r\n".repeat(800) + "Max Mustermann\r\nletzte Zeile";
|
||||||
|
await fs.writeFile(source, text);
|
||||||
|
let rebuilt = ""; let count = 0;
|
||||||
|
for await (const part of fileTextParts(source)) {
|
||||||
|
const core = text.slice(part.coreStart, part.coreEnd);
|
||||||
|
expect(part.text.slice(part.coreStart - part.scanStart, part.coreEnd - part.scanStart)).toBe(core);
|
||||||
|
if (part.coreEnd < text.length) expect(core.endsWith("\n")).toBe(true);
|
||||||
|
expect(part.text.length).toBeLessThan(24_000);
|
||||||
|
rebuilt += core; count++;
|
||||||
|
}
|
||||||
|
expect(count).toBeGreaterThan(1); expect(rebuilt).toBe(text);
|
||||||
|
});
|
||||||
|
it("analysiert mehr als 20 MiB und fügt nur bestätigte Treffer verlustfrei zur Datei zusammen", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "large.txt"); const target = join(root, "masked.txt");
|
||||||
|
const first = "\uFEFF😀 Max Mustermann\r\n"; const last = "Anna Berger ohne abschließenden Umbruch";
|
||||||
|
const filler = "Text ohne Treffer.\r\n".repeat(26_214);
|
||||||
|
const expected = createHash("sha256").update("\uFEFF😀 PERSON_01\r\n");
|
||||||
|
const handle = await fs.open(source, "w");
|
||||||
|
await handle.writeFile(first);
|
||||||
|
for (let i = 0; i < 64; i++) { await handle.writeFile(filler); expected.update(filler); }
|
||||||
|
await handle.writeFile(last); expected.update(last); await handle.close();
|
||||||
|
expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024);
|
||||||
|
const hash = await inspectTextFile(source);
|
||||||
|
let requests = 0, active = 0, maxActive = 0;
|
||||||
|
const result = await analyzeProjectTextFiles([{ key: "large.txt", path: source }], {}, ["PERSON"], {}, async (text, previous) => {
|
||||||
|
requests++; active++; maxActive = Math.max(maxActive, active);
|
||||||
|
expect(text.length).toBeLessThanOrEqual(24_000);
|
||||||
|
await Promise.resolve();
|
||||||
|
const mapping: PlaceholderMapping = { ...previous };
|
||||||
|
const spans = [...text.matchAll(/Max Mustermann|Anna Berger/g)].map((match) => {
|
||||||
|
const placeholder = match[0] === "Max Mustermann" ? "PERSON_01" : "PERSON_02";
|
||||||
|
mapping[placeholder] = { original: match[0], type: "PERSON" };
|
||||||
|
const start = [...text.slice(0, match.index)].length;
|
||||||
|
return { start, end: start + match[0].length, original: match[0], placeholder, type: "PERSON", score: 1 };
|
||||||
|
});
|
||||||
|
active--;
|
||||||
|
return { pseudonymized_text: text, mapping, spans, entity_count: Object.keys(mapping).length, selected_entity_types: ["PERSON"] };
|
||||||
|
}, () => undefined);
|
||||||
|
const spans = result.spansByFile.get("large.txt")!.map((span, i) => ({ ...span, id: String(i) }));
|
||||||
|
expect(spans.map((span) => span.original)).toEqual(["Max Mustermann", "Anna Berger"]);
|
||||||
|
expect(spans[0].start).toBe(first.indexOf("Max"));
|
||||||
|
expect(spans[1].start).toBe(first.length + 64 * filler.length);
|
||||||
|
expect(Object.keys(result.mapping)).toEqual(["PERSON_01", "PERSON_02"]);
|
||||||
|
const outputHash = await writeReplacedTextFile(source, target, spans, new Set(["0"]), hash);
|
||||||
|
expect(outputHash).toBe(expected.digest("hex"));
|
||||||
|
expect(await hashProjectFile(target)).toBe(outputHash);
|
||||||
|
expect(await hashProjectFile(source)).toBe(hash);
|
||||||
|
expect(requests).toBeGreaterThan(1000); expect(maxActive).toBe(1);
|
||||||
|
}, 30_000);
|
||||||
|
it("ersetzt einen Treffer über einer Lesegrenze und erhält unveränderte Bytes", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "cross.txt"); const target = join(root, "out.txt");
|
||||||
|
const text = "x".repeat(65_531) + "Max Mustermann 😀\r\nEnde";
|
||||||
|
await fs.writeFile(source, text);
|
||||||
|
await writeReplacedTextFile(source, target, [{ id: "hit", start: 65_531, end: 65_545, placeholder: "PERSON_01" }], new Set(["hit"]), await hashProjectFile(source));
|
||||||
|
expect(await fs.readFile(target, "utf8")).toBe("x".repeat(65_531) + "PERSON_01 😀\r\nEnde");
|
||||||
|
});
|
||||||
|
it("hält Zuordnungen und Offsets über viele Dateien hinweg getrennt", async () => {
|
||||||
|
const root = await fixture(); const files = [];
|
||||||
|
for (let i = 0; i < 100; i++) { const path = join(root, `${i}.txt`); await fs.writeFile(path, "😀 Anna\r\n"); files.push({ key: String(i), path }); }
|
||||||
|
let requests = 0;
|
||||||
|
const result = await analyzeProjectTextFiles(files, {}, ["PERSON"], {}, async (text, mapping) => {
|
||||||
|
requests++;
|
||||||
|
return { pseudonymized_text: text, mapping: { ...mapping, PERSON_01: { original: "Anna", type: "PERSON" } }, selected_entity_types: ["PERSON"], entity_count: 1,
|
||||||
|
spans: [...text.matchAll(/Anna/g)].map((match) => ({ start: [...text.slice(0, match.index)].length, end: [...text.slice(0, match.index)].length + 4, original: "Anna", type: "PERSON", score: 1, placeholder: "PERSON_01" })) };
|
||||||
|
}, () => undefined);
|
||||||
|
expect(requests).toBe(1); expect(result.spansByFile.size).toBe(100);
|
||||||
|
for (const spans of result.spansByFile.values()) { expect(spans).toHaveLength(1); expect(spans[0].start).toBe(3); }
|
||||||
|
});
|
||||||
|
it("bricht überlange Zeilen ab und entfernt bei Quelländerungen die unvollständige Ausgabe", async () => {
|
||||||
|
const root = await fixture(); const source = join(root, "long.txt"); const target = join(root, "partial.txt");
|
||||||
|
await fs.writeFile(source, "x".repeat(20_001));
|
||||||
|
await expect(analyzeProjectTextFiles([{ key: "long.txt", path: source }], {}, [], {}, async () => { throw Error("should not call"); }, () => undefined)).rejects.toThrow("Zeile 1");
|
||||||
|
await expect(writeReplacedTextFile(source, target, [], new Set(), "old-hash")).rejects.toThrow("geändert");
|
||||||
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||||
|
expect((await fs.stat(source)).size).toBe(20_001);
|
||||||
|
});
|
||||||
|
it("verwirft Binärdaten und unvollständiges UTF-8 ohne fertige Ausgabedatei", async () => {
|
||||||
|
const root = await fixture();
|
||||||
|
for (const data of [Buffer.from([65, 0, 66]), Buffer.from([65, 0xc3])]) {
|
||||||
|
const source = join(root, "invalid.txt"); const target = join(root, "partial.txt"); await fs.writeFile(source, data);
|
||||||
|
await expect(inspectTextFile(source)).rejects.toThrow();
|
||||||
|
await expect(writeReplacedTextFile(source, target, [], new Set(), await hashProjectFile(source))).rejects.toThrow();
|
||||||
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("erkennt einen Namen auch über zwei Zeilen und eine Paketgrenze hinweg genau einmal", async () => {
|
||||||
|
const root = await fixture(); const path = join(root, "boundary.txt");
|
||||||
|
const prefix = "x\n".repeat(4997);
|
||||||
|
await fs.writeFile(path, prefix + "Max\r\nMustermann\r\nEnde");
|
||||||
|
const result = await analyzeProjectTextFiles([{ key: "boundary.txt", path }], {}, ["PERSON"], {}, async (text, mapping) => {
|
||||||
|
const spans = [...text.matchAll(/Max\r\nMustermann/g)].map((match) => ({ start: match.index, end: match.index + match[0].length,
|
||||||
|
original: match[0], placeholder: "PERSON_01", type: "PERSON", score: 1 }));
|
||||||
|
return { pseudonymized_text: text, mapping, spans, entity_count: spans.length, selected_entity_types: ["PERSON"] };
|
||||||
|
}, () => undefined);
|
||||||
|
expect(result.spansByFile.get("boundary.txt")!.map((span) => [span.start, span.end])).toEqual([[prefix.length, prefix.length + 15]]);
|
||||||
|
});
|
||||||
29
tests/restore-file-selection.test.ts
Normal file
29
tests/restore-file-selection.test.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { listRestorableFolders, selectRestorableFolder } from "../src/lib/restore-file-selection";
|
||||||
|
import type { ProjectFile } from "../src/lib/velum-project";
|
||||||
|
|
||||||
|
const files: ProjectFile[] = [
|
||||||
|
{ relPath: "A/Notiz.txt", absPath: "", kind: "text", size: 0 },
|
||||||
|
{ relPath: "A/Unterordner/Tabelle.xlsx", absPath: "", kind: "document", size: 0 },
|
||||||
|
{ relPath: "AB/Nachbar.txt", absPath: "", kind: "text", size: 0 },
|
||||||
|
{ relPath: "Wurzel.txt", absPath: "", kind: "text", size: 0 },
|
||||||
|
];
|
||||||
|
|
||||||
|
describe("Ordnerauswahl beim Klartext-Export", () => {
|
||||||
|
it("zeigt übergeordnete Ordner mit der Anzahl ihrer Unterordner-Dateien", () => {
|
||||||
|
expect(listRestorableFolders(files)).toEqual([
|
||||||
|
{ path: "A", fileCount: 2, textCount: 1, documentCount: 1 },
|
||||||
|
{ path: "A/Unterordner", fileCount: 1, textCount: 0, documentCount: 1 },
|
||||||
|
{ path: "AB", fileCount: 1, textCount: 1, documentCount: 0 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("wählt nur den gewählten Ordner rekursiv und keine ähnlich benannten Nachbarn", () => {
|
||||||
|
expect([...selectRestorableFolder(files, "A")]).toEqual([
|
||||||
|
"A/Notiz.txt",
|
||||||
|
]);
|
||||||
|
expect([...selectRestorableFolder(files, "A", true)]).toEqual([
|
||||||
|
"A/Notiz.txt", "A/Unterordner/Tabelle.xlsx",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
89
tests/rich-text.test.ts
Normal file
89
tests/rich-text.test.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { restoreRichHtml } from "../src/lib/rich-text";
|
||||||
|
|
||||||
|
const mapping = {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
ORG_01: { original: "Müller & Söhne", type: "ORG" },
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("formatierte Textwiederherstellung", () => {
|
||||||
|
it("behält Formatierung bei und maskiert Originale HTML-sicher", () => {
|
||||||
|
const html = "<p>Hallo <strong>PERSON_01</strong> bei <em>ORG_01</em>.</p>";
|
||||||
|
expect(
|
||||||
|
restoreRichHtml(
|
||||||
|
html,
|
||||||
|
"Hallo PERSON_01 bei ORG_01.",
|
||||||
|
"Hallo Max Mustermann bei Müller & Söhne.",
|
||||||
|
mapping,
|
||||||
|
),
|
||||||
|
).toBe(
|
||||||
|
"<p>Hallo <strong>Max Mustermann</strong> bei <em>Müller & Söhne</em>.</p>",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ändert weder Attribute noch unsichtbare Inhalte", () => {
|
||||||
|
const html =
|
||||||
|
'<div data-label="PERSON_01"><style>.PERSON_01{color:red}</style><b>PERSON_01</b></div>';
|
||||||
|
expect(restoreRichHtml(html, "PERSON_01", "Max Mustermann", mapping)).toBe(
|
||||||
|
'<div data-label="PERSON_01"><style>.PERSON_01{color:red}</style><b>Max Mustermann</b></div>',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("übernimmt kodierte Sitzungsplatzhalter", () => {
|
||||||
|
const html = "<span><PERSON_01></span>";
|
||||||
|
expect(
|
||||||
|
restoreRichHtml(
|
||||||
|
html,
|
||||||
|
"<PERSON_01>",
|
||||||
|
"Max Mustermann",
|
||||||
|
mapping,
|
||||||
|
undefined,
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
).toBe("<span>Max Mustermann</span>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verwirft nicht passende oder über mehrere Textknoten verteilte HTML-Daten", () => {
|
||||||
|
expect(
|
||||||
|
restoreRichHtml(
|
||||||
|
"<b>PERSON_01</b>",
|
||||||
|
"anderer Text",
|
||||||
|
"Max Mustermann",
|
||||||
|
mapping,
|
||||||
|
),
|
||||||
|
).toBeUndefined();
|
||||||
|
expect(
|
||||||
|
restoreRichHtml(
|
||||||
|
"<b>PERSON_</b><i>01</i>",
|
||||||
|
"PERSON_01",
|
||||||
|
"Max Mustermann",
|
||||||
|
mapping,
|
||||||
|
),
|
||||||
|
).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("beachtet projektbezogene Ersetzung innerhalb zusammengesetzter Begriffe", () => {
|
||||||
|
const html = "<b>abcPERSON_01xyz</b>";
|
||||||
|
expect(
|
||||||
|
restoreRichHtml(
|
||||||
|
html,
|
||||||
|
"abcPERSON_01xyz",
|
||||||
|
"abcMax Mustermannxyz",
|
||||||
|
mapping,
|
||||||
|
{ PERSON_01: "anywhere" },
|
||||||
|
),
|
||||||
|
).toBe("<b>abcMax Mustermannxyz</b>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("erhält HTML-Formatierung auch bei anders geschriebenen Platzhaltern", () => {
|
||||||
|
const html = "<b>person_01</b> und <i>Person_01</i>";
|
||||||
|
expect(restoreRichHtml(html, "person_01 und Person_01",
|
||||||
|
"max mustermann und Max Mustermann", mapping))
|
||||||
|
.toBe("<b>max mustermann</b> und <i>Max Mustermann</i>");
|
||||||
|
expect(restoreRichHtml("<b>Person_01</b> / <i>PERSON_01</i>",
|
||||||
|
"Person_01 / PERSON_01", "Person_01 / Eins", {
|
||||||
|
PERSON_01: { original: "Eins", type: "PERSON" },
|
||||||
|
person_01: { original: "Zwei", type: "PERSON" },
|
||||||
|
})).toBe("<b>Person_01</b> / <i>Eins</i>");
|
||||||
|
});
|
||||||
|
});
|
||||||
352
tests/text-context.test.ts
Normal file
352
tests/text-context.test.ts
Normal file
@@ -0,0 +1,352 @@
|
|||||||
|
import { afterEach, expect, it, mock } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { PlaceholderMapping, PseudonymizeResponse } from "../src/types";
|
||||||
|
|
||||||
|
const storage = new Map<string, string>();
|
||||||
|
mock.module("@raycast/api", () => ({
|
||||||
|
environment: { supportPath: tmpdir() },
|
||||||
|
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
|
||||||
|
LocalStorage: {
|
||||||
|
getItem: async (key: string) => storage.get(key),
|
||||||
|
setItem: async (key: string, value: string) => { storage.set(key, value); },
|
||||||
|
removeItem: async (key: string) => { storage.delete(key); },
|
||||||
|
},
|
||||||
|
getPreferenceValues: () => ({ velumBaseUrl: "", authentikTokenUrl: "", clientId: "",
|
||||||
|
serviceAccountUsername: "", serviceAccountPassword: "", maxSessions: "20" }),
|
||||||
|
}));
|
||||||
|
const { addTextReviewTerm, applyProjectWhitelist, pseudonymizeInContext, prepareTextInContext, commitPreparedText } = await import("../src/text-context");
|
||||||
|
const project = await import("../src/lib/velum-project");
|
||||||
|
const sessions = await import("../src/sessions");
|
||||||
|
const { relocateProject } = await import("../src/lib/project-relocation");
|
||||||
|
const { normalizePseudonymizeResponse } = await import("../src/velum");
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => {
|
||||||
|
storage.clear();
|
||||||
|
await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("behält Verweise beim Umstellen auf KI-Platzhalter konsistent", () => {
|
||||||
|
const result = normalizePseudonymizeResponse({
|
||||||
|
pseudonymized_text: "PERSON_02", selected_entity_types: ["PERSON"], spans: [], entity_count: 1,
|
||||||
|
mapping: {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(result.mapping["<PERSON_02>"].merged_into).toBe("<PERSON_01>");
|
||||||
|
expect(result.pseudonymized_text).toBe("<PERSON_02>");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("übernimmt eine Projekt-Ausnahme auch bei Textbefehlen", () => {
|
||||||
|
const result = applyProjectWhitelist("Max und Montag", {
|
||||||
|
pseudonymized_text: "PERSON_01 und ORT_01", selected_entity_types: ["PERSON", "ORT"],
|
||||||
|
spans: [
|
||||||
|
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
|
||||||
|
{ start: 8, end: 14, type: "ORT", score: 1, placeholder: "ORT_01", original: "Montag" },
|
||||||
|
], entity_count: 2,
|
||||||
|
mapping: {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Max" },
|
||||||
|
ORT_01: { type: "ORT", original: "Montag" },
|
||||||
|
},
|
||||||
|
}, {}, [{ type: "ORT", original: "Montag" }]);
|
||||||
|
expect(result.pseudonymized_text).toBe("PERSON_01 und Montag");
|
||||||
|
expect(result.mapping.ORT_01).toBeUndefined();
|
||||||
|
expect(result.entity_count).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("speichert vor der Trefferbestätigung nichts und übernimmt nur ausgewählte Treffer", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-review-"));
|
||||||
|
roots.push(root);
|
||||||
|
const folder = join(root, "Projekt");
|
||||||
|
await fs.mkdir(folder);
|
||||||
|
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => ({
|
||||||
|
pseudonymized_text: "PERSON_01 und ORT_01", selected_entity_types: ["PERSON", "ORT"],
|
||||||
|
spans: [
|
||||||
|
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
|
||||||
|
{ start: 8, end: 14, type: "ORT", score: 1, placeholder: "ORT_01", original: "Montag" },
|
||||||
|
], entity_count: 2,
|
||||||
|
mapping: { ...mapping, PERSON_01: { type: "PERSON", original: "Max" },
|
||||||
|
ORT_01: { type: "ORT", original: "Montag" } },
|
||||||
|
});
|
||||||
|
const prepared = await prepareTextInContext({ sessionId: "__new_project__", newProjectPath: [folder] },
|
||||||
|
"Max und Montag", ["PERSON", "ORT"], request);
|
||||||
|
expect(await project.listRuns(folder)).toHaveLength(0);
|
||||||
|
expect(await project.loadProjectWhitelist(folder)).toEqual([]);
|
||||||
|
const { result } = await commitPreparedText(prepared, new Set([0]), true);
|
||||||
|
expect(result.pseudonymized_text).toBe("<PERSON_01> und Montag");
|
||||||
|
expect(result.mapping["<ORT_01>"]).toBeUndefined();
|
||||||
|
expect((await project.listRuns(folder))[0].run.mapping.ORT_01).toBeUndefined();
|
||||||
|
expect(await project.loadProjectWhitelist(folder)).toEqual([{ type: "ORT", original: "Montag" }]);
|
||||||
|
const next = await prepareTextInContext({ sessionId: `project:${folder}` },
|
||||||
|
"Max und Montag", ["PERSON", "ORT"], request);
|
||||||
|
expect(next.raw.spans.map((span) => span.original)).toEqual(["Max"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht erneut vor", async () => {
|
||||||
|
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => ({
|
||||||
|
pseudonymized_text: "PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
|
||||||
|
mapping: { ...mapping, PERSON_01: { type: "PERSON", original: "Fachbegriff" } },
|
||||||
|
spans: [{ start: 0, end: 11, type: "PERSON", score: 0.8,
|
||||||
|
placeholder: "PERSON_01", original: "Fachbegriff" }],
|
||||||
|
});
|
||||||
|
const prepared = await prepareTextInContext({ sessionId: "__new_session__", newSessionName: " Kundenmail " },
|
||||||
|
"Fachbegriff", ["PERSON"], request);
|
||||||
|
expect(await sessions.listSessions()).toHaveLength(0);
|
||||||
|
const { result, session } = await commitPreparedText(prepared, new Set());
|
||||||
|
expect(result.pseudonymized_text).toBe("Fachbegriff");
|
||||||
|
expect(session.name).toBe("Kundenmail");
|
||||||
|
expect(session.mapping).toEqual({});
|
||||||
|
expect(await sessions.getActiveSessionId()).toBe(session.id);
|
||||||
|
expect((await sessions.getSession(session.id))?.excludedTerms).toEqual([
|
||||||
|
{ type: "PERSON", original: "Fachbegriff" },
|
||||||
|
]);
|
||||||
|
const next = await prepareTextInContext({ sessionId: session.id }, "Fachbegriff", ["PERSON"], request);
|
||||||
|
expect(next.raw.spans).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["session", "project"])("ergänzt eigene Begriffe auch bei abgewählter Kategorie und merkt sie für Folgeläufe (%s)", async (context) => {
|
||||||
|
const values = { sessionId: "__new_session__", newProjectPath: [] as string[] };
|
||||||
|
if (context === "project") {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-custom-term-"));
|
||||||
|
roots.push(root);
|
||||||
|
const folder = join(root, "Projekt");
|
||||||
|
await fs.mkdir(folder);
|
||||||
|
roots.push(project.projectDataRoot(folder));
|
||||||
|
values.sessionId = "__new_project__";
|
||||||
|
values.newProjectPath = [folder];
|
||||||
|
}
|
||||||
|
const text = "Max, 4711, 2025, 4711";
|
||||||
|
const term = { type: "REFERENZ", value: "4711" };
|
||||||
|
const request: typeof import("../src/velum").pseudonymize = async (_text, mapping, types, masks) => {
|
||||||
|
expect(types).toEqual(masks ? ["PERSON", "REFERENZ"] : ["PERSON"]);
|
||||||
|
if (masks) expect(masks).toEqual({ REFERENZ: ["4711"] });
|
||||||
|
const spans = [{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" }];
|
||||||
|
if (masks) spans.push(
|
||||||
|
{ start: 5, end: 9, type: "REFERENZ", score: 1, placeholder: "REFERENZ_01", original: "4711" },
|
||||||
|
{ start: 11, end: 15, type: "REFERENZ", score: 1, placeholder: "REFERENZ_02", original: "2025" },
|
||||||
|
{ start: 17, end: 21, type: "REFERENZ", score: 1, placeholder: "REFERENZ_01", original: "4711" },
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
spans, selected_entity_types: types ?? [], entity_count: masks ? 3 : 1,
|
||||||
|
mapping: { ...mapping, PERSON_01: { type: "PERSON", original: "Max" },
|
||||||
|
...(masks && { REFERENZ_01: { type: "REFERENZ", original: "4711" },
|
||||||
|
REFERENZ_02: { type: "REFERENZ", original: "2025" } }) },
|
||||||
|
pseudonymized_text: masks ? "PERSON_01, REFERENZ_01, REFERENZ_02, REFERENZ_01" : "PERSON_01, 4711, 2025, 4711",
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const initial = await prepareTextInContext(values, text, ["PERSON"], request);
|
||||||
|
const updated = await addTextReviewTerm(initial, term, new Set(), request);
|
||||||
|
expect([...updated.selected]).toEqual([1, 2]);
|
||||||
|
expect(await sessions.listSessions()).toHaveLength(0);
|
||||||
|
if (context === "project") expect(await project.loadProjectRules(values.newProjectPath[0])).toEqual([]);
|
||||||
|
const { result, session } = await commitPreparedText(updated.prepared, updated.selected, true);
|
||||||
|
expect(result.pseudonymized_text).toBe("Max, <REFERENZ_01>, 2025, <REFERENZ_01>");
|
||||||
|
expect(result.selected_entity_types).toEqual(["PERSON"]);
|
||||||
|
const followup = await prepareTextInContext({ sessionId: session.id }, text, ["PERSON"], request);
|
||||||
|
expect(followup.raw.spans.map((span) => span.original)).toEqual(["4711", "4711"]);
|
||||||
|
expect(followup.customTerms).toEqual([term]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["session", "project"])("fasst geprüfte Namensvarianten zusammen und speichert sie für Folgeläufe (%s)", async (context) => {
|
||||||
|
let values = { sessionId: "__new_session__", newProjectPath: [] as string[] };
|
||||||
|
if (context === "project") {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-merge-"));
|
||||||
|
roots.push(root);
|
||||||
|
const folder = join(root, "Projekt");
|
||||||
|
await fs.mkdir(folder);
|
||||||
|
values = { sessionId: "__new_project__", newProjectPath: [folder] };
|
||||||
|
}
|
||||||
|
const source = "😀 Max Muster\nMax und Mia";
|
||||||
|
const prepared = await prepareTextInContext(values, source, ["PERSON"], async () => ({
|
||||||
|
pseudonymized_text: "😀 PERSON_01\nPERSON_02 und PERSON_03",
|
||||||
|
selected_entity_types: ["PERSON"], entity_count: 3,
|
||||||
|
mapping: {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Max Muster" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Max" },
|
||||||
|
PERSON_03: { type: "PERSON", original: "Mia" },
|
||||||
|
},
|
||||||
|
spans: [
|
||||||
|
{ start: 2, end: 12, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max Muster" },
|
||||||
|
{ start: 13, end: 16, type: "PERSON", score: 1, placeholder: "PERSON_02", original: "Max" },
|
||||||
|
{ start: 21, end: 24, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Mia" },
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
await expect(commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_03" }))
|
||||||
|
.rejects.toThrow("ausgewählte Personen");
|
||||||
|
const { result, session } = await commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_01" });
|
||||||
|
expect(result.pseudonymized_text).toBe("😀 <PERSON_01>\n<PERSON_01> und Mia");
|
||||||
|
expect(result.entity_count).toBe(1);
|
||||||
|
expect(result.spans.map((span) => span.placeholder)).toEqual(["PERSON_01", "PERSON_01"]);
|
||||||
|
expect(result.mapping["<PERSON_02>"]).toEqual({ type: "PERSON", original: "Max", merged_into: "<PERSON_01>" });
|
||||||
|
expect(result.mapping["<PERSON_03>"]).toBeUndefined();
|
||||||
|
expect(session.mapping["<PERSON_02>"].original).toBe("Max Muster");
|
||||||
|
|
||||||
|
const followup = await prepareTextInContext({ sessionId: session.id }, "Max und Maximilian", ["PERSON"],
|
||||||
|
async (_text, mapping) => {
|
||||||
|
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
|
||||||
|
expect(mapping["<PERSON_02>"]).toBeUndefined();
|
||||||
|
return {
|
||||||
|
pseudonymized_text: "PERSON_01 und PERSON_03", selected_entity_types: ["PERSON"], entity_count: 2,
|
||||||
|
mapping: { ...mapping, PERSON_03: { type: "PERSON", original: "Maximilian" } },
|
||||||
|
spans: [
|
||||||
|
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
|
||||||
|
{ start: 8, end: 18, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Maximilian" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const updated = await commitPreparedText(followup, new Set([0, 1]), false, { PERSON_01: "PERSON_03" });
|
||||||
|
expect(updated.result.pseudonymized_text).toBe("PERSON_03 und PERSON_03");
|
||||||
|
expect(updated.result.mapping.PERSON_02.merged_into).toBe("PERSON_03");
|
||||||
|
expect(updated.session.mapping.PERSON_02.original).toBe("Maximilian");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("entfernt eine False-Positive-Gruppe aus der Sitzung und merkt alle Varianten", async () => {
|
||||||
|
const session = await sessions.createSession("Test");
|
||||||
|
await sessions.updateSessionMapping(session.id, {
|
||||||
|
"<PERSON_01>": { type: "PERSON", original: "Fachbegriff" },
|
||||||
|
"<PERSON_02>": { type: "PERSON", original: "Fachbegriff kurz", merged_into: "<PERSON_01>" },
|
||||||
|
"<ORG_01>": { type: "ORG", original: "Beispiel GmbH" },
|
||||||
|
});
|
||||||
|
const revised = await sessions.releaseSessionMappingGroup(session.id, "<PERSON_01>");
|
||||||
|
expect(Object.keys(revised.mapping)).toEqual(["<ORG_01>"]);
|
||||||
|
expect(revised.excludedTerms).toEqual([
|
||||||
|
{ type: "PERSON", original: "Fachbegriff" },
|
||||||
|
{ type: "PERSON", original: "Fachbegriff kurz" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bewahrt das Anlagedatum einer Sitzung beim Umklammern und Zusammenfassen", async () => {
|
||||||
|
const session = await sessions.createSession("Zeitfolge");
|
||||||
|
const first = await sessions.updateSessionMapping(session.id, {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Beispiel Eins" },
|
||||||
|
});
|
||||||
|
const created = first.mappingCreatedAt?.PERSON_01;
|
||||||
|
expect(created).toBeTruthy();
|
||||||
|
const next = await sessions.updateSessionMapping(session.id, {
|
||||||
|
"<PERSON_01>": { type: "PERSON", original: "Beispiel Eins" },
|
||||||
|
"<PERSON_02>": { type: "PERSON", original: "Beispiel Zwei", merged_into: "<PERSON_01>" },
|
||||||
|
});
|
||||||
|
expect(next.mappingCreatedAt?.["<PERSON_01>"]).toBe(created);
|
||||||
|
expect(next.mappingCreatedAt?.["<PERSON_02>"]).toBeTruthy();
|
||||||
|
expect(next.mappingCreatedAt?.PERSON_01).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verlangt eine ausdrückliche Kontextwahl und legt ein Textprojekt nur einmal an", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-context-"));
|
||||||
|
roots.push(root);
|
||||||
|
const folder = join(root, "Projekt");
|
||||||
|
await fs.mkdir(folder);
|
||||||
|
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => ({
|
||||||
|
pseudonymized_text: "PERSON_01", mapping: {
|
||||||
|
...mapping, PERSON_01: { type: "PERSON", original: "Alex Beispiel" },
|
||||||
|
}, selected_entity_types: ["PERSON"], spans: [], entity_count: 1,
|
||||||
|
});
|
||||||
|
await expect(pseudonymizeInContext({ sessionId: "__choose_context__" }, "Alex Beispiel", ["PERSON"], false, request))
|
||||||
|
.rejects.toThrow("Bitte ein Projekt");
|
||||||
|
const created = await pseudonymizeInContext({ sessionId: "__new_project__", newProjectPath: [folder] },
|
||||||
|
"Alex Beispiel", ["PERSON"], false, request);
|
||||||
|
expect(created.session.name).toBe("Projekt Projekt");
|
||||||
|
expect((await project.listRuns(folder)).length).toBe(1);
|
||||||
|
await expect(pseudonymizeInContext({ sessionId: "__new_project__", newProjectPath: [folder] },
|
||||||
|
"Alex Beispiel", ["PERSON"], false, request)).rejects.toThrow("bereits ein Projekt");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verwendet die bestehende Projekttabelle und bewahrt ihre Verweise für spätere Läufe", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-reuse-"));
|
||||||
|
roots.push(root);
|
||||||
|
const folder = join(root, "Quelle");
|
||||||
|
await fs.mkdir(folder);
|
||||||
|
const saved = await project.createRun(folder);
|
||||||
|
saved.run.mapping = {
|
||||||
|
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
|
||||||
|
};
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => {
|
||||||
|
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
|
||||||
|
return { pseudonymized_text: "PERSON_02 und PERSON_03", mapping: {
|
||||||
|
...mapping, PERSON_03: { type: "PERSON", original: "Mara Muster" },
|
||||||
|
}, selected_entity_types: ["PERSON"], spans: [], entity_count: 2 };
|
||||||
|
};
|
||||||
|
const { result, session } = await pseudonymizeInContext({ sessionId: `project:${folder}` },
|
||||||
|
"Hr. Fuchs und Mara Muster", ["PERSON"], true, request);
|
||||||
|
expect(result.pseudonymized_text).toBe("<PERSON_02> und <PERSON_03>");
|
||||||
|
expect(session.mapping["<PERSON_02>"].original).toBe("Franz Fuchs");
|
||||||
|
const runs = await project.listRuns(folder);
|
||||||
|
expect(runs).toHaveLength(2);
|
||||||
|
expect(runs[0].run.mapping.PERSON_02.original).toBe("Hr. Fuchs");
|
||||||
|
expect(runs[0].run.mapping.PERSON_02.merged_into).toBe("PERSON_01");
|
||||||
|
expect(runs[0].run.mapping.PERSON_03.original).toBe("Mara Muster");
|
||||||
|
expect(runs[1].run.mapping.PERSON_03).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["review", "direct"])("verwendet gespeicherte Projektzuordnungen nach Verschieben des Quellordners (%s)", async (mode) => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-moved-"));
|
||||||
|
roots.push(root);
|
||||||
|
const folder = join(root, "Quelle");
|
||||||
|
await fs.mkdir(folder);
|
||||||
|
roots.push(project.projectDataRoot(folder));
|
||||||
|
const saved = await project.createRun(folder);
|
||||||
|
saved.run.mapping = { PERSON_01: { type: "PERSON", original: "Max" } };
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
await fs.rename(folder, join(root, "Verschoben"));
|
||||||
|
const values = { sessionId: `project:${folder}` };
|
||||||
|
let expectedMapping = saved.run.mapping;
|
||||||
|
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => {
|
||||||
|
expect(mapping).toEqual(expectedMapping);
|
||||||
|
return {
|
||||||
|
pseudonymized_text: "PERSON_01 und PERSON_02", selected_entity_types: ["PERSON"], entity_count: 2,
|
||||||
|
mapping: { ...mapping, PERSON_02: { type: "PERSON", original: "Mara" } },
|
||||||
|
spans: [
|
||||||
|
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
|
||||||
|
{ start: 8, end: 12, type: "PERSON", score: 1, placeholder: "PERSON_02", original: "Mara" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
};
|
||||||
|
const output = mode === "review"
|
||||||
|
? await commitPreparedText(await prepareTextInContext(values, "Max und Mara", ["PERSON"], request), new Set([0, 1]))
|
||||||
|
: await pseudonymizeInContext(values, "Max und Mara", ["PERSON"], false, request);
|
||||||
|
expect(output.result.pseudonymized_text).toBe("PERSON_01 und PERSON_02");
|
||||||
|
expect(output.session.id).toBe(`project:${folder}`);
|
||||||
|
const runs = await project.listRuns(folder);
|
||||||
|
expect(runs).toHaveLength(2);
|
||||||
|
expect(runs[0].run.mapping.PERSON_02.original).toBe("Mara");
|
||||||
|
expect(runs[1].run.mapping.PERSON_02).toBeUndefined();
|
||||||
|
|
||||||
|
const moved = join(root, "Verschoben");
|
||||||
|
roots.push(project.projectDataRoot(moved));
|
||||||
|
await relocateProject(folder, moved);
|
||||||
|
expect(await project.listRuns(folder)).toHaveLength(0);
|
||||||
|
expectedMapping = runs[0].run.mapping;
|
||||||
|
const movedValues = { sessionId: `project:${moved}` };
|
||||||
|
const next = mode === "review"
|
||||||
|
? await commitPreparedText(await prepareTextInContext(movedValues, "Max und Mara", ["PERSON"], request), new Set([0, 1]))
|
||||||
|
: await pseudonymizeInContext(movedValues, "Max und Mara", ["PERSON"], false, request);
|
||||||
|
expect(next.session.id).toBe(`project:${moved}`);
|
||||||
|
expect(next.result.pseudonymized_text).toBe(output.result.pseudonymized_text);
|
||||||
|
expect((await project.listRuns(moved))[0].run.mapping).toEqual(expectedMapping);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["review", "direct"])("prüft den Ordner weiterhin für neue Projekte und verlangt einen gespeicherten Stand für bestehende (%s)", async (mode) => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-validation-"));
|
||||||
|
roots.push(root);
|
||||||
|
const missing = join(root, "Fehlt");
|
||||||
|
const file = join(root, "Datei.txt");
|
||||||
|
await fs.writeFile(file, "kein Ordner");
|
||||||
|
let requests = 0;
|
||||||
|
const request = async (): Promise<PseudonymizeResponse> => {
|
||||||
|
requests++;
|
||||||
|
throw new Error("Die API darf bei ungültigem Kontext nicht aufgerufen werden.");
|
||||||
|
};
|
||||||
|
const run = (values: { sessionId: string; newProjectPath?: string[] }) => mode === "review"
|
||||||
|
? prepareTextInContext(values, "Max", ["PERSON"], request)
|
||||||
|
: pseudonymizeInContext(values, "Max", ["PERSON"], false, request);
|
||||||
|
for (const folder of [undefined, missing, file]) {
|
||||||
|
await expect(run({ sessionId: "__new_project__", newProjectPath: folder ? [folder] : undefined }))
|
||||||
|
.rejects.toThrow("Bitte einen vorhandenen Projektordner wählen.");
|
||||||
|
}
|
||||||
|
await expect(run({ sessionId: `project:${missing}` })).rejects.toThrow("Projektstand nicht gefunden.");
|
||||||
|
expect(requests).toBe(0);
|
||||||
|
});
|
||||||
532
tests/velum-project.test.ts
Normal file
532
tests/velum-project.test.ts
Normal file
@@ -0,0 +1,532 @@
|
|||||||
|
import { afterEach, describe, expect, it, mock } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { RunFile } from "../src/lib/velum-project";
|
||||||
|
|
||||||
|
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() },
|
||||||
|
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
|
||||||
|
LocalStorage: {}, getPreferenceValues: () => ({}) }));
|
||||||
|
const project = await import("../src/lib/velum-project");
|
||||||
|
const { mappingForRestoration } = await import("../src/lib/mapping-groups");
|
||||||
|
const { mergeMappingGroups } = await import("../src/lib/mapping-groups");
|
||||||
|
const { relocateProject } = await import("../src/lib/project-relocation");
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); });
|
||||||
|
|
||||||
|
describe("Velum-Projektstände", () => {
|
||||||
|
it("speichert Projektregeln und Bearbeitungsstände getrennt vom Quellordner", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-project-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
await fs.writeFile(join(source, "Notiz.txt"), "Max Mustermann");
|
||||||
|
const rules = project.parseProjectRules("PERSON: Max Mustermann\nKundenSuite\nREFERENZ: 4711",
|
||||||
|
["BEGRIFF", "PERSON", "REFERENZ"]);
|
||||||
|
await project.saveProjectRules(source, rules, support);
|
||||||
|
expect(await project.loadProjectRules(source, support)).toEqual(rules);
|
||||||
|
expect(project.forceMasks(rules)).toEqual({
|
||||||
|
PERSON: ["Max Mustermann"], BEGRIFF: ["KundenSuite"], REFERENZ: ["4711"],
|
||||||
|
});
|
||||||
|
await project.saveProjectWhitelist(source, [
|
||||||
|
{ type: "PERSON", original: "Falscher Treffer" },
|
||||||
|
{ type: "PERSON", original: "falscher treffer" },
|
||||||
|
], support);
|
||||||
|
expect(await project.loadProjectWhitelist(source, support)).toEqual([
|
||||||
|
{ type: "PERSON", original: "falscher treffer" },
|
||||||
|
]);
|
||||||
|
expect(await fs.readFile(join(source, "Notiz.txt"), "utf8")).toBe("Max Mustermann");
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
created.run.mapping = { PERSON_01: { original: "Max Mustermann", type: "PERSON" } };
|
||||||
|
created.run.files.push({ source: "Notiz.txt", output: "PERSON_01.txt", kind: "text" });
|
||||||
|
await project.saveRun(created.directory, created.run);
|
||||||
|
expect((await project.listRuns(source, support))[0].run.files[0].output).toBe("PERSON_01.txt");
|
||||||
|
expect(await fs.readFile(join(source, "Notiz.txt"), "utf8")).toBe("Max Mustermann");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ordnet erneute Läufe demselben Projektpfad zu und erkennt ältere Pfadschreibweisen", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-project-identity-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const first = await project.createRun(`${source}/`, support);
|
||||||
|
first.run.projectPath = `${source}/`;
|
||||||
|
await project.saveRun(first.directory, first.run);
|
||||||
|
const second = await project.createRun(join(source, "."), support);
|
||||||
|
await project.saveRun(second.directory, second.run);
|
||||||
|
expect(project.projectDataRoot(source, support)).toBe(project.projectDataRoot(`${source}/`, support));
|
||||||
|
expect(first.run.id).not.toBe(second.run.id);
|
||||||
|
expect((await project.listRuns(source, support)).map(({ run }) => run.id).sort())
|
||||||
|
.toEqual([first.run.id, second.run.id].sort());
|
||||||
|
});
|
||||||
|
|
||||||
|
it("übernimmt nach einem Umzug alle Projektstände, Regeln und verschobenen Kopien", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-relocate-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const oldParent = join(root, "Alt");
|
||||||
|
const newParent = join(root, "Neu");
|
||||||
|
const oldPath = join(oldParent, "Projekt");
|
||||||
|
const newPath = join(newParent, "Projekt");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(oldPath, { recursive: true });
|
||||||
|
await fs.writeFile(join(oldPath, "Notiz.txt"), "PERSON_01");
|
||||||
|
await project.saveProjectRules(oldPath, [{ type: "BEGRIFF", value: "Testsystem" }], support);
|
||||||
|
await project.saveProjectWhitelist(oldPath, [{ type: "PERSON", original: "Kein Name" }], support);
|
||||||
|
await project.saveProjectEntityTypes(oldPath, ["PERSON", "ORG"], support);
|
||||||
|
await project.saveProjectFileExclusions(oldPath, ["Ausnahme.txt"], support);
|
||||||
|
const first = await project.createRun(oldPath, support);
|
||||||
|
first.run.mapping = { PERSON_01: { original: "Erika Beispiel", type: "PERSON" } };
|
||||||
|
first.run.files = [{ source: "Notiz.txt", output: "Notiz.txt", kind: "text" }];
|
||||||
|
first.run.inPlace = true;
|
||||||
|
await fs.writeFile(join(first.directory, "files", "Notiz.txt"), "PERSON_01");
|
||||||
|
const oldCopy = join(oldParent, `Projekt-Velum-${first.run.id}`);
|
||||||
|
await fs.mkdir(oldCopy);
|
||||||
|
await fs.writeFile(join(oldCopy, "Notiz.txt"), "PERSON_01");
|
||||||
|
first.run.copyPath = oldCopy;
|
||||||
|
await project.saveRun(first.directory, first.run);
|
||||||
|
const second = await project.createRun(oldPath, support);
|
||||||
|
second.run.createdAt = new Date(Date.parse(first.run.createdAt) + 1000).toISOString();
|
||||||
|
second.run.mapping = first.run.mapping;
|
||||||
|
second.run.files = first.run.files;
|
||||||
|
second.run.inPlace = true;
|
||||||
|
await fs.writeFile(join(second.directory, "files", "Notiz.txt"), "PERSON_01");
|
||||||
|
await project.saveRun(second.directory, second.run);
|
||||||
|
|
||||||
|
await fs.rename(oldParent, newParent);
|
||||||
|
expect(await relocateProject(oldPath, newPath, support))
|
||||||
|
.toEqual({ runsMoved: 2, copiesRelinked: 1, copiesMissing: 0 });
|
||||||
|
expect(await project.listRuns(oldPath, support)).toHaveLength(0);
|
||||||
|
const moved = await project.listRuns(newPath, support);
|
||||||
|
expect(moved.map(({ run }) => run.id)).toEqual([second.run.id, first.run.id]);
|
||||||
|
expect(moved.every(({ run }) => run.projectPath === newPath && run.projectName === "Projekt")).toBe(true);
|
||||||
|
expect(moved[1].run.copyPath).toBe(join(newParent, `Projekt-Velum-${first.run.id}`));
|
||||||
|
expect(moved[0].run.mapping).toEqual(first.run.mapping);
|
||||||
|
expect(await project.loadProjectRules(newPath, support)).toEqual([{ type: "BEGRIFF", value: "Testsystem" }]);
|
||||||
|
expect(await project.loadProjectWhitelist(newPath, support)).toEqual([{ type: "PERSON", original: "Kein Name" }]);
|
||||||
|
expect(await project.loadProjectEntityTypes(newPath, support)).toEqual(["PERSON", "ORG"]);
|
||||||
|
expect(await project.loadProjectFileExclusions(newPath, support)).toEqual(["Ausnahme.txt"]);
|
||||||
|
expect((await project.scanRestorableCopyFiles(moved[0].run, moved[0].directory)).root).toBe(newPath);
|
||||||
|
expect((await project.listAllRuns(support)).filter(({ run }) => run.projectPath === newPath)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verhindert das Umhängen auf einen bereits belegten Projektordner", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-relocate-conflict-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const oldPath = join(root, "Alt");
|
||||||
|
const newPath = join(root, "Neu");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(oldPath);
|
||||||
|
await fs.mkdir(newPath);
|
||||||
|
const oldRun = await project.createRun(oldPath, support);
|
||||||
|
const targetRun = await project.createRun(newPath, support);
|
||||||
|
await project.saveRun(oldRun.directory, oldRun.run);
|
||||||
|
await project.saveRun(targetRun.directory, targetRun.run);
|
||||||
|
await expect(relocateProject(oldPath, oldPath, support)).rejects.toThrow("bereits der Projektordner");
|
||||||
|
await expect(relocateProject(oldPath, join(root, "Fehlt"), support)).rejects.toThrow("nicht vorhanden");
|
||||||
|
await expect(relocateProject(oldPath, newPath, support)).rejects.toThrow("bereits ein Velum-Projekt");
|
||||||
|
expect(await project.listRuns(oldPath, support)).toHaveLength(1);
|
||||||
|
expect(await project.listRuns(newPath, support)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("legt pseudonymisierte Kopien neben dem Projekt ab und behält die Tabelle privat", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-sibling-copy-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
created.run.mapping = { PERSON_01: { original: "Max Mustermann", type: "PERSON" } };
|
||||||
|
created.run.files = [{ source: "Unterordner/Name.txt", output: "Unterordner/PERSON_01.txt", kind: "text" }];
|
||||||
|
await fs.mkdir(join(created.directory, "files", "Unterordner"));
|
||||||
|
await fs.writeFile(join(created.directory, "files", "Unterordner", "PERSON_01.txt"), "PERSON_01");
|
||||||
|
const copyPath = await project.publishProjectCopies(created.run, created.directory);
|
||||||
|
created.run.copyPath = copyPath;
|
||||||
|
await project.saveRun(created.directory, created.run);
|
||||||
|
expect(copyPath.startsWith(join(root, "Quelle-Velum-"))).toBe(true);
|
||||||
|
expect(project.runCopiesPath(created.run, created.directory)).toBe(copyPath);
|
||||||
|
expect(await fs.readFile(join(copyPath, "Unterordner", "PERSON_01.txt"), "utf8")).toBe("PERSON_01");
|
||||||
|
expect(await fs.readdir(copyPath)).toEqual(["Unterordner"]);
|
||||||
|
expect(await fs.readFile(join(created.directory, "run.json"), "utf8")).toContain("Max Mustermann");
|
||||||
|
await fs.writeFile(join(copyPath, "Antwort.txt"), "PERSON_01 antwortet");
|
||||||
|
const current = await project.scanRestorableCopyFiles(created.run, created.directory);
|
||||||
|
expect(current.root).toBe(copyPath);
|
||||||
|
expect(current.files.map((file) => file.relPath)).toEqual(["Antwort.txt", "Unterordner/PERSON_01.txt"]);
|
||||||
|
const history = await project.scanRestorableCopyFiles(created.run, created.directory, false);
|
||||||
|
expect(history.root).toBe(join(created.directory, "files"));
|
||||||
|
expect(history.files.map((file) => file.relPath)).toEqual(["Unterordner/PERSON_01.txt"]);
|
||||||
|
expect(project.restoreTextWithCount("PERSON_01 antwortet", created.run.mapping))
|
||||||
|
.toEqual({ text: "Max Mustermann antwortet", replacements: 1 });
|
||||||
|
await expect(project.publishProjectCopies(created.run, created.directory)).rejects.toThrow("bereits vorhanden");
|
||||||
|
expect((await project.listRuns(source, support))[0].run.copyPath).toBe(copyPath);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("behält die Kategorieauswahl pro Projekt für den nächsten Lauf", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-entity-types-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const other = join(root, "Anderes Projekt");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
await fs.mkdir(other);
|
||||||
|
expect(await project.loadProjectEntityTypes(source, support)).toBeNull();
|
||||||
|
await project.saveProjectEntityTypes(`${source}/`, ["PERSON", "ORG", "PERSON"], support);
|
||||||
|
expect(await project.loadProjectEntityTypes(source, support)).toEqual(["PERSON", "ORG"]);
|
||||||
|
expect(await project.loadProjectEntityTypes(other, support)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("behält abgewählte Dateien pro Projekt und gibt sie nicht an die Analyse weiter", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-file-selection-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const other = join(root, "Anderes Projekt");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(join(source, "Unterordner"), { recursive: true });
|
||||||
|
await fs.mkdir(other);
|
||||||
|
await fs.writeFile(join(source, "Behalten.txt"), "Künstlicher Testtext");
|
||||||
|
await fs.writeFile(join(source, "Unterordner", "Auslassen.md"), "Künstlicher Testtext");
|
||||||
|
|
||||||
|
expect(await project.loadProjectFileExclusions(source, support)).toEqual([]);
|
||||||
|
await project.saveProjectFileExclusions(`${source}/`, ["Unterordner/Auslassen.md", "Unterordner/Auslassen.md"], support);
|
||||||
|
expect(await project.loadProjectFileExclusions(source, support)).toEqual(["Unterordner/Auslassen.md"]);
|
||||||
|
expect(await project.loadProjectFileExclusions(other, support)).toEqual([]);
|
||||||
|
const scan = await project.scanProjectFiles(source, undefined, false);
|
||||||
|
const chosen = project.withoutExcludedProjectFiles(scan.files, await project.loadProjectFileExclusions(source, support));
|
||||||
|
expect(chosen.map((file) => file.relPath)).toEqual(["Behalten.txt"]);
|
||||||
|
const run = await project.createRun(source, support);
|
||||||
|
await fs.writeFile(join(run.directory, "files", "Behalten.txt"), "PERSON_01");
|
||||||
|
await project.replaceProjectFilesInPlace(source, run.directory,
|
||||||
|
chosen.map((file) => ({ source: file.relPath, output: file.relPath, kind: file.kind })));
|
||||||
|
expect(await fs.readFile(join(source, "Behalten.txt"), "utf8")).toBe("PERSON_01");
|
||||||
|
expect(await fs.readFile(join(source, "Unterordner", "Auslassen.md"), "utf8"))
|
||||||
|
.toBe("Künstlicher Testtext");
|
||||||
|
await expect(project.saveProjectFileExclusions(source, ["../Anderes Projekt/Datei.txt"], support))
|
||||||
|
.rejects.toThrow("Ungültiger Dateipfad");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("überspringt temporäre und falsch benannte Office-Dateien vor der API-Analyse", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-office-scan-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
await fs.writeFile(join(root, "Notiz.txt"), "Nur ein künstlicher Testtext");
|
||||||
|
await fs.writeFile(join(root, "Bericht.xlsx"), "Kein Excel-Archiv");
|
||||||
|
await fs.writeFile(join(root, "~$Entwurf.xlsx"), "Sperrdatei");
|
||||||
|
await fs.writeFile(join(root, "._Tabelle.xlsx"), "AppleDouble");
|
||||||
|
await fs.writeFile(join(root, "Gültig.xlsx"), Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x00]));
|
||||||
|
|
||||||
|
const scan = await project.scanProjectFiles(root);
|
||||||
|
expect(scan.files.map((file) => file.relPath)).toEqual(["Gültig.xlsx", "Notiz.txt"]);
|
||||||
|
expect(scan.skipped).toEqual(expect.arrayContaining([
|
||||||
|
{ path: "Bericht.xlsx", reason: expect.stringContaining("Office-ZIP-Archiv") },
|
||||||
|
{ path: "~$Entwurf.xlsx", reason: "Temporäre Office-/macOS-Datei" },
|
||||||
|
{ path: "._Tabelle.xlsx", reason: "Temporäre Office-/macOS-Datei" },
|
||||||
|
]));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stellt aktuelle In-Place-Dateien aus dem Projektordner und frühere Stände aus dem Snapshot bereit", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-current-source-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Projekt");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
created.run.inPlace = true;
|
||||||
|
created.run.files = [{ source: "Notiz.txt", output: "Notiz.txt", kind: "text" }];
|
||||||
|
await fs.writeFile(join(created.directory, "files", "Notiz.txt"), "PERSON_01");
|
||||||
|
await fs.writeFile(join(source, "Notiz.txt"), "PERSON_01");
|
||||||
|
await fs.writeFile(join(source, "Antwort.txt"), "PERSON_01 antwortet");
|
||||||
|
|
||||||
|
const current = await project.scanRestorableCopyFiles(created.run, created.directory);
|
||||||
|
expect(current.root).toBe(source);
|
||||||
|
expect(current.files.map((file) => file.relPath)).toEqual(["Antwort.txt", "Notiz.txt"]);
|
||||||
|
const historical = await project.scanRestorableCopyFiles(created.run, created.directory, false);
|
||||||
|
expect(historical.root).toBe(join(created.directory, "files"));
|
||||||
|
expect(historical.files.map((file) => file.relPath)).toEqual(["Notiz.txt"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ersetzt nur bestätigte Vorkommen und stellt Dateinamen wieder her", () => {
|
||||||
|
const hits = [
|
||||||
|
{ id: "a", start: 0, end: 3, placeholder: "PERSON_01" },
|
||||||
|
{ id: "b", start: 8, end: 11, placeholder: "PERSON_01" },
|
||||||
|
];
|
||||||
|
expect(project.replaceSpans("Max und Max", hits, new Set(["a"]))).toBe("PERSON_01 und Max");
|
||||||
|
expect(project.restorePath("PERSON_01_Bericht.txt", {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
})).toBe("Max Mustermann_Bericht.txt");
|
||||||
|
expect(project.restorePath("Archiv/BerichtPERSON_01.docx", {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
})).toBe("Archiv/BerichtMax Mustermann.docx");
|
||||||
|
expect(project.restorePath("archiv/bericht_person_01.docx", {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
})).toBe("archiv/bericht_max mustermann.docx");
|
||||||
|
expect(project.restoreTextWithCount("person_01 und Person_01", {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
})).toEqual({ text: "max mustermann und Max Mustermann", replacements: 2 });
|
||||||
|
expect(project.restoreText("PERSON_01 / person_01 / Person_01", {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
})).toBe("Max Mustermann / max mustermann / Max Mustermann");
|
||||||
|
expect(project.restoreText("KUNDE_01 / kunde_01 / Kunde_01", {
|
||||||
|
KUNDE_01: { original: "ACME GMBH", type: "KUNDE" },
|
||||||
|
})).toBe("ACME GMBH / acme gmbh / Acme Gmbh");
|
||||||
|
expect(project.restoreText("person_01 / PERSON_01", {
|
||||||
|
person_01: { original: "max mustermann", type: "PERSON" },
|
||||||
|
})).toBe("max mustermann / MAX MUSTERMANN");
|
||||||
|
expect(project.restoreText("BerichtPERSON_01", {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
})).toBe("BerichtPERSON_01");
|
||||||
|
expect(project.restoreText("Fachkonzept `PROJEKT_01_Fachkonzept_V03.docx` widerspricht Kommentar PERSON_61 (ID 1088)", {
|
||||||
|
PROJEKT_01: { original: "Beispielprojekt", type: "PROJEKT" },
|
||||||
|
PERSON_61: { original: "Mara Muster", type: "PERSON" },
|
||||||
|
}, undefined, true)).toBe("Fachkonzept `Beispielprojekt_Fachkonzept_V03.docx` widerspricht Kommentar Mara Muster (ID 1088)");
|
||||||
|
expect(project.restoreText("PERSON_0101 und PERSON_01", {
|
||||||
|
PERSON_01: { original: "Max Mustermann", type: "PERSON" },
|
||||||
|
}, undefined, true)).toBe("PERSON_0101 und Max Mustermann");
|
||||||
|
expect(project.restorePath("PERSON_0101.txt", {
|
||||||
|
PERSON_01: { original: "Falsch", type: "PERSON" },
|
||||||
|
PERSON_0101: { original: "Richtig", type: "PERSON" },
|
||||||
|
})).toBe("Richtig.txt");
|
||||||
|
expect(project.restoreText("Person_01 / PERSON_01", {
|
||||||
|
PERSON_01: { original: "Eins", type: "PERSON" },
|
||||||
|
person_01: { original: "Zwei", type: "PERSON" },
|
||||||
|
})).toBe("Person_01 / Eins");
|
||||||
|
expect(() => project.safeRelativePath("../geheim.txt")).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stellt alte Personen-Verweise in Text und Dateiname mit dem Hauptbegriff wieder her", () => {
|
||||||
|
const mapping = mappingForRestoration({
|
||||||
|
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
|
||||||
|
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
|
||||||
|
});
|
||||||
|
expect(project.restoreText("PERSON_02 und PERSON_01", mapping)).toBe("Franz Fuchs und Franz Fuchs");
|
||||||
|
expect(project.restorePath("PERSON_02_Entwurf.md", mapping)).toBe("Franz Fuchs_Entwurf.md");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verwendet ältere Zuordnungen nur bei übereinstimmender Bedeutung und meldet übrig gebliebene Markdown-Platzhalter", () => {
|
||||||
|
const current = { PERSON_01: { original: "Alex Beispiel", type: "PERSON" } };
|
||||||
|
const older = [
|
||||||
|
{ PERSON_61: { original: "Mara Muster", type: "PERSON" }, PROJEKT_01: { original: "Projekt Eins", type: "PROJEKT" } },
|
||||||
|
{ PERSON_61: { original: "Mara Muster", type: "PERSON" }, PROJEKT_01: { original: "Projekt Zwei", type: "PROJEKT" } },
|
||||||
|
];
|
||||||
|
const mapping = project.withUnambiguousHistoricalMappings(current, older);
|
||||||
|
expect(mapping.PERSON_61?.original).toBe("Mara Muster");
|
||||||
|
expect(mapping.PROJEKT_01).toBeUndefined();
|
||||||
|
const restored = project.restoreText("PERSON_61 und PROJEKT_01", mapping, undefined, true);
|
||||||
|
expect(restored).toBe("Mara Muster und PROJEKT_01");
|
||||||
|
expect(project.unresolvedPlaceholderIds(restored, [current, ...older])).toEqual(["PROJEKT_01"]);
|
||||||
|
expect(project.isMarkdownFile("Notizen.MD")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("löst eine wiederverwendete ID nur über eine identische gespeicherte Datei auf", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-exact-snapshot-"));
|
||||||
|
roots.push(root);
|
||||||
|
const first = await project.createRun(join(root, "Quelle"), root);
|
||||||
|
const second = await project.createRun(join(root, "Quelle"), root);
|
||||||
|
const relPath = "Fragenliste.md";
|
||||||
|
first.run.files = [{ source: relPath, output: relPath, kind: "text" }];
|
||||||
|
second.run.files = [{ source: relPath, output: relPath, kind: "text" }];
|
||||||
|
first.run.mapping = {
|
||||||
|
PERSON_60: { original: "Alex Beispiel", type: "PERSON" },
|
||||||
|
PERSON_61: { original: "Hr. Beispiel", type: "PERSON", merged_into: "PERSON_60" },
|
||||||
|
};
|
||||||
|
second.run.mapping = { PERSON_61: { original: "Mara Muster", type: "PERSON" } };
|
||||||
|
const source = Buffer.from("Kommentar PERSON_61");
|
||||||
|
await fs.writeFile(join(first.directory, "files", relPath), source);
|
||||||
|
await fs.writeFile(join(second.directory, "files", relPath), "anderer Inhalt");
|
||||||
|
const exact = await project.mappingForMatchingSnapshots(relPath, project.digest(source), [first, second]);
|
||||||
|
expect(exact.PERSON_61?.original).toBe("Alex Beispiel");
|
||||||
|
const unknown = await project.mappingForMatchingSnapshots(relPath, project.digest(Buffer.from("neu")), [first, second]);
|
||||||
|
expect(unknown.PERSON_61).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ergänzt einen fehlenden Platzhalter in einem neuen Projektstand ohne alte Daten zu ändern", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-manual-mapping-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, root);
|
||||||
|
saved.run.mapping = { PERSON_01: { original: "Alex Beispiel", type: "PERSON" } };
|
||||||
|
saved.run.files = [{ source: "Notiz.md", output: "Notiz.md", kind: "text" }];
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "Notiz.md"), "PERSON_61");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const updated = await project.addProjectMappingEntry(source,
|
||||||
|
{ placeholder: "PERSON_61", original: "Mara Muster", type: "PERSON" }, root);
|
||||||
|
expect(updated.mapping.PERSON_61?.original).toBe("Mara Muster");
|
||||||
|
expect((await project.listRuns(source, root))[0].run.id).toBe(updated.id);
|
||||||
|
expect(await fs.readFile(join(saved.directory, "files", "Notiz.md"), "utf8")).toBe("PERSON_61");
|
||||||
|
expect((await project.listRuns(source, root))[1].run.mapping.PERSON_61).toBeUndefined();
|
||||||
|
expect(await fs.readFile(join(project.projectDataRoot(source, root), "runs", updated.id, "files", "Notiz.md"), "utf8"))
|
||||||
|
.toBe("PERSON_61");
|
||||||
|
expect(project.prepareManualMappingEntry(updated.mapping, [],
|
||||||
|
{ original: "Weiterer Begriff", type: "PERSON" }).placeholder).toBe("PERSON_62");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("speichert eine Gruppierung als neuen Projektstand und lässt frühere Dateien unverändert", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-group-mapping-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const saved = await project.createRun(source, root);
|
||||||
|
saved.run.mapping = {
|
||||||
|
PERSON_01: { original: "Franz Fuchs", type: "PERSON" },
|
||||||
|
PERSON_02: { original: "Hr. Fuchs", type: "PERSON" },
|
||||||
|
};
|
||||||
|
saved.run.files = [{ source: "Notiz.md", output: "Notiz.md", kind: "text" }];
|
||||||
|
await fs.writeFile(join(saved.directory, "files", "Notiz.md"), "PERSON_02");
|
||||||
|
await project.saveRun(saved.directory, saved.run);
|
||||||
|
const updated = await project.updateProjectMapping(source,
|
||||||
|
(mapping) => mergeMappingGroups(mapping, "PERSON_02", "PERSON_01"), root);
|
||||||
|
expect(updated.mapping.PERSON_02.merged_into).toBe("PERSON_01");
|
||||||
|
expect((await project.listRuns(source, root))[1].run.mapping.PERSON_02.merged_into).toBeUndefined();
|
||||||
|
expect(await fs.readFile(join(project.projectDataRoot(source, root), "runs", updated.id, "files", "Notiz.md"), "utf8"))
|
||||||
|
.toBe("PERSON_02");
|
||||||
|
expect(project.restoreText("PERSON_02", mappingForRestoration(updated.mapping))).toBe("Franz Fuchs");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verhindert eine neue projektweite Zuordnung für eine früher anders belegte ID", () => {
|
||||||
|
expect(() => project.prepareManualMappingEntry({}, [
|
||||||
|
{ PERSON_61: { original: "Alex Beispiel", type: "PERSON" } },
|
||||||
|
], { placeholder: "PERSON_61", original: "Mara Muster", type: "PERSON" }))
|
||||||
|
.toThrow("andere Bedeutung");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("übernimmt API-Trefferpositionen auch nach einem Emoji korrekt", () => {
|
||||||
|
const text = "😀 Max";
|
||||||
|
const spans = project.toUtf16Offsets(text, [{ id: "max", start: 2, end: 5, placeholder: "PERSON_01" }]);
|
||||||
|
expect(project.replaceSpans(text, spans, new Set(["max"]))).toBe("😀 PERSON_01");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ersetzt ausgewählte Projektdateien vor Ort und sichert die Originale außerhalb", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-in-place-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
await fs.writeFile(join(source, "Bericht.txt"), "Max Mustermann");
|
||||||
|
await fs.chmod(join(source, "Bericht.txt"), 0o640);
|
||||||
|
await fs.writeFile(join(source, "Unberührt.txt"), "bleibt");
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
await fs.writeFile(join(created.directory, "files", "PERSON_01.txt"), "PERSON_01");
|
||||||
|
const files: RunFile[] = [{ source: "Bericht.txt", output: "PERSON_01.txt", kind: "text" }];
|
||||||
|
await project.replaceProjectFilesInPlace(source, created.directory, files);
|
||||||
|
expect(await fs.readFile(join(source, "PERSON_01.txt"), "utf8")).toBe("PERSON_01");
|
||||||
|
expect((await fs.stat(join(source, "PERSON_01.txt"))).mode & 0o777).toBe(0o640);
|
||||||
|
expect(await fs.readFile(join(created.directory, "backup", "Bericht.txt"), "utf8")).toBe("Max Mustermann");
|
||||||
|
expect((await fs.stat(join(created.directory, "backup", "Bericht.txt"))).mode & 0o777).toBe(0o600);
|
||||||
|
expect(await fs.readFile(join(source, "Unberührt.txt"), "utf8")).toBe("bleibt");
|
||||||
|
await expect(fs.access(join(source, "Bericht.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ersetzt keine inzwischen erneut bearbeitete Projektdatei", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-in-place-guard-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
await fs.writeFile(join(source, "Notiz.md"), "neuer Stand");
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
await fs.writeFile(join(created.directory, "files", "Notiz.md"), "korrigierte Ausgabe");
|
||||||
|
await expect(project.replaceProjectFilesInPlace(source, created.directory,
|
||||||
|
[{ source: "Notiz.md", output: "Notiz.md", kind: "text" }],
|
||||||
|
new Map([["Notiz.md", project.digest(Buffer.from("alter Stand"))]])))
|
||||||
|
.rejects.toThrow("vor dem Ersetzen erneut geändert");
|
||||||
|
expect(await fs.readFile(join(source, "Notiz.md"), "utf8")).toBe("neuer Stand");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("verhindert Namenskollisionen vor dem Ersetzen", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-in-place-collision-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
await fs.writeFile(join(source, "Bericht.txt"), "Original");
|
||||||
|
await fs.writeFile(join(source, "PERSON_01.txt"), "Andere Datei");
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
await fs.writeFile(join(created.directory, "files", "PERSON_01.txt"), "Pseudonym");
|
||||||
|
await expect(project.replaceProjectFilesInPlace(source, created.directory,
|
||||||
|
[{ source: "Bericht.txt", output: "PERSON_01.txt", kind: "text" }])).rejects.toThrow("Zielname bereits vorhanden");
|
||||||
|
expect(await fs.readFile(join(source, "Bericht.txt"), "utf8")).toBe("Original");
|
||||||
|
expect(await fs.readFile(join(source, "PERSON_01.txt"), "utf8")).toBe("Andere Datei");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("erkennt unveränderte Ausgaben für einen erneuten Lauf desselben Ordners", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-repeat-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
const filename = "PERSON_01.txt";
|
||||||
|
await fs.writeFile(join(created.directory, "files", filename), "PERSON_01");
|
||||||
|
const current = join(source, filename);
|
||||||
|
await fs.writeFile(current, "PERSON_01");
|
||||||
|
const hash = project.digest(await fs.readFile(current));
|
||||||
|
expect(await project.matchesPreviousOutput(created.directory, filename, hash)).toBe(true);
|
||||||
|
await fs.writeFile(current, "PERSON_01 und neuer Text");
|
||||||
|
expect(await project.matchesPreviousOutput(created.directory, filename,
|
||||||
|
project.digest(await fs.readFile(current)))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("übernimmt unveränderte Quelldateien aus Kopien- und In-Place-Ständen ohne erneute Analyse", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-reuse-test-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const created = await project.createRun(source, support);
|
||||||
|
await fs.writeFile(join(created.directory, "files", "PERSON_01.txt"), "PERSON_01");
|
||||||
|
created.run.files = [{ source: "Name.txt", output: "PERSON_01.txt", kind: "text" }];
|
||||||
|
const originalHash = project.digest(Buffer.from("Max Mustermann"));
|
||||||
|
created.run.sourceState = { "Name.txt": { hash: originalHash, output: "PERSON_01.txt" } };
|
||||||
|
expect(await project.reusableProjectOutput(created.run, created.directory, "Name.txt", originalHash))
|
||||||
|
.toBe("PERSON_01.txt");
|
||||||
|
expect(await project.reusableProjectOutput(created.run, created.directory, "Name.txt",
|
||||||
|
project.digest(Buffer.from("Änderung")))).toBeUndefined();
|
||||||
|
created.run.sourceState = undefined;
|
||||||
|
created.run.inPlace = true;
|
||||||
|
created.run.files = [{ source: "Name.txt", output: "PERSON_01.txt", kind: "text" }];
|
||||||
|
expect(await project.reusableProjectOutput(created.run, created.directory, "PERSON_01.txt",
|
||||||
|
project.digest(Buffer.from("PERSON_01")))).toBe("PERSON_01.txt");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("analysiert unveränderte Dateien bei unbekannter oder geänderter Kategorieauswahl neu", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-category-coverage-"));
|
||||||
|
roots.push(root);
|
||||||
|
const source = join(root, "Quelle");
|
||||||
|
const support = join(root, "Raycast");
|
||||||
|
await fs.mkdir(source);
|
||||||
|
const { run } = await project.createRun(source, support);
|
||||||
|
expect(project.sameEntityTypeCoverage(run, ["EMAIL"])).toBe(false);
|
||||||
|
run.entityTypes = ["PERSON", "EMAIL"];
|
||||||
|
expect(project.sameEntityTypeCoverage(run, ["EMAIL", "PERSON"])).toBe(true);
|
||||||
|
expect(project.sameEntityTypeCoverage(run, ["PERSON"])).toBe(false);
|
||||||
|
expect(project.sameEntityTypeCoverage(run, ["PERSON", "EMAIL", "URL"])).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("erfasst große Textdateien weiterhin, behält aber die Office-Uploadgrenze", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-large-scan-")); roots.push(root);
|
||||||
|
for (const name of ["large.txt", "large.docx"]) {
|
||||||
|
const handle = await fs.open(join(root, name), "w"); await handle.truncate(21 * 1024 * 1024); await handle.close();
|
||||||
|
}
|
||||||
|
const result = await project.scanProjectFiles(root, undefined, false);
|
||||||
|
expect(result.files.map((file) => file.relPath)).toEqual(["large.txt"]);
|
||||||
|
expect(result.skipped).toEqual([{ path: "large.docx", reason: "Datei zu groß (Grenze: 20 MiB)" }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
it("offers large XLSX files for local restoration while keeping the upload limit for pseudonymization", async () => {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-large-xlsx-scan-")); roots.push(root);
|
||||||
|
const source = join(root, "source"); await fs.mkdir(source);
|
||||||
|
for (const name of ["large.xlsx", "large.docx"]) {
|
||||||
|
const handle = await fs.open(join(source, name), "w");
|
||||||
|
await handle.write(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
||||||
|
await handle.truncate(21 * 1024 * 1024); await handle.close();
|
||||||
|
}
|
||||||
|
const { run, directory } = await project.createRun(source, join(root, "support"));
|
||||||
|
run.inPlace = true;
|
||||||
|
const upload = await project.scanProjectFiles(source);
|
||||||
|
expect(upload.files).toHaveLength(0);
|
||||||
|
const restore = await project.scanRestorableCopyFiles(run, directory);
|
||||||
|
expect(restore.files.map((file) => file.relPath)).toEqual(["large.xlsx"]);
|
||||||
|
expect(restore.skipped).toBe(1);
|
||||||
|
});
|
||||||
119
tests/xlsx-restoration.test.ts
Normal file
119
tests/xlsx-restoration.test.ts
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
import { afterEach, expect, it } from "bun:test";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import { zipSync, unzipSync, strToU8, strFromU8 } from "fflate";
|
||||||
|
import { SaxesParser } from "saxes";
|
||||||
|
import { restoreXlsxFile } from "../src/lib/xlsx-restoration";
|
||||||
|
|
||||||
|
const S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
||||||
|
const roots: string[] = [];
|
||||||
|
afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
|
||||||
|
async function fixture(parts: Record<string, Uint8Array> = {}) {
|
||||||
|
const root = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-")); roots.push(root);
|
||||||
|
const source = join(root, "source.xlsx"), target = join(root, "restored.xlsx");
|
||||||
|
await fs.writeFile(source, zipSync({
|
||||||
|
"[Content_Types].xml": strToU8('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'),
|
||||||
|
"xl/workbook.xml": strToU8(`<workbook xmlns="${S}"><sheets><sheet name="PERSON_01" sheetId="1"/></sheets></workbook>`),
|
||||||
|
...parts,
|
||||||
|
}, { level: 0 }));
|
||||||
|
return { source, target };
|
||||||
|
}
|
||||||
|
function xmlTexts(xml: string): string[] {
|
||||||
|
const values: string[] = [];
|
||||||
|
const parser = new SaxesParser();
|
||||||
|
parser.on("text", (text) => values.push(text));
|
||||||
|
parser.write(xml).close();
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("restores placeholders across rich-text runs while preserving XML escaping and boundaries", async () => {
|
||||||
|
const { source, target } = await fixture({
|
||||||
|
"xl/sharedStrings.xml": strToU8(`<sst xmlns="${S}" count="2" uniqueCount="2"><si><r><t>PER</t></r><r><rPr><b/></rPr><t>SON_01</t></r></si><si><t>PERSON_010 PERSON_01 xPERSON_01 ÄPERSON_01 UNKNOWN_99</t></si></sst>`),
|
||||||
|
"xl/media/image1.png": Uint8Array.from([0, 42, 255]),
|
||||||
|
});
|
||||||
|
const before = await fs.readFile(source);
|
||||||
|
const result = await restoreXlsxFile(source, target, {
|
||||||
|
PERSON_01: { original: 'A & B <Müller> "😀"', type: "PERSON" },
|
||||||
|
PERSON_010: { original: "Anna", type: "PERSON" },
|
||||||
|
});
|
||||||
|
const parts = unzipSync(await fs.readFile(target));
|
||||||
|
expect(xmlTexts(strFromU8(parts["xl/sharedStrings.xml"]))).toEqual([
|
||||||
|
'A & B <Müller> "😀"', 'Anna A & B <Müller> "😀" xPERSON_01 ÄPERSON_01 UNKNOWN_99',
|
||||||
|
]);
|
||||||
|
expect(strFromU8(parts["xl/sharedStrings.xml"])).toContain("<b></b>");
|
||||||
|
expect(parts["xl/media/image1.png"]).toEqual(Uint8Array.from([0, 42, 255]));
|
||||||
|
expect(strFromU8(parts["xl/workbook.xml"])).toContain('name="A & B <Müller> "😀""');
|
||||||
|
expect(result.replacements).toBe(4);
|
||||||
|
expect(await fs.readFile(source)).toEqual(before);
|
||||||
|
expect((await fs.stat(target)).mode & 0o777).toBe(0o600);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("restores inline strings, formulas, comments, links and UTF-16 XML without changing numbers", async () => {
|
||||||
|
const xml = `<?xml version="1.0" encoding="UTF-16"?><worksheet xmlns="${S}"><sheetData><row><c r="A1" t="inlineStr"><is><t>PERSON_01</t></is></c><c r="B1"><f>"PERSON_01"</f><v>42</v></c></row></sheetData></worksheet>`;
|
||||||
|
const { source, target } = await fixture({
|
||||||
|
"xl/worksheets/sheet1.xml": Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(xml, "utf16le")]),
|
||||||
|
"xl/comments/comment1.xml": strToU8(`<comments xmlns="${S}"><authors><author>PERSON_01</author></authors></comments>`),
|
||||||
|
"xl/_rels/workbook.xml.rels": strToU8('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r1" Target="https://example.test/PERSON_01" TargetMode="External"/></Relationships>'),
|
||||||
|
});
|
||||||
|
await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } });
|
||||||
|
const parts = unzipSync(await fs.readFile(target));
|
||||||
|
expect(xmlTexts(strFromU8(parts["xl/worksheets/sheet1.xml"]))).toEqual(["Anna Berger", '"Anna Berger"', "42"]);
|
||||||
|
expect(xmlTexts(strFromU8(parts["xl/comments/comment1.xml"]))).toEqual(["Anna Berger"]);
|
||||||
|
expect(strFromU8(parts["xl/_rels/workbook.xml.rels"])).toContain('Target="https://example.test/Anna Berger"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports compressed workbooks above the API's 20 MiB upload limit", async () => {
|
||||||
|
const binary = randomBytes(21 * 1024 * 1024);
|
||||||
|
const { source, target } = await fixture({
|
||||||
|
"xl/media/opaque.bin": binary,
|
||||||
|
"xl/sharedStrings.xml": strToU8(`<sst xmlns="${S}">` + '<si><t>PERSON_6001</t></si>'.repeat(170_000) + '</sst>'),
|
||||||
|
});
|
||||||
|
const mapping = Object.fromEntries(Array.from({ length: 6001 }, (_, i) => [`PERSON_${String(i + 1).padStart(2, "0")}`, { original: `Name ${i + 1}`, type: "PERSON" }]));
|
||||||
|
const result = await restoreXlsxFile(source, target, mapping);
|
||||||
|
expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024);
|
||||||
|
expect(result.replacements).toBe(170_001);
|
||||||
|
const parts = unzipSync(await fs.readFile(target));
|
||||||
|
expect(parts["xl/media/opaque.bin"]).toEqual(new Uint8Array(binary));
|
||||||
|
const restored = strFromU8(parts["xl/sharedStrings.xml"]);
|
||||||
|
expect(restored.match(/Name 6001/g)).toHaveLength(170_000);
|
||||||
|
expect(restored).not.toContain("PERSON_6001");
|
||||||
|
}, 60_000);
|
||||||
|
|
||||||
|
it("removes incomplete outputs on malformed XML, DTDs and damaged ZIP payloads", async () => {
|
||||||
|
for (const xml of ['<bad>', '<!DOCTYPE sst [<!ENTITY x "test">]><sst>&x;</sst>']) {
|
||||||
|
const { source, target } = await fixture({ "xl/sharedStrings.xml": strToU8(xml) });
|
||||||
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow();
|
||||||
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||||
|
}
|
||||||
|
const { source, target } = await fixture({ "xl/data.bin": strToU8("UNIQUE_PAYLOAD") });
|
||||||
|
const data = await fs.readFile(source);
|
||||||
|
data[data.indexOf("UNIQUE_PAYLOAD")] ^= 1;
|
||||||
|
await fs.writeFile(source, data);
|
||||||
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("CRC");
|
||||||
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not overwrite an existing target or accept a truncated archive", async () => {
|
||||||
|
const { source, target } = await fixture();
|
||||||
|
await fs.writeFile(target, "keep this file");
|
||||||
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow();
|
||||||
|
expect(await fs.readFile(target, "utf8")).toBe("keep this file");
|
||||||
|
await fs.rm(target);
|
||||||
|
const data = await fs.readFile(source);
|
||||||
|
await fs.writeFile(source, data.subarray(0, data.length - 30));
|
||||||
|
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("ZIP");
|
||||||
|
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
it("restores split placeholders in DrawingML text boxes and keeps run formatting", async () => {
|
||||||
|
const { source, target } = await fixture({
|
||||||
|
"xl/drawings/drawing1.xml": strToU8('<a:shape xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:p><a:r><a:rPr b="1"/><a:t>PER</a:t></a:r><a:r><a:t>SON_01</a:t></a:r></a:p></a:shape>'),
|
||||||
|
});
|
||||||
|
await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } });
|
||||||
|
const drawing = strFromU8(unzipSync(await fs.readFile(target))["xl/drawings/drawing1.xml"]);
|
||||||
|
expect(xmlTexts(drawing)).toEqual(["Anna Berger"]);
|
||||||
|
expect(drawing).toContain('b="1"');
|
||||||
|
});
|
||||||
292
tools/migrate-ki-datenschutz.mjs
Normal file
292
tools/migrate-ki-datenschutz.mjs
Normal file
@@ -0,0 +1,292 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/** One-time, standalone converter. It is not imported by the Raycast extension. */
|
||||||
|
import { createHash, randomUUID } from "node:crypto";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const styles = ["typed", "title", "lower", "upper", "camel", "pascal", "kebab",
|
||||||
|
"kebabUpper", "snake", "snakeUpper", "flat", "flatUpper", "camelKeep", "pascalKeep"];
|
||||||
|
const excluded = new Set([".git", "node_modules", "dist", "build", "out", ".next", ".nuxt",
|
||||||
|
".venv", "venv", "__pycache__", "target", "vendor", "coverage", ".cache", ".turbo",
|
||||||
|
".idea", ".vscode", "Pods", "DerivedData"]);
|
||||||
|
const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
// In URL-kodierten Dateinamen steht nach %2f unmittelbar ein "f" vor dem Platzhalter.
|
||||||
|
// Das ist ein Pfadtrenner, kein angrenzender Buchstabe des Bezeichners.
|
||||||
|
const strictPrefix = "(?:(?<![\\p{L}\\p{N}])|(?<=%2[fF]))";
|
||||||
|
const hasSeparator = (value) => /[^\p{L}\p{N}]/u.test(value);
|
||||||
|
const shape = (value) => !/\p{L}/u.test(value) ? "mixed"
|
||||||
|
: value === value.toUpperCase() ? "upper" : value === value.toLowerCase() ? "lower" : "mixed";
|
||||||
|
|
||||||
|
function canonical(pairs, attached) {
|
||||||
|
const sameShape = pairs.filter((pair) => hasSeparator(pair.termVariant) === hasSeparator(pairs[0].placeholderVariant));
|
||||||
|
const candidates = sameShape.length ? sameShape : pairs;
|
||||||
|
const wantedShape = shape(pairs[0].placeholderVariant);
|
||||||
|
return [...candidates].sort((a, b) => {
|
||||||
|
const preferred = Number((b.style === "typed") === !attached) - Number((a.style === "typed") === !attached);
|
||||||
|
if (preferred) return preferred;
|
||||||
|
const casing = Number(shape(b.termVariant) === wantedShape) - Number(shape(a.termVariant) === wantedShape);
|
||||||
|
return casing || styles.indexOf(a.style) - styles.indexOf(b.style);
|
||||||
|
})[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
function category(type) {
|
||||||
|
return ({ Person: "PERSON", Firma: "FIRMA", Kunde: "KUNDE", System: "BEGRIFF",
|
||||||
|
Sonstiges: "BEGRIFF" })[type] ?? "BEGRIFF";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createConverter(manifest, globalTerms = []) {
|
||||||
|
if (manifest.version !== 1 || !Array.isArray(manifest.variantTable)) {
|
||||||
|
throw new Error("Unbekanntes Tabellenformat.");
|
||||||
|
}
|
||||||
|
const terms = new Map([...globalTerms, ...(manifest.projectTerms ?? [])].map((term) => [term.id, term]));
|
||||||
|
const groups = new Map();
|
||||||
|
for (const pair of manifest.variantTable) {
|
||||||
|
if (typeof pair.placeholderVariant !== "string" || typeof pair.termVariant !== "string"
|
||||||
|
|| !pair.placeholderVariant || !pair.termVariant || typeof pair.termId !== "string") {
|
||||||
|
throw new Error("Ungültiger Eintrag in der alten Variante-Tabelle.");
|
||||||
|
}
|
||||||
|
const bucket = groups.get(pair.placeholderVariant) ?? [];
|
||||||
|
bucket.push(pair);
|
||||||
|
groups.set(pair.placeholderVariant, bucket);
|
||||||
|
}
|
||||||
|
const needles = [...groups].map(([needle, pairs]) => ({
|
||||||
|
needle, pairs, strict: pairs.every((pair) => pair.boundary === "strict"),
|
||||||
|
})).sort((a, b) => b.needle.length - a.needle.length || a.needle.localeCompare(b.needle));
|
||||||
|
const lookup = new Map(needles.map((item) => [item.needle, item]));
|
||||||
|
const pattern = needles.length ? new RegExp(needles.map((item) => item.strict
|
||||||
|
? `${strictPrefix}${escapeRegex(item.needle)}(?![\\p{L}\\p{N}])`
|
||||||
|
: escapeRegex(item.needle)).join("|"), "gu") : null;
|
||||||
|
const mapping = {};
|
||||||
|
const matchModes = {};
|
||||||
|
const allocated = new Map();
|
||||||
|
const counters = new Map();
|
||||||
|
let replacements = 0;
|
||||||
|
|
||||||
|
function convert(input, onReplacement) {
|
||||||
|
if (!pattern) return input;
|
||||||
|
pattern.lastIndex = 0;
|
||||||
|
return input.replace(pattern, (matched, offset, whole) => {
|
||||||
|
const item = lookup.get(matched);
|
||||||
|
if (!item) return matched;
|
||||||
|
const before = offset > 0 ? whole[offset - 1] : "";
|
||||||
|
const after = whole[offset + matched.length] ?? "";
|
||||||
|
const attached = /[\p{L}\p{N}_-]/u.test(before) || /[\p{L}\p{N}_-]/u.test(after);
|
||||||
|
const chosen = canonical(item.pairs, attached);
|
||||||
|
const type = category(terms.get(chosen.termId)?.category);
|
||||||
|
const key = `${matched}\0${attached ? "attached" : "standalone"}`;
|
||||||
|
let placeholder = allocated.get(key);
|
||||||
|
if (!placeholder) {
|
||||||
|
// Keep imported identifiers clear of ordinary low-numbered Velum IDs.
|
||||||
|
let number = counters.get(type) ?? 100000;
|
||||||
|
do { number += 1; placeholder = `${type}_${String(number).padStart(2, "0")}`; }
|
||||||
|
while (groups.has(placeholder) || mapping[placeholder]);
|
||||||
|
counters.set(type, number);
|
||||||
|
if (Object.keys(mapping).length >= 5000) throw new Error("Mehr als 5.000 neue Platzhalter.");
|
||||||
|
mapping[placeholder] = { original: chosen.termVariant, type };
|
||||||
|
matchModes[placeholder] = attached ? "anywhere" : "token";
|
||||||
|
allocated.set(key, placeholder);
|
||||||
|
}
|
||||||
|
replacements += 1;
|
||||||
|
onReplacement?.(matched, placeholder);
|
||||||
|
return placeholder;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { convert, mapping, matchModes, get replacements() { return replacements; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeRelative(path) {
|
||||||
|
const value = path.split("\\").join("/");
|
||||||
|
if (!value || value.startsWith("/") || value.split("/").some((part) => !part || part === "." || part === "..")) {
|
||||||
|
throw new Error("Ungültiger relativer Pfad.");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function filesUnder(root) {
|
||||||
|
const files = [];
|
||||||
|
const skippedFiles = [];
|
||||||
|
const skip = (path, reason) => skippedFiles.push({ path: relative(root, path).split(sep).join("/"), reason });
|
||||||
|
async function walk(dir) {
|
||||||
|
for (const entry of (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
||||||
|
const path = join(dir, entry.name);
|
||||||
|
if (entry.isSymbolicLink()) { skip(path, "Symbolischer Link"); continue; }
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
if (excluded.has(entry.name)) { skip(path, "Ausgeschlossener Ordner"); continue; }
|
||||||
|
await walk(path);
|
||||||
|
} else if (entry.isFile()) {
|
||||||
|
if (entry.name === ".aishield.json") { skip(path, "Alte Projektmetadaten"); continue; }
|
||||||
|
if (entry.name === ".env" || entry.name.startsWith(".env.") ||
|
||||||
|
[".pem", ".key", ".p12", ".pfx"].includes(extname(entry.name).toLowerCase())) {
|
||||||
|
skip(path, "Vertrauliche Konfigurations- oder Schlüsseldatei");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
files.push({ abs: path, rel: relative(root, path).split(sep).join("/") });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await walk(root);
|
||||||
|
return { files, skippedFiles };
|
||||||
|
}
|
||||||
|
|
||||||
|
function convertedPath(rel, convert) {
|
||||||
|
return safeRelative(rel.split("/").map(convert).join("/"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function replacementList(counts) {
|
||||||
|
return [...counts.values()].sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to));
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportText(summary, converted, skippedFiles) {
|
||||||
|
const quoted = (value) => JSON.stringify(value);
|
||||||
|
const lines = [
|
||||||
|
"# Migrationsvorschau für Velum", "",
|
||||||
|
"Diese Vorschau wurde ohne Übernahme erstellt. Sie enthält alte und neue Platzhalter, aber keine Klartextwerte aus der Zuordnungstabelle.", "",
|
||||||
|
`Dateien: ${summary.files} · Ausgelassen: ${summary.skipped} · Ersetzungen: ${summary.replacements} · Neue Platzhalter: ${summary.placeholders}`, "",
|
||||||
|
"## Dateien", "",
|
||||||
|
];
|
||||||
|
for (const file of converted) {
|
||||||
|
lines.push(`- Quelle: ${quoted(file.source)}`);
|
||||||
|
if (file.source !== file.output) lines.push(` Zielname: ${quoted(file.output)}`);
|
||||||
|
const pathReplacements = replacementList(file.pathReplacements);
|
||||||
|
const contentReplacements = replacementList(file.contentReplacements);
|
||||||
|
if (!pathReplacements.length && !contentReplacements.length) lines.push(" Keine Änderung.");
|
||||||
|
for (const [label, entries] of [["Name", pathReplacements], ["Inhalt", contentReplacements]]) {
|
||||||
|
for (const entry of entries) lines.push(` ${label}: ${quoted(entry.from)} → ${quoted(entry.to)} (${entry.count}×)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!converted.length) lines.push("Keine übernehmbaren Dateien.");
|
||||||
|
lines.push("", "## Ausgelassen", "");
|
||||||
|
for (const item of skippedFiles) lines.push(`- ${quoted(item.path)}: ${item.reason}`);
|
||||||
|
if (!skippedFiles.length) lines.push("Keine.");
|
||||||
|
return lines.join("\n") + "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function migrate({ project, manifestFile, targetSupport, apply = false, previewFile }) {
|
||||||
|
const root = resolve(project);
|
||||||
|
if (apply && previewFile) throw new Error("Vorschau-Datei und --apply bitte in getrennten Aufrufen verwenden.");
|
||||||
|
if (previewFile && (resolve(previewFile) === root || resolve(previewFile).startsWith(root + sep))) {
|
||||||
|
throw new Error("Die Vorschau-Datei muss außerhalb des Projektordners liegen.");
|
||||||
|
}
|
||||||
|
if (previewFile) {
|
||||||
|
const realRoot = await fs.realpath(root);
|
||||||
|
const realPreviewParent = await fs.realpath(dirname(resolve(previewFile)));
|
||||||
|
if (realPreviewParent === realRoot || realPreviewParent.startsWith(realRoot + sep)) {
|
||||||
|
throw new Error("Die Vorschau-Datei muss außerhalb des Projektordners liegen.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (resolve(targetSupport) === root || resolve(targetSupport).startsWith(root + sep)) {
|
||||||
|
throw new Error("Der Velum-Datenordner muss außerhalb des Projektordners liegen.");
|
||||||
|
}
|
||||||
|
const manifest = JSON.parse(await fs.readFile(resolve(manifestFile), "utf8"));
|
||||||
|
if (resolve(manifest.projectPath) !== root) throw new Error("Tabelle und Projektordner gehören nicht zusammen.");
|
||||||
|
let globalTerms = [];
|
||||||
|
try {
|
||||||
|
const termFile = join(dirname(dirname(resolve(manifestFile))), "terms.json");
|
||||||
|
globalTerms = JSON.parse(await fs.readFile(termFile, "utf8")).terms ?? [];
|
||||||
|
} catch (error) {
|
||||||
|
if ((error).code !== "ENOENT") throw error;
|
||||||
|
}
|
||||||
|
const converter = createConverter(manifest, globalTerms);
|
||||||
|
const scan = await filesUnder(root);
|
||||||
|
const converted = [];
|
||||||
|
const seen = new Set();
|
||||||
|
const skippedFiles = [...scan.skippedFiles];
|
||||||
|
const skip = (file, reason) => skippedFiles.push({ path: file.rel, reason });
|
||||||
|
const track = (counts) => (from, to) => {
|
||||||
|
const key = `${from}\0${to}`;
|
||||||
|
const entry = counts.get(key) ?? { from, to, count: 0 };
|
||||||
|
entry.count += 1;
|
||||||
|
counts.set(key, entry);
|
||||||
|
};
|
||||||
|
for (const file of scan.files) {
|
||||||
|
if ([".docx", ".xlsx", ".pptx", ".pdf"].includes(extname(file.rel).toLowerCase())) {
|
||||||
|
skip(file, "Office- oder PDF-Datei");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bytes = await fs.readFile(file.abs);
|
||||||
|
if (bytes.includes(0)) { skip(file, "Binärdatei"); continue; }
|
||||||
|
let text;
|
||||||
|
try { text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
|
||||||
|
catch { skip(file, "Kein gültiger UTF-8-Text"); continue; }
|
||||||
|
const pathReplacements = new Map();
|
||||||
|
const contentReplacements = new Map();
|
||||||
|
const output = convertedPath(file.rel, (part) => converter.convert(part, track(pathReplacements)));
|
||||||
|
if (seen.has(output)) throw new Error("Zwei Dateien hätten denselben Zielnamen.");
|
||||||
|
seen.add(output);
|
||||||
|
converted.push({ source: file.rel, output, content: converter.convert(text, track(contentReplacements)),
|
||||||
|
kind: "text", pathReplacements, contentReplacements });
|
||||||
|
}
|
||||||
|
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`;
|
||||||
|
const projectId = createHash("sha1").update(root.replace(/\/+$/, "")).digest("hex").slice(0, 16);
|
||||||
|
const projectData = join(resolve(targetSupport), "velum-projects", projectId);
|
||||||
|
const runDir = join(projectData, "runs", id);
|
||||||
|
const run = {
|
||||||
|
version: 2, origin: "imported", id, projectPath: root, projectName: basename(root), createdAt: new Date().toISOString(),
|
||||||
|
mapping: converter.mapping, matchModes: converter.matchModes,
|
||||||
|
files: converted.map(({ source, output, kind }) => ({ source, output, kind })),
|
||||||
|
};
|
||||||
|
const summary = { files: converted.length, skipped: skippedFiles.length, replacements: converter.replacements,
|
||||||
|
placeholders: Object.keys(converter.mapping).length };
|
||||||
|
if (!apply) {
|
||||||
|
if (previewFile) {
|
||||||
|
await fs.writeFile(resolve(previewFile), reportText(summary, converted, skippedFiles),
|
||||||
|
{ encoding: "utf8", flag: "wx", mode: 0o600 });
|
||||||
|
}
|
||||||
|
return { summary, applied: false, previewFile: previewFile && resolve(previewFile) };
|
||||||
|
}
|
||||||
|
const stage = join(projectData, `.${id}.staging`);
|
||||||
|
await fs.mkdir(join(stage, "files"), { recursive: true, mode: 0o700 });
|
||||||
|
let committed = false;
|
||||||
|
try {
|
||||||
|
for (const file of converted) {
|
||||||
|
const dest = resolve(stage, "files", file.output);
|
||||||
|
if (!dest.startsWith(resolve(stage, "files") + sep)) throw new Error("Zielpfad außerhalb des Projektstands.");
|
||||||
|
await fs.mkdir(dirname(dest), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.writeFile(dest, file.content, { encoding: "utf8", mode: 0o600 });
|
||||||
|
}
|
||||||
|
await fs.writeFile(join(stage, "run.json"), JSON.stringify(run), { encoding: "utf8", mode: 0o600 });
|
||||||
|
await fs.mkdir(dirname(runDir), { recursive: true, mode: 0o700 });
|
||||||
|
await fs.rename(stage, runDir);
|
||||||
|
committed = true;
|
||||||
|
const projectRules = (manifest.projectTerms ?? []).filter((term) => term.enabled).flatMap((term) => {
|
||||||
|
const type = category(term.category);
|
||||||
|
return [term.term, ...(term.aliases ?? []).map((alias) => alias.text)].map((value) => ({ type, value }));
|
||||||
|
});
|
||||||
|
const rulesFile = join(projectData, "rules.json");
|
||||||
|
try { await fs.writeFile(rulesFile, JSON.stringify(projectRules), { encoding: "utf8", flag: "wx", mode: 0o600 }); }
|
||||||
|
catch (error) { if (error.code !== "EEXIST") throw error; }
|
||||||
|
} catch (error) {
|
||||||
|
await fs.rm(stage, { recursive: true, force: true });
|
||||||
|
if (committed) await fs.rm(runDir, { recursive: true, force: true });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return { summary, applied: true, runDir };
|
||||||
|
}
|
||||||
|
|
||||||
|
function option(args, name) {
|
||||||
|
const index = args.indexOf(name);
|
||||||
|
return index < 0 ? undefined : args[index + 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const project = option(args, "--project");
|
||||||
|
const manifestFile = option(args, "--manifest");
|
||||||
|
const targetSupport = option(args, "--target-support");
|
||||||
|
const previewFile = option(args, "--preview-file");
|
||||||
|
if (!project || !manifestFile || !targetSupport ||
|
||||||
|
(args.includes("--preview-file") && (!previewFile || previewFile.startsWith("--")))) {
|
||||||
|
process.stderr.write("Aufruf: node tools/migrate-ki-datenschutz.mjs --project <Ordner> --manifest <alte Tabelle.json> --target-support <Velum-Datenordner> [--preview-file <Bericht.md> | --apply]\n");
|
||||||
|
process.exitCode = 2;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const result = await migrate({ project, manifestFile, targetSupport, previewFile, apply: args.includes("--apply") });
|
||||||
|
process.stdout.write(`${result.applied ? "Import erstellt" : "Vorschau"}: ${result.summary.files} Dateien, ${result.summary.skipped} übersprungen, ${result.summary.replacements} Ersetzungen, ${result.summary.placeholders} neue Platzhalter.\n`);
|
||||||
|
if (result.previewFile) process.stdout.write(`Bericht: ${result.previewFile}\n`);
|
||||||
|
} catch (error) {
|
||||||
|
process.stderr.write(`Migration fehlgeschlagen: ${error.message}\n`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user