iobroker.e-invoices 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -420,7 +420,7 @@ for example a NAS, over **SFTP**. The adapter opens the SSH connection itself: n
420
420
  3. Press *Test connection*: the adapter logs in, creates the directory, writes and deletes a small test file, and
421
421
  shows the **fingerprint** of the server. Enter that fingerprint in the settings to trust only this server — a
422
422
  different server is then refused before the password is sent. Without a fingerprint the copy works too, but
423
- the server is not verified (the log says so once, with the fingerprint).
423
+ the server is not verified (the log warns at every copy, with the fingerprint).
424
424
 
425
425
  How it behaves:
426
426
 
@@ -428,7 +428,9 @@ How it behaves:
428
428
  `info.remoteBackupError`, and the backup page tells it. A failed copy is **not retried**: the next backup is
429
429
  copied again, as it contains everything.
430
430
  - A copy appears under its final name only when it is complete (it is uploaded as `.part`, its size is checked and
431
- it is renamed). The whole copy is limited to ten minutes.
431
+ it is renamed). The whole copy is limited to ten minutes. A half file of a failed upload is removed at once
432
+ when the connection still works; otherwise the next good copy removes it (only `e-invoices-auto-….zip.part` and
433
+ `e-invoices-backup-….zip.part`, nothing else).
432
434
  - *Copies to keep on the server* deletes the oldest **automatic** copies beyond that number (0 = keep all). Backups
433
435
  made by hand and every other file in the directory are never deleted.
434
436
  - Only password login is supported. The ZIP is **not encrypted** (see *Security notes*): the transfer is, the file
@@ -608,6 +610,16 @@ validation and hybrid embedding, `pdfkit`, `exceljs`, `jszip`,
608
610
  Placeholder for the next version (at the beginning of the line):
609
611
  ### **WORK IN PROGRESS**
610
612
  -->
613
+ ### 1.2.1 (2026-10-12)
614
+
615
+ * (alex) A half uploaded file (`….zip.part`) of a failed copy is removed on the server: at once when the connection still works, otherwise by the next good copy. Only half files of this adapter are touched.
616
+ * (alex) fix: *Test connection* uses the saved password only for the saved server and user, so no script can have the password sent to a server of its own.
617
+ * (alex) fix: when the time limit runs out while the connection is still being made, the late connection is closed at once instead of uploading after the failure was reported.
618
+ * (alex) fix: a failed state update can no longer turn a successful backup into an error of the API; an old copy error is cleared when the copy is switched off.
619
+ * (alex) fix: a restored attachment takes its size from its content, not from `dump.json`.
620
+ * (alex) The admin labels "Host" and "Password" of the external backup are worded so every language has its own text.
621
+ * (alex) fix: the time limit of the copy to the external server uses the timers of the adapter (`this.setTimeout`) instead of the plain `setTimeout` of Node.js (repository checker E5005).
622
+
611
623
  ### 1.2.0 (2026-10-12)
612
624
 
613
625
  * (alex) **Copy of the backups to an external server over SFTP:** the new tab *External backup* in the instance settings copies every backup (automatic and by hand) to another computer, for example a Synology NAS. Pure SFTP without mount, `sudo` or shell command; password stored encrypted; optional host key fingerprint; *Test connection* button; a failed copy never touches the local backup and is shown in the log, in `info.remoteBackupError` and on the backup page. Optionally the oldest automatic copies on the server are deleted (only files of this adapter).
@@ -629,10 +641,6 @@ validation and hybrid embedding, `pdfkit`, `exceljs`, `jszip`,
629
641
  * (alex) The objects of the adapter (info and control states, the file storage) carry their names in all eleven ioBroker languages; an existing installation gets the new names on the next start.
630
642
  * (alex) fix: the control buttons (`control.createDraft`, `issue`, `refresh`, `backup`, `restore`) act on the value `true` only. Writing `false` or another value no longer starts an issue, a backup or a restore.
631
643
 
632
- ### 1.1.2 (2026-10-11)
633
-
634
- * (alex) Documentation in English: the documents in `docs/` are now in `docs/en/` (validation evidence, disclaimer, performance), the German originals in `docs/de/`, as the ioBroker reviewers ask for. The English validation document is up to date (13 sample cases, XRechnung, warnings fail the run); a test keeps German out of `docs/en/` and pairs every German file with an English one.
635
-
636
644
  Older changes: see [CHANGELOG_OLD.md](CHANGELOG_OLD.md).
637
645
 
638
646
  ## License
@@ -63,11 +63,11 @@
63
63
  "External backup": "Externes Backup",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Jedes Backup wird zusätzlich per SFTP auf einen anderen Rechner kopiert (zum Beispiel eine Synology NAS), damit es den Ausfall dieses Rechners übersteht. Verwenden Sie einen Benutzer, der nur in das Zielverzeichnis schreiben darf, keinen Administrator. Die Kopie braucht weder einen Mount noch sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Backups auf einen externen Server kopieren (SFTP)",
66
- "Host": "Host",
66
+ "Server address": "Serveradresse",
67
67
  "IP address or host name of the server": "IP-Adresse oder Hostname des Servers",
68
68
  "SSH port": "SSH-Port",
69
69
  "User name": "Benutzername",
70
- "Password": "Passwort",
70
+ "Password of the user": "Passwort des Benutzers",
71
71
  "Directory on the server": "Verzeichnis auf dem Server",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "z. B. /backups/e-invoices, wird bei Bedarf angelegt",
73
73
  "Server fingerprint (optional)": "Fingerabdruck des Servers (optional)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "External backup",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Copy backups to an external server (SFTP)",
66
- "Host": "Host",
66
+ "Server address": "Server address",
67
67
  "IP address or host name of the server": "IP address or host name of the server",
68
68
  "SSH port": "SSH port",
69
69
  "User name": "User name",
70
- "Password": "Password",
70
+ "Password of the user": "Password of the user",
71
71
  "Directory on the server": "Directory on the server",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "e.g. /backups/e-invoices, created when it is missing",
73
73
  "Server fingerprint (optional)": "Server fingerprint (optional)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Copia externa",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Cada copia de seguridad se copia además por SFTP a otro ordenador (por ejemplo, un NAS Synology) para sobrevivir a la pérdida de este equipo. Use un usuario que solo pueda escribir en la carpeta de destino, no un administrador. La copia no necesita ni montaje ni sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Copiar las copias de seguridad a un servidor externo (SFTP)",
66
- "Host": "Host",
66
+ "Server address": "Dirección del servidor",
67
67
  "IP address or host name of the server": "Dirección IP o nombre de host del servidor",
68
68
  "SSH port": "Puerto SSH",
69
69
  "User name": "Nombre de usuario",
70
- "Password": "Contraseña",
70
+ "Password of the user": "Contraseña del usuario",
71
71
  "Directory on the server": "Carpeta en el servidor",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "p. ej. /backups/e-invoices, se crea si falta",
73
73
  "Server fingerprint (optional)": "Huella del servidor (opcional)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Sauvegarde externe",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Chaque sauvegarde est aussi copiée par SFTP vers un autre ordinateur (par exemple un NAS Synology), afin de survivre à la perte de cet hôte. Utilisez un utilisateur qui ne peut écrire que dans le dossier cible, pas un administrateur. La copie n'a besoin ni de montage ni de sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Copier les sauvegardes vers un serveur externe (SFTP)",
66
- "Host": "Hôte",
66
+ "Server address": "Adresse du serveur",
67
67
  "IP address or host name of the server": "Adresse IP ou nom d'hôte du serveur",
68
68
  "SSH port": "Port SSH",
69
69
  "User name": "Nom d'utilisateur",
70
- "Password": "Mot de passe",
70
+ "Password of the user": "Mot de passe de l'utilisateur",
71
71
  "Directory on the server": "Dossier sur le serveur",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "p. ex. /backups/e-invoices, créé s'il manque",
73
73
  "Server fingerprint (optional)": "Empreinte du serveur (facultatif)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Backup esterno",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Ogni backup viene copiato anche via SFTP su un altro computer (ad esempio un NAS Synology), così sopravvive alla perdita di questo host. Usate un utente che può scrivere solo nella cartella di destinazione, non un amministratore. La copia non richiede né un mount né sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Copia i backup su un server esterno (SFTP)",
66
- "Host": "Host",
66
+ "Server address": "Indirizzo del server",
67
67
  "IP address or host name of the server": "Indirizzo IP o nome host del server",
68
68
  "SSH port": "Porta SSH",
69
69
  "User name": "Nome utente",
70
- "Password": "Password",
70
+ "Password of the user": "Password dell'utente",
71
71
  "Directory on the server": "Cartella sul server",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "ad es. /backups/e-invoices, creata se manca",
73
73
  "Server fingerprint (optional)": "Impronta del server (facoltativa)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Externe back-up",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Elke back-up wordt ook via SFTP naar een andere computer gekopieerd (bijvoorbeeld een Synology NAS), zodat hij het verlies van deze host overleeft. Gebruik een gebruiker die alleen in de doelmap mag schrijven, geen beheerder. Voor de kopie zijn geen mount en geen sudo nodig.",
65
65
  "Copy backups to an external server (SFTP)": "Back-ups naar een externe server kopiëren (SFTP)",
66
- "Host": "Host",
66
+ "Server address": "Serveradres",
67
67
  "IP address or host name of the server": "IP-adres of hostnaam van de server",
68
68
  "SSH port": "SSH-poort",
69
69
  "User name": "Gebruikersnaam",
70
- "Password": "Wachtwoord",
70
+ "Password of the user": "Wachtwoord van de gebruiker",
71
71
  "Directory on the server": "Map op de server",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "bijv. /backups/e-invoices, wordt aangemaakt als die ontbreekt",
73
73
  "Server fingerprint (optional)": "Vingerafdruk van de server (optioneel)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Zewnętrzna kopia",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Każda kopia zapasowa jest dodatkowo kopiowana przez SFTP na inny komputer (na przykład NAS Synology), aby przetrwała utratę tego hosta. Użyj użytkownika, który może zapisywać tylko w folderze docelowym, a nie administratora. Kopiowanie nie wymaga ani montowania, ani sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Kopiuj kopie zapasowe na serwer zewnętrzny (SFTP)",
66
- "Host": "Host",
66
+ "Server address": "Adres serwera",
67
67
  "IP address or host name of the server": "Adres IP lub nazwa hosta serwera",
68
68
  "SSH port": "Port SSH",
69
69
  "User name": "Nazwa użytkownika",
70
- "Password": "Hasło",
70
+ "Password of the user": "Hasło użytkownika",
71
71
  "Directory on the server": "Folder na serwerze",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "np. /backups/e-invoices, tworzony w razie braku",
73
73
  "Server fingerprint (optional)": "Odcisk palca serwera (opcjonalnie)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Cópia externa",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Cada cópia de segurança é também copiada por SFTP para outro computador (por exemplo, um NAS Synology), para sobreviver à perda deste anfitrião. Utilize um utilizador que só possa escrever na pasta de destino, não um administrador. A cópia não precisa de montagem nem de sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Copiar as cópias de segurança para um servidor externo (SFTP)",
66
- "Host": "Anfitrião",
66
+ "Server address": "Endereço do servidor",
67
67
  "IP address or host name of the server": "Endereço IP ou nome do anfitrião do servidor",
68
68
  "SSH port": "Porta SSH",
69
69
  "User name": "Nome de utilizador",
70
- "Password": "Palavra-passe",
70
+ "Password of the user": "Palavra-passe do utilizador",
71
71
  "Directory on the server": "Pasta no servidor",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "p. ex. /backups/e-invoices, criada se não existir",
73
73
  "Server fingerprint (optional)": "Impressão digital do servidor (opcional)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Внешняя копия",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Каждая резервная копия дополнительно копируется по SFTP на другой компьютер (например, на NAS Synology), чтобы пережить потерю этого узла. Используйте пользователя, которому разрешено писать только в целевой каталог, а не администратора. Для копирования не нужны ни монтирование, ни sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Копировать резервные копии на внешний сервер (SFTP)",
66
- "Host": "Хост",
66
+ "Server address": "Адрес сервера",
67
67
  "IP address or host name of the server": "IP-адрес или имя хоста сервера",
68
68
  "SSH port": "Порт SSH",
69
69
  "User name": "Имя пользователя",
70
- "Password": "Пароль",
70
+ "Password of the user": "Пароль пользователя",
71
71
  "Directory on the server": "Каталог на сервере",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "например, /backups/e-invoices, создаётся при отсутствии",
73
73
  "Server fingerprint (optional)": "Отпечаток сервера (необязательно)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "Зовнішня копія",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "Кожна резервна копія додатково копіюється через SFTP на інший комп'ютер (наприклад, NAS Synology), щоб пережити втрату цього вузла. Використовуйте користувача, якому дозволено писати лише в цільову теку, а не адміністратора. Для копіювання не потрібні ні монтування, ні sudo.",
65
65
  "Copy backups to an external server (SFTP)": "Копіювати резервні копії на зовнішній сервер (SFTP)",
66
- "Host": "Хост",
66
+ "Server address": "Адреса сервера",
67
67
  "IP address or host name of the server": "IP-адреса або ім'я хоста сервера",
68
68
  "SSH port": "Порт SSH",
69
69
  "User name": "Ім'я користувача",
70
- "Password": "Пароль",
70
+ "Password of the user": "Пароль користувача",
71
71
  "Directory on the server": "Тека на сервері",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "наприклад, /backups/e-invoices, створюється за потреби",
73
73
  "Server fingerprint (optional)": "Відбиток сервера (необов'язково)",
@@ -63,11 +63,11 @@
63
63
  "External backup": "外部备份",
64
64
  "Every backup is also copied to another computer over SFTP (for example a Synology NAS), so it survives the loss of this host. Use a user that may only write into the target directory, not an administrator. The copy needs no mount and no sudo.": "每份备份还会通过 SFTP 复制到另一台计算机(例如群晖 NAS),这样即使本主机丢失也能保留。请使用只能写入目标目录的用户,而不是管理员。复制既不需要挂载,也不需要 sudo。",
65
65
  "Copy backups to an external server (SFTP)": "将备份复制到外部服务器(SFTP)",
66
- "Host": "主机",
66
+ "Server address": "服务器地址",
67
67
  "IP address or host name of the server": "服务器的 IP 地址或主机名",
68
68
  "SSH port": "SSH 端口",
69
69
  "User name": "用户名",
70
- "Password": "密码",
70
+ "Password of the user": "该用户的密码",
71
71
  "Directory on the server": "服务器上的目录",
72
72
  "e.g. /backups/e-invoices, created when it is missing": "例如 /backups/e-invoices,不存在时会创建",
73
73
  "Server fingerprint (optional)": "服务器指纹(可选)",
@@ -519,7 +519,7 @@
519
519
  },
520
520
  "remoteHost": {
521
521
  "type": "text",
522
- "label": "Host",
522
+ "label": "Server address",
523
523
  "help": "IP address or host name of the server",
524
524
  "disabled": "!data.remoteEnabled",
525
525
  "newLine": true,
@@ -555,7 +555,7 @@
555
555
  },
556
556
  "remotePassword": {
557
557
  "type": "password",
558
- "label": "Password",
558
+ "label": "Password of the user",
559
559
  "repeat": false,
560
560
  "visible": true,
561
561
  "disabled": "!data.remoteEnabled",
@@ -385,7 +385,8 @@ async function readAndVerifyBackup(zipData, limits) {
385
385
  invoiceId: attachment.invoiceId,
386
386
  filename: attachment.filename,
387
387
  mime: attachment.mime,
388
- size: attachment.size,
388
+ // the content decides, not a number in dump.json
389
+ size: data.length,
389
390
  data,
390
391
  createdAt: attachment.createdAt
391
392
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/backup.ts"],
4
- "sourcesContent": ["/**\n * Backup and restore for ioBroker.e-invoices (P5).\n *\n * A backup ZIP contains:\n * - manifest.json (app id, format version, counts, per-file SHA-256)\n * - dump.json (full database content; the attachment rows carry no content)\n * - attachments/<id> (the content of each attachment, hashed in the manifest)\n * - files/<path> (PDF/XML/XLSX/logos from the mountpoint)\n *\n * Format 1 (older backups) carried the attachments as base64 inside dump.json;\n * they can still be restored.\n *\n * Restore verifies the manifest first, replaces the database in one\n * transaction and rewrites the files afterwards (each with its own\n * try/catch, failures are reported, not hidden).\n */\nimport JSZip from 'jszip';\nimport { createHash } from 'node:crypto';\nimport type { InvoiceDatabase, DatabaseDump } from './db';\nimport { isQuote } from './invoice-model';\nimport { LATEST_SCHEMA_VERSION } from './migrations';\n\n/** File name prefix of backups the user asked for. */\nexport const MANUAL_BACKUP_PREFIX = 'backups/e-invoices-backup-';\n\n/** File name prefix of the automatic backups \u2014 the only ones that are ever deleted again. */\nexport const AUTO_BACKUP_PREFIX = 'backups/e-invoices-auto-';\n\n/** App id stamped into every manifest. */\nexport const BACKUP_APP_ID = 'ioBroker.e-invoices';\n\n/** Backup format version written by this adapter (2: attachments as own ZIP entries). */\nexport const BACKUP_FORMAT_VERSION = 2;\n\n/** Backup format versions a restore understands (1: attachments as base64 in dump.json). */\nconst SUPPORTED_BACKUP_FORMATS = [1, 2];\n\n/** One file listed in the manifest. */\nexport interface BackupManifestFile {\n\t/** Path inside files/ and on the mountpoint. */\n\tpath: string;\n\t/** Size in bytes. */\n\tsize: number;\n\t/** SHA-256 hex of the file content. */\n\tsha256: string;\n}\n\n/** Backup manifest content. */\nexport interface BackupManifest {\n\t/** Always ioBroker.e-invoices. */\n\tapp: string;\n\t/** Backup format version. */\n\tformatVersion: number;\n\t/** Creation timestamp. */\n\tcreatedAt: string;\n\t/** Adapter version that wrote the backup. */\n\tadapterVersion: string;\n\t/** DB schema version at export. */\n\tschemaVersion: number;\n\t/** Entity counts. */\n\tcounts: { invoices: number; templates: number; attachments: number; customers: number; files: number };\n\t/** Files with hashes. */\n\tfiles: BackupManifestFile[];\n\t/** Attachment contents (format 2): `path` is the attachment id, stored as attachments/<id>. */\n\tattachmentFiles?: BackupManifestFile[];\n\t/** SHA-256 hex of dump.json, the payload that actually replaces the database. */\n\tdumpSha256?: string;\n}\n\n/** Created backup (ZIP bytes + metadata). */\nexport interface BackupResult {\n\t/** Mountpoint filename, e.g. backups/e-invoices-2026-....zip. */\n\tfilename: string;\n\t/** ZIP size in bytes. */\n\tsize: number;\n\t/** SHA-256 hex of the ZIP. */\n\tsha256: string;\n\t/** Manifest. */\n\tmanifest: BackupManifest;\n\t/** ZIP bytes. */\n\tdata: Buffer;\n}\n\n/** Restore outcome. */\nexport interface RestoreSummary {\n\t/** Manifest of the restored backup. */\n\tmanifest: BackupManifest;\n\t/** Imported invoices. */\n\tinvoices: number;\n\t/** Imported templates. */\n\ttemplates: number;\n\t/** Rewritten files. */\n\tfilesWritten: string[];\n\t/** Files that failed with reasons. */\n\tfileErrors: string[];\n\t/** Backup of the state before the restore (mountpoint path). */\n\tsafetyBackup: string | null;\n\t/** Counters that stayed higher than in the backup, so no number is issued twice. */\n\tcountersKept: string[];\n}\n\n/** Minimal logger shape (adapter log compatible). */\nexport interface BackupLogger {\n\t/** Info message. */\n\tinfo(message: string): void;\n\t/** Error message. */\n\terror(message: string): void;\n}\n\n/** File backend (mountpoint in prod, memory in tests). */\nexport interface BackupStorage {\n\t/** Write a file. */\n\twrite(relPath: string, data: string | Buffer): Promise<void>;\n\t/** Read a file. */\n\tread(relPath: string): Promise<Buffer>;\n}\n\nfunction sha256Hex(data: Buffer | string): string {\n\treturn createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * Rejects backup entry paths that would escape the storage root\n * (zip slip: `../`, absolute paths, Windows drive letters, backslashes).\n *\n * @param relPath - Path taken from the backup manifest.\n */\nfunction assertSafeEntryPath(relPath: unknown): asserts relPath is string {\n\tif (typeof relPath !== 'string' || relPath.trim() === '') {\n\t\tthrow new Error('Backup manifest contains an invalid file path');\n\t}\n\tif (relPath.includes('\\\\') || relPath.startsWith('/') || /^[A-Za-z]:/.test(relPath)) {\n\t\tthrow new Error(`Backup manifest contains an unsafe file path: ${relPath}`);\n\t}\n\tfor (const segment of relPath.split('/')) {\n\t\tif (segment === '..' || segment === '' || segment === '.') {\n\t\t\tthrow new Error(`Backup manifest contains an unsafe file path: ${relPath}`);\n\t\t}\n\t}\n}\n\n/** Shape of a document number the adapter can have issued (see `normalizeNumberFormat`). */\nconst SAFE_NUMBER = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\n/**\n * A backup is data from outside: what ends up in a path or in a download header\n * has to look like what the adapter itself writes. The archive checksums only\n * tell that nothing was damaged, not that nothing was crafted.\n *\n * @param dump - Parsed database content of the backup.\n * @throws {Error} When a number or a stored path could leave its place.\n */\nfunction assertSafeRecords(dump: DatabaseDump): void {\n\tfor (const invoice of dump.invoices) {\n\t\tif (invoice.number != null && !SAFE_NUMBER.test(invoice.number)) {\n\t\t\tthrow new Error(`Backup contains an unsafe document number: ${String(invoice.number).slice(0, 40)}`);\n\t\t}\n\t\tfor (const stored of [invoice.pdfPath, invoice.xlsxPath]) {\n\t\t\tif (stored != null) {\n\t\t\t\tassertSafeEntryPath(stored);\n\t\t\t\tif (!stored.startsWith('invoices/')) {\n\t\t\t\t\tthrow new Error(`Backup contains an artifact path outside invoices/: ${stored}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// R7.8: the frozen layout carries a logo path too, and it is read from disk on re-render\n\t\tconst frozenLogo = invoice.templateSnapshot?.definition?.logo?.path;\n\t\tif (frozenLogo != null) {\n\t\t\tassertSafeEntryPath(frozenLogo);\n\t\t\tif (!frozenLogo.startsWith('logos/')) {\n\t\t\t\tthrow new Error(`Backup contains a logo path outside logos/: ${frozenLogo}`);\n\t\t\t}\n\t\t}\n\t}\n\tfor (const template of dump.templates) {\n\t\tconst logo = template.definition?.logo?.path;\n\t\tif (logo != null) {\n\t\t\tassertSafeEntryPath(logo);\n\t\t\tif (!logo.startsWith('logos/')) {\n\t\t\t\tthrow new Error(`Backup contains a logo path outside logos/: ${logo}`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Hard limits for restore input, so a crafted ZIP cannot exhaust memory (R3). */\nexport interface BackupLimits {\n\t/** Maximum size of the incoming ZIP in bytes. */\n\tzipBytes: number;\n\t/** Maximum sum of all uncompressed bytes in the ZIP. */\n\tunpackedBytes: number;\n\t/** Maximum number of entries in the ZIP. */\n\tentries: number;\n\t/** Maximum size of the single `dump.json` payload. */\n\tdumpBytes: number;\n}\n\n/** Production limits: a 512 MB ZIP may expand to at most 1 GB. */\nexport const DEFAULT_BACKUP_LIMITS: BackupLimits = {\n\tzipBytes: 512 * 1024 * 1024,\n\tunpackedBytes: 1024 * 1024 * 1024,\n\tentries: 20000,\n\tdumpBytes: 256 * 1024 * 1024,\n};\n\n/**\n * Merges caller limits with the production defaults.\n *\n * @param limits - Optional overrides (used by tests).\n */\nfunction resolveLimits(limits?: Partial<BackupLimits>): BackupLimits {\n\treturn { ...DEFAULT_BACKUP_LIMITS, ...(limits ?? {}) };\n}\n\n/**\n * Uncompressed size as declared in the ZIP directory, when JSZip exposes it.\n * Optional by design \u2014 the running total while extracting is the hard guard.\n *\n * @param entry - ZIP entry (or null when the name does not exist).\n */\nfunction declaredSize(entry: JSZip.JSZipObject | null): number | undefined {\n\tconst data = (entry as unknown as { _data?: { uncompressedSize?: number } } | null)?._data;\n\treturn typeof data?.uncompressedSize === 'number' ? data.uncompressedSize : undefined;\n}\n\nfunction stampName(date = new Date()): string {\n\treturn date.toISOString().replace(/[:.]/g, '-').slice(0, 19);\n}\n\n/**\n * Collects artifact paths referenced by the database content.\n *\n * @param dump - Exported database content.\n */\nexport function collectArtifactPaths(dump: DatabaseDump): string[] {\n\tconst paths = new Set<string>();\n\tfor (const invoice of dump.invoices) {\n\t\tif (invoice.pdfPath) {\n\t\t\tpaths.add(invoice.pdfPath);\n\t\t}\n\t\tif (invoice.xlsxPath) {\n\t\t\tpaths.add(invoice.xlsxPath);\n\t\t}\n\t\t// a quotation is no e-invoice and never has an XML file (R8): looking for one would log an error\n\t\t// \"unreadable file\" in every backup\n\t\tif (invoice.number && !isQuote(invoice.docType)) {\n\t\t\tpaths.add(`invoices/${invoice.issueDate.slice(0, 4)}/${invoice.number}.xml`);\n\t\t}\n\t\tif (invoice.templateSnapshot?.definition?.logo?.path) {\n\t\t\tpaths.add(invoice.templateSnapshot.definition.logo.path);\n\t\t}\n\t}\n\tfor (const template of dump.templates) {\n\t\tif (template.definition.logo?.path) {\n\t\t\tpaths.add(template.definition.logo.path);\n\t\t}\n\t}\n\treturn [...paths];\n}\n\ninterface DumpJsonAttachment {\n\t/** Row id (kept for traceability, reinserted without id). */\n\tid: number;\n\t/** Owning invoice UUID. */\n\tinvoiceId: string;\n\t/** Original filename. */\n\tfilename: string;\n\t/** MIME type. */\n\tmime: string;\n\t/** Size in bytes. */\n\tsize: number;\n\t/** Base64 content (format 1 only; format 2 keeps the content in attachments/<id>). */\n\tdataBase64?: string;\n\t/** Creation timestamp. */\n\tcreatedAt: string;\n}\n\n/**\n * Creates a backup ZIP from the database and the file backend.\n *\n * @param db - Open invoice database.\n * @param storage - File backend for reading artifacts.\n * @param log - Logger.\n * @param adapterVersion - Adapter version for the manifest.\n * @param kind - `manual` (default) or `auto`: automatic backups get their own file name, so only\n * they are ever pruned.\n * @param limits - The limits a restore enforces (default: the production ones; tests pass small ones).\n * @throws {Error} When the backup could not be restored with these limits \u2014 better no backup than one\n * that only looks like protection.\n */\nexport async function createBackup(\n\tdb: InvoiceDatabase,\n\tstorage: Pick<BackupStorage, 'read'>,\n\tlog: BackupLogger,\n\tadapterVersion: string,\n\tkind: 'manual' | 'auto' = 'manual',\n\tlimits?: Partial<BackupLimits>,\n): Promise<BackupResult> {\n\tconst caps = resolveLimits(limits);\n\tconst dump = db.exportData();\n\t// before anything is packed: the attachments alone can already be more than a restore accepts \u2014\n\t// and would eat the memory of the ioBroker host first\n\tconst attachmentBytes = dump.attachments.reduce((sum, attachment) => sum + attachment.data.length, 0);\n\tconst early = backupSizeProblems({ unpackedBytes: attachmentBytes }, caps);\n\tif (early.length > 0) {\n\t\tthrow new Error(backupTooLargeMessage(early));\n\t}\n\tconst dumpJson = {\n\t\t...dump,\n\t\tattachments: dump.attachments.map((attachment): DumpJsonAttachment => ({\n\t\t\tid: attachment.id,\n\t\t\tinvoiceId: attachment.invoiceId,\n\t\t\tfilename: attachment.filename,\n\t\t\tmime: attachment.mime,\n\t\t\tsize: attachment.size,\n\t\t\tcreatedAt: attachment.createdAt,\n\t\t})),\n\t};\n\n\tconst zip = new JSZip();\n\tconst files: BackupManifestFile[] = [];\n\tconst attachmentFiles: BackupManifestFile[] = [];\n\tfor (const attachment of dump.attachments) {\n\t\tzip.file(`attachments/${attachment.id}`, attachment.data);\n\t\tattachmentFiles.push({\n\t\t\tpath: String(attachment.id),\n\t\t\tsize: attachment.data.length,\n\t\t\tsha256: sha256Hex(attachment.data),\n\t\t});\n\t}\n\tfor (const path of collectArtifactPaths(dump)) {\n\t\ttry {\n\t\t\tconst data = await storage.read(path);\n\t\t\tzip.file(`files/${path}`, data);\n\t\t\tfiles.push({ path, size: data.length, sha256: sha256Hex(data) });\n\t\t} catch (error) {\n\t\t\tlog.error(`Backup skips unreadable file ${path}: ${(error as Error).message}`);\n\t\t}\n\t}\n\tconst dumpJsonText = JSON.stringify(dumpJson, null, 2);\n\tconst dumpBytes = Buffer.byteLength(dumpJsonText);\n\t// the restore refuses what is above its limits, so such a backup must not be created at all\n\tconst problems = backupSizeProblems(\n\t\t{\n\t\t\tdumpBytes,\n\t\t\tunpackedBytes: dumpBytes + [...files, ...attachmentFiles].reduce((sum, file) => sum + file.size, 0),\n\t\t\tentries: files.length + attachmentFiles.length + 2,\n\t\t},\n\t\tcaps,\n\t);\n\tif (problems.length > 0) {\n\t\tthrow new Error(backupTooLargeMessage(problems));\n\t}\n\tzip.file('dump.json', dumpJsonText);\n\tconst manifest: BackupManifest = {\n\t\tapp: BACKUP_APP_ID,\n\t\tformatVersion: BACKUP_FORMAT_VERSION,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tadapterVersion,\n\t\tschemaVersion: dump.schemaVersion,\n\t\tcounts: {\n\t\t\tinvoices: dump.invoices.length,\n\t\t\ttemplates: dump.templates.length,\n\t\t\tattachments: dump.attachments.length,\n\t\t\tcustomers: dump.customers.length,\n\t\t\tfiles: files.length,\n\t\t},\n\t\tfiles,\n\t\tattachmentFiles,\n\t\tdumpSha256: sha256Hex(dumpJsonText),\n\t};\n\tzip.file('manifest.json', JSON.stringify(manifest, null, 2));\n\tconst data = Buffer.from(await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }));\n\tconst zipProblems = backupSizeProblems({ zipBytes: data.length }, caps);\n\tif (zipProblems.length > 0) {\n\t\tthrow new Error(backupTooLargeMessage(zipProblems));\n\t}\n\tconst filename = `${kind === 'auto' ? AUTO_BACKUP_PREFIX : MANUAL_BACKUP_PREFIX}${stampName()}.zip`;\n\treturn { filename, size: data.length, sha256: sha256Hex(data), manifest, data };\n}\n\n/** What a restore would change, without touching anything. */\nexport interface RestorePreview {\n\t/** Manifest of the inspected backup. */\n\tmanifest: BackupManifest;\n\t/** Invoice count in the backup. */\n\tinvoices: number;\n\t/** Issued invoices among them. */\n\tissued: number;\n\t/** Invoice numbers carried by the backup. */\n\tnumbers: string[];\n\t/** Template count. */\n\ttemplates: number;\n\t/** Customer count. */\n\tcustomers: number;\n\t/** Product count. */\n\tproducts: number;\n\t/** Company profile count. */\n\tcompanies: number;\n\t/** Invoice count currently in the database. */\n\tcurrentInvoices: number;\n\t/** Numbers that would be overwritten by this backup. */\n\toverwritten: string[];\n\t/** Numbers that only exist here and would be new. */\n\tadded: string[];\n\t/** Numbers that exist only in the current database and would be removed from it. */\n\tonlyHere: string[];\n\t/** Counters that are ahead of the backup (they are kept, numbers are never reused). */\n\tcounterAhead: string[];\n\t/** Files that would be written. */\n\tfilesWritten: number;\n}\n\n/**\n * Inspects a backup ZIP without writing anything.\n *\n * A restore replaces the whole database, so the user should see exactly what\n * would change before confirming. Every integrity check of the real restore\n * runs here as well, so a broken backup is rejected in the preview and never\n * half-applied.\n *\n * @param db - Open invoice database (read-only use).\n * @param zipData - Backup ZIP bytes.\n * @param limits - Optional ZIP limits (defaults to the production caps).\n * @returns Counts and the diff against the current state.\n * @throws {Error} When the ZIP, manifest, checksums or schema are not usable.\n */\nexport async function previewRestore(\n\tdb: InvoiceDatabase,\n\tzipData: Buffer,\n\tlimits?: Partial<BackupLimits>,\n): Promise<RestorePreview> {\n\tconst { manifest, dump } = await readAndVerifyBackup(zipData, limits);\n\tconst numbers = dump.invoices.map(i => i.number).filter((n): n is string => Boolean(n));\n\tconst currentNumbers = new Set(\n\t\tdb\n\t\t\t.allInvoices()\n\t\t\t.map(i => i.number)\n\t\t\t.filter(Boolean) as string[],\n\t);\n\treturn {\n\t\tmanifest,\n\t\tinvoices: dump.invoices.length,\n\t\tissued: dump.invoices.filter(i => i.status === 'issued').length,\n\t\tnumbers,\n\t\ttemplates: dump.templates.length,\n\t\tcustomers: dump.customers.length,\n\t\tproducts: dump.products.length,\n\t\tcompanies: dump.companies.length,\n\t\tcurrentInvoices: db.allInvoices().length,\n\t\toverwritten: numbers.filter(n => currentNumbers.has(n)),\n\t\tadded: numbers.filter(n => !currentNumbers.has(n)),\n\t\tfilesWritten: (manifest.files ?? []).length,\n\t\tonlyHere: [...currentNumbers].filter(n => !numbers.includes(n)),\n\t\tcounterAhead: mergeCounters(dump.counters, db.exportData().counters).raised,\n\t};\n}\n\n/**\n * Raises the counters of a backup to the current ones where those are higher.\n *\n * A restore may bring back an older state, but a number that was handed out\n * once must never be handed out again (\u00A7 14 Abs. 4 Nr. 4 UStG, GoBD): its\n * PDF/XML may still lie on the mountpoint and would be overwritten.\n *\n * @param fromBackup - Counters of the backup dump.\n * @param current - Counters of the running database.\n * @returns The merged counters and a readable list of those that were raised.\n */\nfunction mergeCounters(\n\tfromBackup: DatabaseDump['counters'],\n\tcurrent: DatabaseDump['counters'],\n): { counters: DatabaseDump['counters']; raised: string[] } {\n\tconst key = (c: { year: number; employee?: string; doc_type?: string }): string =>\n\t\t`${c.year}/${c.employee ?? '00'}/${c.doc_type ?? 'invoice'}`;\n\tconst merged = new Map<string, DatabaseDump['counters'][number]>();\n\tfor (const counter of fromBackup ?? []) {\n\t\tmerged.set(key(counter), counter);\n\t}\n\tconst raised: string[] = [];\n\tfor (const counter of current) {\n\t\tconst existing = merged.get(key(counter));\n\t\tif (!existing || existing.last_seq < counter.last_seq) {\n\t\t\tmerged.set(key(counter), counter);\n\t\t\traised.push(`${key(counter)} (backup ${existing?.last_seq ?? 0}, kept ${counter.last_seq})`);\n\t\t}\n\t}\n\treturn { counters: [...merged.values()], raised };\n}\n\n/**\n * Opens a backup ZIP and verifies it completely: structure, application id,\n * format version, schema compatibility, per-file checksums and the dump\n * checksum. Shared by the preview and the real restore, so a broken backup\n * can never be half applied.\n *\n * @param zipData - Backup ZIP bytes.\n * @param limits - Optional ZIP limits (defaults to the production caps).\n * @returns The verified manifest, the parsed database dump and the verified files.\n * @throws {Error} When anything about the archive is unusable.\n */\nasync function readAndVerifyBackup(\n\tzipData: Buffer,\n\tlimits?: Partial<BackupLimits>,\n): Promise<{ manifest: BackupManifest; dump: DatabaseDump; files: { path: string; data: Buffer }[] }> {\n\tconst caps = resolveLimits(limits);\n\tif (zipData.length > caps.zipBytes) {\n\t\tthrow new Error(`Backup ZIP is too large (${zipData.length} bytes, limit ${caps.zipBytes})`);\n\t}\n\tlet zip: JSZip;\n\ttry {\n\t\tzip = await JSZip.loadAsync(zipData);\n\t} catch {\n\t\tthrow new Error('File is no valid backup ZIP');\n\t}\n\t// ZIP bomb guard: entry count and declared sizes are checked before the\n\t// first entry is decompressed.\n\tconst names = Object.keys(zip.files);\n\tif (names.length > caps.entries) {\n\t\tthrow new Error(`Backup ZIP has too many entries (${names.length}, limit ${caps.entries})`);\n\t}\n\tlet declared = 0;\n\tfor (const name of names) {\n\t\tconst size = declaredSize(zip.files[name]);\n\t\tif (size === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tdeclared += size;\n\t\tif (declared > caps.unpackedBytes) {\n\t\t\tthrow new Error(`Backup ZIP would expand to at least ${declared} bytes (limit ${caps.unpackedBytes})`);\n\t\t}\n\t}\n\tconst manifestFile = zip.file('manifest.json');\n\tconst dumpFile = zip.file('dump.json');\n\tif (!manifestFile || !dumpFile) {\n\t\tthrow new Error('Backup ZIP misses manifest.json or dump.json');\n\t}\n\tconst manifest = JSON.parse(await manifestFile.async('string')) as BackupManifest;\n\tif (manifest.app !== BACKUP_APP_ID || !SUPPORTED_BACKUP_FORMATS.includes(manifest.formatVersion)) {\n\t\tthrow new Error(`Unsupported backup (app=${String(manifest.app)}, format=${String(manifest.formatVersion)})`);\n\t}\n\tif (manifest.schemaVersion > LATEST_SCHEMA_VERSION) {\n\t\tthrow new Error(`Backup needs schema v${manifest.schemaVersion}, adapter knows v${LATEST_SCHEMA_VERSION}`);\n\t}\n\t// Read the artifact files once: the restore writes exactly these buffers,\n\t// so a second read can no longer fail after the database was replaced.\n\tconst files: { path: string; data: Buffer }[] = [];\n\tlet unpacked = 0;\n\tfor (const file of manifest.files ?? []) {\n\t\tassertSafeEntryPath(file.path);\n\t\tconst entry = zip.file(`files/${file.path}`);\n\t\tif (!entry) {\n\t\t\tthrow new Error(`Backup misses file: files/${file.path}`);\n\t\t}\n\t\tconst data = Buffer.from(await entry.async('nodebuffer'));\n\t\tunpacked += data.length;\n\t\tif (unpacked > caps.unpackedBytes) {\n\t\t\tthrow new Error(`Backup expands to more than ${caps.unpackedBytes} bytes`);\n\t\t}\n\t\tif (sha256Hex(data) !== file.sha256 || data.length !== file.size) {\n\t\t\tthrow new Error(`Checksum mismatch: files/${file.path}`);\n\t\t}\n\t\tfiles.push({ path: file.path, data });\n\t}\n\n\t// attachment contents (format 2): hashed like the files, checked against the sizes in the dump below\n\tconst attachmentData = new Map<number, Buffer>();\n\tfor (const file of manifest.attachmentFiles ?? []) {\n\t\tconst id = Number(file.path);\n\t\tif (!Number.isInteger(id) || id < 0 || String(id) !== file.path) {\n\t\t\tthrow new Error(`Backup lists an invalid attachment id: ${file.path}`);\n\t\t}\n\t\tconst entry = zip.file(`attachments/${id}`);\n\t\tif (!entry) {\n\t\t\tthrow new Error(`Backup misses attachment: attachments/${id}`);\n\t\t}\n\t\tconst data = Buffer.from(await entry.async('nodebuffer'));\n\t\tunpacked += data.length;\n\t\tif (unpacked > caps.unpackedBytes) {\n\t\t\tthrow new Error(`Backup expands to more than ${caps.unpackedBytes} bytes`);\n\t\t}\n\t\tif (sha256Hex(data) !== file.sha256 || data.length !== file.size) {\n\t\t\tthrow new Error(`Checksum mismatch: attachments/${id}`);\n\t\t}\n\t\tattachmentData.set(id, data);\n\t}\n\n\tconst declaredDump = declaredSize(dumpFile);\n\tif (declaredDump !== undefined && declaredDump > caps.dumpBytes) {\n\t\tthrow new Error(`Backup dump.json is too large (${declaredDump} bytes, limit ${caps.dumpBytes})`);\n\t}\n\tconst dumpJsonText = await dumpFile.async('string');\n\tif (Buffer.byteLength(dumpJsonText, 'utf8') > caps.dumpBytes) {\n\t\tthrow new Error(`Backup dump.json is too large (limit ${caps.dumpBytes})`);\n\t}\n\tif (manifest.dumpSha256 && sha256Hex(dumpJsonText) !== manifest.dumpSha256) {\n\t\tthrow new Error('Checksum mismatch: dump.json');\n\t}\n\tlet dumpJson: Omit<DatabaseDump, 'attachments'> & { attachments: DumpJsonAttachment[] };\n\ttry {\n\t\tdumpJson = JSON.parse(dumpJsonText) as typeof dumpJson;\n\t} catch {\n\t\tthrow new Error('Backup ZIP is corrupt: dump.json is not readable JSON');\n\t}\n\tconst dump: DatabaseDump = {\n\t\tformatVersion: 1,\n\t\texportedAt: String(dumpJson.exportedAt ?? new Date().toISOString()),\n\t\tschemaVersion: Number(dumpJson.schemaVersion ?? 0),\n\t\tinvoices: dumpJson.invoices ?? [],\n\t\tcounters: dumpJson.counters ?? [],\n\t\ttemplates: dumpJson.templates ?? [],\n\t\tcompanies: dumpJson.companies ?? [],\n\t\tcustomers: dumpJson.customers ?? [],\n\t\tproducts: dumpJson.products ?? [],\n\t\tdunningTexts: dumpJson.dunningTexts,\n\t\tattachments: (dumpJson.attachments ?? []).map(attachment => {\n\t\t\tlet data: Buffer;\n\t\t\tif (attachment.dataBase64 !== undefined) {\n\t\t\t\tdata = Buffer.from(attachment.dataBase64, 'base64');\n\t\t\t} else {\n\t\t\t\tconst own = attachmentData.get(attachment.id);\n\t\t\t\tif (!own) {\n\t\t\t\t\tthrow new Error(`Backup has no content for attachment ${attachment.id} (${attachment.filename})`);\n\t\t\t\t}\n\t\t\t\tdata = own;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tid: attachment.id,\n\t\t\t\tinvoiceId: attachment.invoiceId,\n\t\t\t\tfilename: attachment.filename,\n\t\t\t\tmime: attachment.mime,\n\t\t\t\tsize: attachment.size,\n\t\t\t\tdata,\n\t\t\t\tcreatedAt: attachment.createdAt,\n\t\t\t};\n\t\t}),\n\t};\n\tassertSafeRecords(dump);\n\treturn { manifest, dump, files };\n}\n\n/**\n * Restores a backup ZIP: verifies the manifest, replaces the database\n * transactionally and rewrites the files.\n *\n * @param db - Open invoice database.\n * @param storage - File backend for writing artifacts.\n * @param zipData - Backup ZIP bytes.\n * @param log - Logger.\n * @param limits - Optional ZIP limits (defaults to the production caps).\n * @param options - Adapter version for the safety backup and the source for the restore log.\n * @param options.adapterVersion - Adapter version written into the safety backup.\n * @param options.source - Where the restore came from (`api`, `state`, ...).\n */\nexport async function restoreBackup(\n\tdb: InvoiceDatabase,\n\tstorage: BackupStorage,\n\tzipData: Buffer,\n\tlog: BackupLogger,\n\tlimits?: Partial<BackupLimits>,\n\toptions: { adapterVersion?: string; source?: string } = {},\n): Promise<RestoreSummary> {\n\tconst { manifest, dump, files } = await readAndVerifyBackup(zipData, limits);\n\n\t// H3: a restore replaces everything, so the current state is saved first.\n\t// Without that copy the restore is not started.\n\tlet safetyBackup: string | null = null;\n\ttry {\n\t\tconst safety = await createBackup(db, storage, log, options.adapterVersion ?? 'unknown');\n\t\tsafetyBackup = safety.filename.replace('-backup-', '-prerestore-');\n\t\tawait storage.write(safetyBackup, safety.data);\n\t\tdb.logBackup({\n\t\t\tfilename: safetyBackup,\n\t\t\tsize: safety.size,\n\t\t\tsha256: safety.sha256,\n\t\t\tmanifestJson: JSON.stringify(safety.manifest),\n\t\t});\n\t\tlog.info(`Safety backup before restore: ${safetyBackup}`);\n\t} catch (error) {\n\t\tthrow new Error(`Restore aborted: the safety backup of the current state failed (${(error as Error).message})`);\n\t}\n\n\t// H3: counters never move backwards, so no issued number is reused.\n\tconst { counters, raised } = mergeCounters(dump.counters, db.exportData().counters);\n\tdump.counters = counters;\n\tif (raised.length > 0) {\n\t\tlog.info(`Restore keeps ${raised.length} counter(s) ahead of the backup: ${raised.join('; ')}`);\n\t}\n\n\tdb.importData(dump);\n\tif (!db.getDefaultTemplate()) {\n\t\tdb.ensureDefaultTemplate();\n\t}\n\tlog.info(`Database restored: ${dump.invoices.length} invoices, ${dump.templates.length} templates`);\n\n\tconst filesWritten: string[] = [];\n\tconst fileErrors: string[] = [];\n\tfor (const file of files) {\n\t\ttry {\n\t\t\tawait storage.write(file.path, file.data);\n\t\t\tfilesWritten.push(file.path);\n\t\t} catch (error) {\n\t\t\tconst message = `${file.path}: ${(error as Error).message}`;\n\t\t\tfileErrors.push(message);\n\t\t\tlog.error(`Restore cannot write ${message}`);\n\t\t}\n\t}\n\n\t// audit trail: who restored what and when stays readable outside the database\n\ttry {\n\t\tlet previous = '';\n\t\ttry {\n\t\t\tprevious = (await storage.read('backups/restore-log.jsonl')).toString('utf8');\n\t\t} catch {\n\t\t\t// first entry\n\t\t}\n\t\tconst entry = JSON.stringify({\n\t\t\tat: new Date().toISOString(),\n\t\t\tsource: options.source ?? 'api',\n\t\t\tbackupCreatedAt: manifest.createdAt,\n\t\t\tinvoices: dump.invoices.length,\n\t\t\tsafetyBackup,\n\t\t\tcountersKept: raised,\n\t\t});\n\t\tawait storage.write('backups/restore-log.jsonl', `${previous}${entry}\\n`);\n\t} catch (error) {\n\t\tlog.error(`Cannot write the restore log: ${(error as Error).message}`);\n\t}\n\treturn {\n\t\tmanifest,\n\t\tinvoices: dump.invoices.length,\n\t\ttemplates: dump.templates.length,\n\t\tfilesWritten,\n\t\tfileErrors,\n\t\tsafetyBackup,\n\t\tcountersKept: raised,\n\t};\n}\n\n/** An entry of the backup log, as far as the schedule needs it. */\nexport interface BackupLogItem {\n\t/** Path below the storage mount, e.g. `backups/e-invoices-auto-\u2026.zip`. */\n\tfilename: string;\n\t/** ISO creation time. */\n\tcreatedAt: string;\n}\n\n/**\n * Picks the automatic backups that exceed the number to keep (the oldest ones).\n *\n * Only files with the automatic prefix qualify: backups the user made by hand and the\n * safety backups before a restore are never touched. `keep` 0 (or less) keeps everything.\n *\n * @param entries - The backup log.\n * @param keep - How many automatic backups to keep.\n * @returns File names to delete.\n */\nexport function selectBackupsToPrune(entries: BackupLogItem[], keep: number): string[] {\n\tif (!Number.isFinite(keep) || keep <= 0) {\n\t\treturn [];\n\t}\n\treturn entries\n\t\t.filter(entry => entry.filename.startsWith(AUTO_BACKUP_PREFIX))\n\t\t.sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n\t\t.slice(Math.floor(keep))\n\t\t.map(entry => entry.filename);\n}\n\n/** Never sooner than this after a start, so a restarting adapter does not back up in a loop. */\nconst MIN_BACKUP_DELAY_MS = 60_000;\n\n/**\n * Delay until the next automatic backup.\n *\n * The schedule survives restarts: the interval counts from the last automatic backup, not from\n * the start of the adapter. Without one \u2014 or when it is overdue \u2014 the backup runs a minute\n * after the start.\n *\n * @param lastAutoAt - ISO time of the newest automatic backup, null when there is none.\n * @param intervalMs - Backup interval.\n * @param now - Current time in ms.\n */\nexport function nextBackupDelayMs(lastAutoAt: string | null, intervalMs: number, now: number): number {\n\tconst last = lastAutoAt ? Date.parse(lastAutoAt) : Number.NaN;\n\tif (!Number.isFinite(last)) {\n\t\treturn MIN_BACKUP_DELAY_MS;\n\t}\n\treturn Math.min(intervalMs, Math.max(MIN_BACKUP_DELAY_MS, last + intervalMs - now));\n}\n\n/** How current the newest backup is. */\nexport interface BackupStatus {\n\t/** ISO time of the newest backup of any kind, null when there is none. */\n\tlastAt: string | null;\n\t/** Age of that backup in hours, null when there is none. */\n\tageHours: number | null;\n\t/** `none` = no backup at all, `stale` = too old, null = fine. */\n\twarning: 'none' | 'stale' | null;\n\t/** Configured interval in minutes, 0 = automatic backup off. */\n\tintervalMinutes: number;\n\t/** Automatic backups kept, 0 = all. */\n\tkeep: number;\n}\n\n/**\n * Judges the backup log.\n *\n * Stale means: older than twice the interval but at least two days with the automatic backup\n * on; older than a week with it off. Backup is the only protection of the database against the\n * BackItUp gap (the database file itself is not part of an ioBroker backup).\n *\n * @param entries - The backup log.\n * @param intervalMinutes - Configured interval, 0 = off.\n * @param keep - Automatic backups kept.\n * @param now - Current time in ms.\n */\nexport function backupStatus(\n\tentries: BackupLogItem[],\n\tintervalMinutes: number,\n\tkeep: number,\n\tnow: number,\n): BackupStatus {\n\tconst newest = entries.map(entry => entry.createdAt).sort((a, b) => b.localeCompare(a))[0] ?? null;\n\tconst base = { intervalMinutes, keep };\n\tif (!newest) {\n\t\treturn { lastAt: null, ageHours: null, warning: 'none', ...base };\n\t}\n\tconst ageMs = now - Date.parse(newest);\n\tconst limitMs = intervalMinutes > 0 ? Math.max(2 * intervalMinutes * 60_000, 48 * 3_600_000) : 7 * 24 * 3_600_000;\n\treturn {\n\t\tlastAt: newest,\n\t\tageHours: Math.max(0, Math.round(ageMs / 3_600_000)),\n\t\twarning: ageMs > limitMs ? 'stale' : null,\n\t\t...base,\n\t};\n}\n\n/** The sizes of a backup that the restore limits apply to; every field is optional. */\nexport interface BackupSizes {\n\t/** Size of the finished ZIP. */\n\tzipBytes?: number;\n\t/** Size of `dump.json`. */\n\tdumpBytes?: number;\n\t/** Sum of everything the ZIP unpacks to. */\n\tunpackedBytes?: number;\n\t/** Number of entries in the ZIP. */\n\tentries?: number;\n}\n\n/**\n * Compares the sizes of a backup with the limits the restore enforces (M2).\n *\n * A backup the restore would refuse is no backup: it would only be found out in the emergency. The same\n * limits protect against crafted ZIPs on the way in; here they protect the user on the way out.\n *\n * @param sizes - What is known about the backup so far.\n * @param limits - The restore limits.\n * @returns One text per exceeded limit, empty when the backup could be restored.\n */\nexport function backupSizeProblems(sizes: BackupSizes, limits: BackupLimits): string[] {\n\tconst mb = (bytes: number): string => `${(bytes / 1048576).toFixed(1)} MB`;\n\tconst out: string[] = [];\n\tif (sizes.dumpBytes !== undefined && sizes.dumpBytes > limits.dumpBytes) {\n\t\tout.push(`the database part (dump.json) would be ${mb(sizes.dumpBytes)}, the limit is ${mb(limits.dumpBytes)}`);\n\t}\n\tif (sizes.unpackedBytes !== undefined && sizes.unpackedBytes > limits.unpackedBytes) {\n\t\tout.push(`the backup would unpack to ${mb(sizes.unpackedBytes)}, the limit is ${mb(limits.unpackedBytes)}`);\n\t}\n\tif (sizes.zipBytes !== undefined && sizes.zipBytes > limits.zipBytes) {\n\t\tout.push(`the ZIP would be ${mb(sizes.zipBytes)}, the limit is ${mb(limits.zipBytes)}`);\n\t}\n\tif (sizes.entries !== undefined && sizes.entries > limits.entries) {\n\t\tout.push(`the ZIP would hold ${sizes.entries} files, the limit is ${limits.entries}`);\n\t}\n\treturn out;\n}\n\n/**\n * The error text for a backup that is too large to be restored.\n *\n * @param problems - Result of `backupSizeProblems`.\n */\nfunction backupTooLargeMessage(problems: string[]): string {\n\treturn `Backup not created, it could not be restored: ${problems.join('; ')}. Reduce the attachments, or rely on the instance backup (BackItUp) for the files.`;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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C/G;AACA,MAAI,MAAM,kBAAkB,UAAa,MAAM,gBAAgB,OAAO,eAAe;AACpF,QAAI,KAAK,8BAA8B,GAAG,MAAM,aAAa,CAAC,kBAAkB,GAAG,OAAO,aAAa,CAAC,EAAE;AAAA,EAC3G;AACA,MAAI,MAAM,aAAa,UAAa,MAAM,WAAW,OAAO,UAAU;AACrE,QAAI,KAAK,oBAAoB,GAAG,MAAM,QAAQ,CAAC,kBAAkB,GAAG,OAAO,QAAQ,CAAC,EAAE;AAAA,EACvF;AACA,MAAI,MAAM,YAAY,UAAa,MAAM,UAAU,OAAO,SAAS;AAClE,QAAI,KAAK,sBAAsB,MAAM,OAAO,wBAAwB,OAAO,OAAO,EAAE;AAAA,EACrF;AACA,SAAO;AACR;AAOA,SAAS,sBAAsB,UAA4B;AAC1D,SAAO,iDAAiD,SAAS,KAAK,IAAI,CAAC;AAC5E;",
4
+ "sourcesContent": ["/**\n * Backup and restore for ioBroker.e-invoices (P5).\n *\n * A backup ZIP contains:\n * - manifest.json (app id, format version, counts, per-file SHA-256)\n * - dump.json (full database content; the attachment rows carry no content)\n * - attachments/<id> (the content of each attachment, hashed in the manifest)\n * - files/<path> (PDF/XML/XLSX/logos from the mountpoint)\n *\n * Format 1 (older backups) carried the attachments as base64 inside dump.json;\n * they can still be restored.\n *\n * Restore verifies the manifest first, replaces the database in one\n * transaction and rewrites the files afterwards (each with its own\n * try/catch, failures are reported, not hidden).\n */\nimport JSZip from 'jszip';\nimport { createHash } from 'node:crypto';\nimport type { InvoiceDatabase, DatabaseDump } from './db';\nimport { isQuote } from './invoice-model';\nimport { LATEST_SCHEMA_VERSION } from './migrations';\n\n/** File name prefix of backups the user asked for. */\nexport const MANUAL_BACKUP_PREFIX = 'backups/e-invoices-backup-';\n\n/** File name prefix of the automatic backups \u2014 the only ones that are ever deleted again. */\nexport const AUTO_BACKUP_PREFIX = 'backups/e-invoices-auto-';\n\n/** App id stamped into every manifest. */\nexport const BACKUP_APP_ID = 'ioBroker.e-invoices';\n\n/** Backup format version written by this adapter (2: attachments as own ZIP entries). */\nexport const BACKUP_FORMAT_VERSION = 2;\n\n/** Backup format versions a restore understands (1: attachments as base64 in dump.json). */\nconst SUPPORTED_BACKUP_FORMATS = [1, 2];\n\n/** One file listed in the manifest. */\nexport interface BackupManifestFile {\n\t/** Path inside files/ and on the mountpoint. */\n\tpath: string;\n\t/** Size in bytes. */\n\tsize: number;\n\t/** SHA-256 hex of the file content. */\n\tsha256: string;\n}\n\n/** Backup manifest content. */\nexport interface BackupManifest {\n\t/** Always ioBroker.e-invoices. */\n\tapp: string;\n\t/** Backup format version. */\n\tformatVersion: number;\n\t/** Creation timestamp. */\n\tcreatedAt: string;\n\t/** Adapter version that wrote the backup. */\n\tadapterVersion: string;\n\t/** DB schema version at export. */\n\tschemaVersion: number;\n\t/** Entity counts. */\n\tcounts: { invoices: number; templates: number; attachments: number; customers: number; files: number };\n\t/** Files with hashes. */\n\tfiles: BackupManifestFile[];\n\t/** Attachment contents (format 2): `path` is the attachment id, stored as attachments/<id>. */\n\tattachmentFiles?: BackupManifestFile[];\n\t/** SHA-256 hex of dump.json, the payload that actually replaces the database. */\n\tdumpSha256?: string;\n}\n\n/** Created backup (ZIP bytes + metadata). */\nexport interface BackupResult {\n\t/** Mountpoint filename, e.g. backups/e-invoices-2026-....zip. */\n\tfilename: string;\n\t/** ZIP size in bytes. */\n\tsize: number;\n\t/** SHA-256 hex of the ZIP. */\n\tsha256: string;\n\t/** Manifest. */\n\tmanifest: BackupManifest;\n\t/** ZIP bytes. */\n\tdata: Buffer;\n}\n\n/** Restore outcome. */\nexport interface RestoreSummary {\n\t/** Manifest of the restored backup. */\n\tmanifest: BackupManifest;\n\t/** Imported invoices. */\n\tinvoices: number;\n\t/** Imported templates. */\n\ttemplates: number;\n\t/** Rewritten files. */\n\tfilesWritten: string[];\n\t/** Files that failed with reasons. */\n\tfileErrors: string[];\n\t/** Backup of the state before the restore (mountpoint path). */\n\tsafetyBackup: string | null;\n\t/** Counters that stayed higher than in the backup, so no number is issued twice. */\n\tcountersKept: string[];\n}\n\n/** Minimal logger shape (adapter log compatible). */\nexport interface BackupLogger {\n\t/** Info message. */\n\tinfo(message: string): void;\n\t/** Error message. */\n\terror(message: string): void;\n}\n\n/** File backend (mountpoint in prod, memory in tests). */\nexport interface BackupStorage {\n\t/** Write a file. */\n\twrite(relPath: string, data: string | Buffer): Promise<void>;\n\t/** Read a file. */\n\tread(relPath: string): Promise<Buffer>;\n}\n\nfunction sha256Hex(data: Buffer | string): string {\n\treturn createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * Rejects backup entry paths that would escape the storage root\n * (zip slip: `../`, absolute paths, Windows drive letters, backslashes).\n *\n * @param relPath - Path taken from the backup manifest.\n */\nfunction assertSafeEntryPath(relPath: unknown): asserts relPath is string {\n\tif (typeof relPath !== 'string' || relPath.trim() === '') {\n\t\tthrow new Error('Backup manifest contains an invalid file path');\n\t}\n\tif (relPath.includes('\\\\') || relPath.startsWith('/') || /^[A-Za-z]:/.test(relPath)) {\n\t\tthrow new Error(`Backup manifest contains an unsafe file path: ${relPath}`);\n\t}\n\tfor (const segment of relPath.split('/')) {\n\t\tif (segment === '..' || segment === '' || segment === '.') {\n\t\t\tthrow new Error(`Backup manifest contains an unsafe file path: ${relPath}`);\n\t\t}\n\t}\n}\n\n/** Shape of a document number the adapter can have issued (see `normalizeNumberFormat`). */\nconst SAFE_NUMBER = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\n/**\n * A backup is data from outside: what ends up in a path or in a download header\n * has to look like what the adapter itself writes. The archive checksums only\n * tell that nothing was damaged, not that nothing was crafted.\n *\n * @param dump - Parsed database content of the backup.\n * @throws {Error} When a number or a stored path could leave its place.\n */\nfunction assertSafeRecords(dump: DatabaseDump): void {\n\tfor (const invoice of dump.invoices) {\n\t\tif (invoice.number != null && !SAFE_NUMBER.test(invoice.number)) {\n\t\t\tthrow new Error(`Backup contains an unsafe document number: ${String(invoice.number).slice(0, 40)}`);\n\t\t}\n\t\tfor (const stored of [invoice.pdfPath, invoice.xlsxPath]) {\n\t\t\tif (stored != null) {\n\t\t\t\tassertSafeEntryPath(stored);\n\t\t\t\tif (!stored.startsWith('invoices/')) {\n\t\t\t\t\tthrow new Error(`Backup contains an artifact path outside invoices/: ${stored}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// R7.8: the frozen layout carries a logo path too, and it is read from disk on re-render\n\t\tconst frozenLogo = invoice.templateSnapshot?.definition?.logo?.path;\n\t\tif (frozenLogo != null) {\n\t\t\tassertSafeEntryPath(frozenLogo);\n\t\t\tif (!frozenLogo.startsWith('logos/')) {\n\t\t\t\tthrow new Error(`Backup contains a logo path outside logos/: ${frozenLogo}`);\n\t\t\t}\n\t\t}\n\t}\n\tfor (const template of dump.templates) {\n\t\tconst logo = template.definition?.logo?.path;\n\t\tif (logo != null) {\n\t\t\tassertSafeEntryPath(logo);\n\t\t\tif (!logo.startsWith('logos/')) {\n\t\t\t\tthrow new Error(`Backup contains a logo path outside logos/: ${logo}`);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Hard limits for restore input, so a crafted ZIP cannot exhaust memory (R3). */\nexport interface BackupLimits {\n\t/** Maximum size of the incoming ZIP in bytes. */\n\tzipBytes: number;\n\t/** Maximum sum of all uncompressed bytes in the ZIP. */\n\tunpackedBytes: number;\n\t/** Maximum number of entries in the ZIP. */\n\tentries: number;\n\t/** Maximum size of the single `dump.json` payload. */\n\tdumpBytes: number;\n}\n\n/** Production limits: a 512 MB ZIP may expand to at most 1 GB. */\nexport const DEFAULT_BACKUP_LIMITS: BackupLimits = {\n\tzipBytes: 512 * 1024 * 1024,\n\tunpackedBytes: 1024 * 1024 * 1024,\n\tentries: 20000,\n\tdumpBytes: 256 * 1024 * 1024,\n};\n\n/**\n * Merges caller limits with the production defaults.\n *\n * @param limits - Optional overrides (used by tests).\n */\nfunction resolveLimits(limits?: Partial<BackupLimits>): BackupLimits {\n\treturn { ...DEFAULT_BACKUP_LIMITS, ...(limits ?? {}) };\n}\n\n/**\n * Uncompressed size as declared in the ZIP directory, when JSZip exposes it.\n * Optional by design \u2014 the running total while extracting is the hard guard.\n *\n * @param entry - ZIP entry (or null when the name does not exist).\n */\nfunction declaredSize(entry: JSZip.JSZipObject | null): number | undefined {\n\tconst data = (entry as unknown as { _data?: { uncompressedSize?: number } } | null)?._data;\n\treturn typeof data?.uncompressedSize === 'number' ? data.uncompressedSize : undefined;\n}\n\nfunction stampName(date = new Date()): string {\n\treturn date.toISOString().replace(/[:.]/g, '-').slice(0, 19);\n}\n\n/**\n * Collects artifact paths referenced by the database content.\n *\n * @param dump - Exported database content.\n */\nexport function collectArtifactPaths(dump: DatabaseDump): string[] {\n\tconst paths = new Set<string>();\n\tfor (const invoice of dump.invoices) {\n\t\tif (invoice.pdfPath) {\n\t\t\tpaths.add(invoice.pdfPath);\n\t\t}\n\t\tif (invoice.xlsxPath) {\n\t\t\tpaths.add(invoice.xlsxPath);\n\t\t}\n\t\t// a quotation is no e-invoice and never has an XML file (R8): looking for one would log an error\n\t\t// \"unreadable file\" in every backup\n\t\tif (invoice.number && !isQuote(invoice.docType)) {\n\t\t\tpaths.add(`invoices/${invoice.issueDate.slice(0, 4)}/${invoice.number}.xml`);\n\t\t}\n\t\tif (invoice.templateSnapshot?.definition?.logo?.path) {\n\t\t\tpaths.add(invoice.templateSnapshot.definition.logo.path);\n\t\t}\n\t}\n\tfor (const template of dump.templates) {\n\t\tif (template.definition.logo?.path) {\n\t\t\tpaths.add(template.definition.logo.path);\n\t\t}\n\t}\n\treturn [...paths];\n}\n\ninterface DumpJsonAttachment {\n\t/** Row id (kept for traceability, reinserted without id). */\n\tid: number;\n\t/** Owning invoice UUID. */\n\tinvoiceId: string;\n\t/** Original filename. */\n\tfilename: string;\n\t/** MIME type. */\n\tmime: string;\n\t/** Size in bytes. */\n\tsize: number;\n\t/** Base64 content (format 1 only; format 2 keeps the content in attachments/<id>). */\n\tdataBase64?: string;\n\t/** Creation timestamp. */\n\tcreatedAt: string;\n}\n\n/**\n * Creates a backup ZIP from the database and the file backend.\n *\n * @param db - Open invoice database.\n * @param storage - File backend for reading artifacts.\n * @param log - Logger.\n * @param adapterVersion - Adapter version for the manifest.\n * @param kind - `manual` (default) or `auto`: automatic backups get their own file name, so only\n * they are ever pruned.\n * @param limits - The limits a restore enforces (default: the production ones; tests pass small ones).\n * @throws {Error} When the backup could not be restored with these limits \u2014 better no backup than one\n * that only looks like protection.\n */\nexport async function createBackup(\n\tdb: InvoiceDatabase,\n\tstorage: Pick<BackupStorage, 'read'>,\n\tlog: BackupLogger,\n\tadapterVersion: string,\n\tkind: 'manual' | 'auto' = 'manual',\n\tlimits?: Partial<BackupLimits>,\n): Promise<BackupResult> {\n\tconst caps = resolveLimits(limits);\n\tconst dump = db.exportData();\n\t// before anything is packed: the attachments alone can already be more than a restore accepts \u2014\n\t// and would eat the memory of the ioBroker host first\n\tconst attachmentBytes = dump.attachments.reduce((sum, attachment) => sum + attachment.data.length, 0);\n\tconst early = backupSizeProblems({ unpackedBytes: attachmentBytes }, caps);\n\tif (early.length > 0) {\n\t\tthrow new Error(backupTooLargeMessage(early));\n\t}\n\tconst dumpJson = {\n\t\t...dump,\n\t\tattachments: dump.attachments.map((attachment): DumpJsonAttachment => ({\n\t\t\tid: attachment.id,\n\t\t\tinvoiceId: attachment.invoiceId,\n\t\t\tfilename: attachment.filename,\n\t\t\tmime: attachment.mime,\n\t\t\tsize: attachment.size,\n\t\t\tcreatedAt: attachment.createdAt,\n\t\t})),\n\t};\n\n\tconst zip = new JSZip();\n\tconst files: BackupManifestFile[] = [];\n\tconst attachmentFiles: BackupManifestFile[] = [];\n\tfor (const attachment of dump.attachments) {\n\t\tzip.file(`attachments/${attachment.id}`, attachment.data);\n\t\tattachmentFiles.push({\n\t\t\tpath: String(attachment.id),\n\t\t\tsize: attachment.data.length,\n\t\t\tsha256: sha256Hex(attachment.data),\n\t\t});\n\t}\n\tfor (const path of collectArtifactPaths(dump)) {\n\t\ttry {\n\t\t\tconst data = await storage.read(path);\n\t\t\tzip.file(`files/${path}`, data);\n\t\t\tfiles.push({ path, size: data.length, sha256: sha256Hex(data) });\n\t\t} catch (error) {\n\t\t\tlog.error(`Backup skips unreadable file ${path}: ${(error as Error).message}`);\n\t\t}\n\t}\n\tconst dumpJsonText = JSON.stringify(dumpJson, null, 2);\n\tconst dumpBytes = Buffer.byteLength(dumpJsonText);\n\t// the restore refuses what is above its limits, so such a backup must not be created at all\n\tconst problems = backupSizeProblems(\n\t\t{\n\t\t\tdumpBytes,\n\t\t\tunpackedBytes: dumpBytes + [...files, ...attachmentFiles].reduce((sum, file) => sum + file.size, 0),\n\t\t\tentries: files.length + attachmentFiles.length + 2,\n\t\t},\n\t\tcaps,\n\t);\n\tif (problems.length > 0) {\n\t\tthrow new Error(backupTooLargeMessage(problems));\n\t}\n\tzip.file('dump.json', dumpJsonText);\n\tconst manifest: BackupManifest = {\n\t\tapp: BACKUP_APP_ID,\n\t\tformatVersion: BACKUP_FORMAT_VERSION,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tadapterVersion,\n\t\tschemaVersion: dump.schemaVersion,\n\t\tcounts: {\n\t\t\tinvoices: dump.invoices.length,\n\t\t\ttemplates: dump.templates.length,\n\t\t\tattachments: dump.attachments.length,\n\t\t\tcustomers: dump.customers.length,\n\t\t\tfiles: files.length,\n\t\t},\n\t\tfiles,\n\t\tattachmentFiles,\n\t\tdumpSha256: sha256Hex(dumpJsonText),\n\t};\n\tzip.file('manifest.json', JSON.stringify(manifest, null, 2));\n\tconst data = Buffer.from(await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }));\n\tconst zipProblems = backupSizeProblems({ zipBytes: data.length }, caps);\n\tif (zipProblems.length > 0) {\n\t\tthrow new Error(backupTooLargeMessage(zipProblems));\n\t}\n\tconst filename = `${kind === 'auto' ? AUTO_BACKUP_PREFIX : MANUAL_BACKUP_PREFIX}${stampName()}.zip`;\n\treturn { filename, size: data.length, sha256: sha256Hex(data), manifest, data };\n}\n\n/** What a restore would change, without touching anything. */\nexport interface RestorePreview {\n\t/** Manifest of the inspected backup. */\n\tmanifest: BackupManifest;\n\t/** Invoice count in the backup. */\n\tinvoices: number;\n\t/** Issued invoices among them. */\n\tissued: number;\n\t/** Invoice numbers carried by the backup. */\n\tnumbers: string[];\n\t/** Template count. */\n\ttemplates: number;\n\t/** Customer count. */\n\tcustomers: number;\n\t/** Product count. */\n\tproducts: number;\n\t/** Company profile count. */\n\tcompanies: number;\n\t/** Invoice count currently in the database. */\n\tcurrentInvoices: number;\n\t/** Numbers that would be overwritten by this backup. */\n\toverwritten: string[];\n\t/** Numbers that only exist here and would be new. */\n\tadded: string[];\n\t/** Numbers that exist only in the current database and would be removed from it. */\n\tonlyHere: string[];\n\t/** Counters that are ahead of the backup (they are kept, numbers are never reused). */\n\tcounterAhead: string[];\n\t/** Files that would be written. */\n\tfilesWritten: number;\n}\n\n/**\n * Inspects a backup ZIP without writing anything.\n *\n * A restore replaces the whole database, so the user should see exactly what\n * would change before confirming. Every integrity check of the real restore\n * runs here as well, so a broken backup is rejected in the preview and never\n * half-applied.\n *\n * @param db - Open invoice database (read-only use).\n * @param zipData - Backup ZIP bytes.\n * @param limits - Optional ZIP limits (defaults to the production caps).\n * @returns Counts and the diff against the current state.\n * @throws {Error} When the ZIP, manifest, checksums or schema are not usable.\n */\nexport async function previewRestore(\n\tdb: InvoiceDatabase,\n\tzipData: Buffer,\n\tlimits?: Partial<BackupLimits>,\n): Promise<RestorePreview> {\n\tconst { manifest, dump } = await readAndVerifyBackup(zipData, limits);\n\tconst numbers = dump.invoices.map(i => i.number).filter((n): n is string => Boolean(n));\n\tconst currentNumbers = new Set(\n\t\tdb\n\t\t\t.allInvoices()\n\t\t\t.map(i => i.number)\n\t\t\t.filter(Boolean) as string[],\n\t);\n\treturn {\n\t\tmanifest,\n\t\tinvoices: dump.invoices.length,\n\t\tissued: dump.invoices.filter(i => i.status === 'issued').length,\n\t\tnumbers,\n\t\ttemplates: dump.templates.length,\n\t\tcustomers: dump.customers.length,\n\t\tproducts: dump.products.length,\n\t\tcompanies: dump.companies.length,\n\t\tcurrentInvoices: db.allInvoices().length,\n\t\toverwritten: numbers.filter(n => currentNumbers.has(n)),\n\t\tadded: numbers.filter(n => !currentNumbers.has(n)),\n\t\tfilesWritten: (manifest.files ?? []).length,\n\t\tonlyHere: [...currentNumbers].filter(n => !numbers.includes(n)),\n\t\tcounterAhead: mergeCounters(dump.counters, db.exportData().counters).raised,\n\t};\n}\n\n/**\n * Raises the counters of a backup to the current ones where those are higher.\n *\n * A restore may bring back an older state, but a number that was handed out\n * once must never be handed out again (\u00A7 14 Abs. 4 Nr. 4 UStG, GoBD): its\n * PDF/XML may still lie on the mountpoint and would be overwritten.\n *\n * @param fromBackup - Counters of the backup dump.\n * @param current - Counters of the running database.\n * @returns The merged counters and a readable list of those that were raised.\n */\nfunction mergeCounters(\n\tfromBackup: DatabaseDump['counters'],\n\tcurrent: DatabaseDump['counters'],\n): { counters: DatabaseDump['counters']; raised: string[] } {\n\tconst key = (c: { year: number; employee?: string; doc_type?: string }): string =>\n\t\t`${c.year}/${c.employee ?? '00'}/${c.doc_type ?? 'invoice'}`;\n\tconst merged = new Map<string, DatabaseDump['counters'][number]>();\n\tfor (const counter of fromBackup ?? []) {\n\t\tmerged.set(key(counter), counter);\n\t}\n\tconst raised: string[] = [];\n\tfor (const counter of current) {\n\t\tconst existing = merged.get(key(counter));\n\t\tif (!existing || existing.last_seq < counter.last_seq) {\n\t\t\tmerged.set(key(counter), counter);\n\t\t\traised.push(`${key(counter)} (backup ${existing?.last_seq ?? 0}, kept ${counter.last_seq})`);\n\t\t}\n\t}\n\treturn { counters: [...merged.values()], raised };\n}\n\n/**\n * Opens a backup ZIP and verifies it completely: structure, application id,\n * format version, schema compatibility, per-file checksums and the dump\n * checksum. Shared by the preview and the real restore, so a broken backup\n * can never be half applied.\n *\n * @param zipData - Backup ZIP bytes.\n * @param limits - Optional ZIP limits (defaults to the production caps).\n * @returns The verified manifest, the parsed database dump and the verified files.\n * @throws {Error} When anything about the archive is unusable.\n */\nasync function readAndVerifyBackup(\n\tzipData: Buffer,\n\tlimits?: Partial<BackupLimits>,\n): Promise<{ manifest: BackupManifest; dump: DatabaseDump; files: { path: string; data: Buffer }[] }> {\n\tconst caps = resolveLimits(limits);\n\tif (zipData.length > caps.zipBytes) {\n\t\tthrow new Error(`Backup ZIP is too large (${zipData.length} bytes, limit ${caps.zipBytes})`);\n\t}\n\tlet zip: JSZip;\n\ttry {\n\t\tzip = await JSZip.loadAsync(zipData);\n\t} catch {\n\t\tthrow new Error('File is no valid backup ZIP');\n\t}\n\t// ZIP bomb guard: entry count and declared sizes are checked before the\n\t// first entry is decompressed.\n\tconst names = Object.keys(zip.files);\n\tif (names.length > caps.entries) {\n\t\tthrow new Error(`Backup ZIP has too many entries (${names.length}, limit ${caps.entries})`);\n\t}\n\tlet declared = 0;\n\tfor (const name of names) {\n\t\tconst size = declaredSize(zip.files[name]);\n\t\tif (size === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tdeclared += size;\n\t\tif (declared > caps.unpackedBytes) {\n\t\t\tthrow new Error(`Backup ZIP would expand to at least ${declared} bytes (limit ${caps.unpackedBytes})`);\n\t\t}\n\t}\n\tconst manifestFile = zip.file('manifest.json');\n\tconst dumpFile = zip.file('dump.json');\n\tif (!manifestFile || !dumpFile) {\n\t\tthrow new Error('Backup ZIP misses manifest.json or dump.json');\n\t}\n\tconst manifest = JSON.parse(await manifestFile.async('string')) as BackupManifest;\n\tif (manifest.app !== BACKUP_APP_ID || !SUPPORTED_BACKUP_FORMATS.includes(manifest.formatVersion)) {\n\t\tthrow new Error(`Unsupported backup (app=${String(manifest.app)}, format=${String(manifest.formatVersion)})`);\n\t}\n\tif (manifest.schemaVersion > LATEST_SCHEMA_VERSION) {\n\t\tthrow new Error(`Backup needs schema v${manifest.schemaVersion}, adapter knows v${LATEST_SCHEMA_VERSION}`);\n\t}\n\t// Read the artifact files once: the restore writes exactly these buffers,\n\t// so a second read can no longer fail after the database was replaced.\n\tconst files: { path: string; data: Buffer }[] = [];\n\tlet unpacked = 0;\n\tfor (const file of manifest.files ?? []) {\n\t\tassertSafeEntryPath(file.path);\n\t\tconst entry = zip.file(`files/${file.path}`);\n\t\tif (!entry) {\n\t\t\tthrow new Error(`Backup misses file: files/${file.path}`);\n\t\t}\n\t\tconst data = Buffer.from(await entry.async('nodebuffer'));\n\t\tunpacked += data.length;\n\t\tif (unpacked > caps.unpackedBytes) {\n\t\t\tthrow new Error(`Backup expands to more than ${caps.unpackedBytes} bytes`);\n\t\t}\n\t\tif (sha256Hex(data) !== file.sha256 || data.length !== file.size) {\n\t\t\tthrow new Error(`Checksum mismatch: files/${file.path}`);\n\t\t}\n\t\tfiles.push({ path: file.path, data });\n\t}\n\n\t// attachment contents (format 2): hashed like the files, checked against the sizes in the dump below\n\tconst attachmentData = new Map<number, Buffer>();\n\tfor (const file of manifest.attachmentFiles ?? []) {\n\t\tconst id = Number(file.path);\n\t\tif (!Number.isInteger(id) || id < 0 || String(id) !== file.path) {\n\t\t\tthrow new Error(`Backup lists an invalid attachment id: ${file.path}`);\n\t\t}\n\t\tconst entry = zip.file(`attachments/${id}`);\n\t\tif (!entry) {\n\t\t\tthrow new Error(`Backup misses attachment: attachments/${id}`);\n\t\t}\n\t\tconst data = Buffer.from(await entry.async('nodebuffer'));\n\t\tunpacked += data.length;\n\t\tif (unpacked > caps.unpackedBytes) {\n\t\t\tthrow new Error(`Backup expands to more than ${caps.unpackedBytes} bytes`);\n\t\t}\n\t\tif (sha256Hex(data) !== file.sha256 || data.length !== file.size) {\n\t\t\tthrow new Error(`Checksum mismatch: attachments/${id}`);\n\t\t}\n\t\tattachmentData.set(id, data);\n\t}\n\n\tconst declaredDump = declaredSize(dumpFile);\n\tif (declaredDump !== undefined && declaredDump > caps.dumpBytes) {\n\t\tthrow new Error(`Backup dump.json is too large (${declaredDump} bytes, limit ${caps.dumpBytes})`);\n\t}\n\tconst dumpJsonText = await dumpFile.async('string');\n\tif (Buffer.byteLength(dumpJsonText, 'utf8') > caps.dumpBytes) {\n\t\tthrow new Error(`Backup dump.json is too large (limit ${caps.dumpBytes})`);\n\t}\n\tif (manifest.dumpSha256 && sha256Hex(dumpJsonText) !== manifest.dumpSha256) {\n\t\tthrow new Error('Checksum mismatch: dump.json');\n\t}\n\tlet dumpJson: Omit<DatabaseDump, 'attachments'> & { attachments: DumpJsonAttachment[] };\n\ttry {\n\t\tdumpJson = JSON.parse(dumpJsonText) as typeof dumpJson;\n\t} catch {\n\t\tthrow new Error('Backup ZIP is corrupt: dump.json is not readable JSON');\n\t}\n\tconst dump: DatabaseDump = {\n\t\tformatVersion: 1,\n\t\texportedAt: String(dumpJson.exportedAt ?? new Date().toISOString()),\n\t\tschemaVersion: Number(dumpJson.schemaVersion ?? 0),\n\t\tinvoices: dumpJson.invoices ?? [],\n\t\tcounters: dumpJson.counters ?? [],\n\t\ttemplates: dumpJson.templates ?? [],\n\t\tcompanies: dumpJson.companies ?? [],\n\t\tcustomers: dumpJson.customers ?? [],\n\t\tproducts: dumpJson.products ?? [],\n\t\tdunningTexts: dumpJson.dunningTexts,\n\t\tattachments: (dumpJson.attachments ?? []).map(attachment => {\n\t\t\tlet data: Buffer;\n\t\t\tif (attachment.dataBase64 !== undefined) {\n\t\t\t\tdata = Buffer.from(attachment.dataBase64, 'base64');\n\t\t\t} else {\n\t\t\t\tconst own = attachmentData.get(attachment.id);\n\t\t\t\tif (!own) {\n\t\t\t\t\tthrow new Error(`Backup has no content for attachment ${attachment.id} (${attachment.filename})`);\n\t\t\t\t}\n\t\t\t\tdata = own;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tid: attachment.id,\n\t\t\t\tinvoiceId: attachment.invoiceId,\n\t\t\t\tfilename: attachment.filename,\n\t\t\t\tmime: attachment.mime,\n\t\t\t\t// the content decides, not a number in dump.json\n\t\t\t\tsize: data.length,\n\t\t\t\tdata,\n\t\t\t\tcreatedAt: attachment.createdAt,\n\t\t\t};\n\t\t}),\n\t};\n\tassertSafeRecords(dump);\n\treturn { manifest, dump, files };\n}\n\n/**\n * Restores a backup ZIP: verifies the manifest, replaces the database\n * transactionally and rewrites the files.\n *\n * @param db - Open invoice database.\n * @param storage - File backend for writing artifacts.\n * @param zipData - Backup ZIP bytes.\n * @param log - Logger.\n * @param limits - Optional ZIP limits (defaults to the production caps).\n * @param options - Adapter version for the safety backup and the source for the restore log.\n * @param options.adapterVersion - Adapter version written into the safety backup.\n * @param options.source - Where the restore came from (`api`, `state`, ...).\n */\nexport async function restoreBackup(\n\tdb: InvoiceDatabase,\n\tstorage: BackupStorage,\n\tzipData: Buffer,\n\tlog: BackupLogger,\n\tlimits?: Partial<BackupLimits>,\n\toptions: { adapterVersion?: string; source?: string } = {},\n): Promise<RestoreSummary> {\n\tconst { manifest, dump, files } = await readAndVerifyBackup(zipData, limits);\n\n\t// H3: a restore replaces everything, so the current state is saved first.\n\t// Without that copy the restore is not started.\n\tlet safetyBackup: string | null = null;\n\ttry {\n\t\tconst safety = await createBackup(db, storage, log, options.adapterVersion ?? 'unknown');\n\t\tsafetyBackup = safety.filename.replace('-backup-', '-prerestore-');\n\t\tawait storage.write(safetyBackup, safety.data);\n\t\tdb.logBackup({\n\t\t\tfilename: safetyBackup,\n\t\t\tsize: safety.size,\n\t\t\tsha256: safety.sha256,\n\t\t\tmanifestJson: JSON.stringify(safety.manifest),\n\t\t});\n\t\tlog.info(`Safety backup before restore: ${safetyBackup}`);\n\t} catch (error) {\n\t\tthrow new Error(`Restore aborted: the safety backup of the current state failed (${(error as Error).message})`);\n\t}\n\n\t// H3: counters never move backwards, so no issued number is reused.\n\tconst { counters, raised } = mergeCounters(dump.counters, db.exportData().counters);\n\tdump.counters = counters;\n\tif (raised.length > 0) {\n\t\tlog.info(`Restore keeps ${raised.length} counter(s) ahead of the backup: ${raised.join('; ')}`);\n\t}\n\n\tdb.importData(dump);\n\tif (!db.getDefaultTemplate()) {\n\t\tdb.ensureDefaultTemplate();\n\t}\n\tlog.info(`Database restored: ${dump.invoices.length} invoices, ${dump.templates.length} templates`);\n\n\tconst filesWritten: string[] = [];\n\tconst fileErrors: string[] = [];\n\tfor (const file of files) {\n\t\ttry {\n\t\t\tawait storage.write(file.path, file.data);\n\t\t\tfilesWritten.push(file.path);\n\t\t} catch (error) {\n\t\t\tconst message = `${file.path}: ${(error as Error).message}`;\n\t\t\tfileErrors.push(message);\n\t\t\tlog.error(`Restore cannot write ${message}`);\n\t\t}\n\t}\n\n\t// audit trail: who restored what and when stays readable outside the database\n\ttry {\n\t\tlet previous = '';\n\t\ttry {\n\t\t\tprevious = (await storage.read('backups/restore-log.jsonl')).toString('utf8');\n\t\t} catch {\n\t\t\t// first entry\n\t\t}\n\t\tconst entry = JSON.stringify({\n\t\t\tat: new Date().toISOString(),\n\t\t\tsource: options.source ?? 'api',\n\t\t\tbackupCreatedAt: manifest.createdAt,\n\t\t\tinvoices: dump.invoices.length,\n\t\t\tsafetyBackup,\n\t\t\tcountersKept: raised,\n\t\t});\n\t\tawait storage.write('backups/restore-log.jsonl', `${previous}${entry}\\n`);\n\t} catch (error) {\n\t\tlog.error(`Cannot write the restore log: ${(error as Error).message}`);\n\t}\n\treturn {\n\t\tmanifest,\n\t\tinvoices: dump.invoices.length,\n\t\ttemplates: dump.templates.length,\n\t\tfilesWritten,\n\t\tfileErrors,\n\t\tsafetyBackup,\n\t\tcountersKept: raised,\n\t};\n}\n\n/** An entry of the backup log, as far as the schedule needs it. */\nexport interface BackupLogItem {\n\t/** Path below the storage mount, e.g. `backups/e-invoices-auto-\u2026.zip`. */\n\tfilename: string;\n\t/** ISO creation time. */\n\tcreatedAt: string;\n}\n\n/**\n * Picks the automatic backups that exceed the number to keep (the oldest ones).\n *\n * Only files with the automatic prefix qualify: backups the user made by hand and the\n * safety backups before a restore are never touched. `keep` 0 (or less) keeps everything.\n *\n * @param entries - The backup log.\n * @param keep - How many automatic backups to keep.\n * @returns File names to delete.\n */\nexport function selectBackupsToPrune(entries: BackupLogItem[], keep: number): string[] {\n\tif (!Number.isFinite(keep) || keep <= 0) {\n\t\treturn [];\n\t}\n\treturn entries\n\t\t.filter(entry => entry.filename.startsWith(AUTO_BACKUP_PREFIX))\n\t\t.sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n\t\t.slice(Math.floor(keep))\n\t\t.map(entry => entry.filename);\n}\n\n/** Never sooner than this after a start, so a restarting adapter does not back up in a loop. */\nconst MIN_BACKUP_DELAY_MS = 60_000;\n\n/**\n * Delay until the next automatic backup.\n *\n * The schedule survives restarts: the interval counts from the last automatic backup, not from\n * the start of the adapter. Without one \u2014 or when it is overdue \u2014 the backup runs a minute\n * after the start.\n *\n * @param lastAutoAt - ISO time of the newest automatic backup, null when there is none.\n * @param intervalMs - Backup interval.\n * @param now - Current time in ms.\n */\nexport function nextBackupDelayMs(lastAutoAt: string | null, intervalMs: number, now: number): number {\n\tconst last = lastAutoAt ? Date.parse(lastAutoAt) : Number.NaN;\n\tif (!Number.isFinite(last)) {\n\t\treturn MIN_BACKUP_DELAY_MS;\n\t}\n\treturn Math.min(intervalMs, Math.max(MIN_BACKUP_DELAY_MS, last + intervalMs - now));\n}\n\n/** How current the newest backup is. */\nexport interface BackupStatus {\n\t/** ISO time of the newest backup of any kind, null when there is none. */\n\tlastAt: string | null;\n\t/** Age of that backup in hours, null when there is none. */\n\tageHours: number | null;\n\t/** `none` = no backup at all, `stale` = too old, null = fine. */\n\twarning: 'none' | 'stale' | null;\n\t/** Configured interval in minutes, 0 = automatic backup off. */\n\tintervalMinutes: number;\n\t/** Automatic backups kept, 0 = all. */\n\tkeep: number;\n}\n\n/**\n * Judges the backup log.\n *\n * Stale means: older than twice the interval but at least two days with the automatic backup\n * on; older than a week with it off. Backup is the only protection of the database against the\n * BackItUp gap (the database file itself is not part of an ioBroker backup).\n *\n * @param entries - The backup log.\n * @param intervalMinutes - Configured interval, 0 = off.\n * @param keep - Automatic backups kept.\n * @param now - Current time in ms.\n */\nexport function backupStatus(\n\tentries: BackupLogItem[],\n\tintervalMinutes: number,\n\tkeep: number,\n\tnow: number,\n): BackupStatus {\n\tconst newest = entries.map(entry => entry.createdAt).sort((a, b) => b.localeCompare(a))[0] ?? null;\n\tconst base = { intervalMinutes, keep };\n\tif (!newest) {\n\t\treturn { lastAt: null, ageHours: null, warning: 'none', ...base };\n\t}\n\tconst ageMs = now - Date.parse(newest);\n\tconst limitMs = intervalMinutes > 0 ? Math.max(2 * intervalMinutes * 60_000, 48 * 3_600_000) : 7 * 24 * 3_600_000;\n\treturn {\n\t\tlastAt: newest,\n\t\tageHours: Math.max(0, Math.round(ageMs / 3_600_000)),\n\t\twarning: ageMs > limitMs ? 'stale' : null,\n\t\t...base,\n\t};\n}\n\n/** The sizes of a backup that the restore limits apply to; every field is optional. */\nexport interface BackupSizes {\n\t/** Size of the finished ZIP. */\n\tzipBytes?: number;\n\t/** Size of `dump.json`. */\n\tdumpBytes?: number;\n\t/** Sum of everything the ZIP unpacks to. */\n\tunpackedBytes?: number;\n\t/** Number of entries in the ZIP. */\n\tentries?: number;\n}\n\n/**\n * Compares the sizes of a backup with the limits the restore enforces (M2).\n *\n * A backup the restore would refuse is no backup: it would only be found out in the emergency. The same\n * limits protect against crafted ZIPs on the way in; here they protect the user on the way out.\n *\n * @param sizes - What is known about the backup so far.\n * @param limits - The restore limits.\n * @returns One text per exceeded limit, empty when the backup could be restored.\n */\nexport function backupSizeProblems(sizes: BackupSizes, limits: BackupLimits): string[] {\n\tconst mb = (bytes: number): string => `${(bytes / 1048576).toFixed(1)} MB`;\n\tconst out: string[] = [];\n\tif (sizes.dumpBytes !== undefined && sizes.dumpBytes > limits.dumpBytes) {\n\t\tout.push(`the database part (dump.json) would be ${mb(sizes.dumpBytes)}, the limit is ${mb(limits.dumpBytes)}`);\n\t}\n\tif (sizes.unpackedBytes !== undefined && sizes.unpackedBytes > limits.unpackedBytes) {\n\t\tout.push(`the backup would unpack to ${mb(sizes.unpackedBytes)}, the limit is ${mb(limits.unpackedBytes)}`);\n\t}\n\tif (sizes.zipBytes !== undefined && sizes.zipBytes > limits.zipBytes) {\n\t\tout.push(`the ZIP would be ${mb(sizes.zipBytes)}, the limit is ${mb(limits.zipBytes)}`);\n\t}\n\tif (sizes.entries !== undefined && sizes.entries > limits.entries) {\n\t\tout.push(`the ZIP would hold ${sizes.entries} files, the limit is ${limits.entries}`);\n\t}\n\treturn out;\n}\n\n/**\n * The error text for a backup that is too large to be restored.\n *\n * @param problems - Result of `backupSizeProblems`.\n */\nfunction backupTooLargeMessage(problems: string[]): string {\n\treturn `Backup not created, it could not be restored: ${problems.join('; ')}. Reduce the attachments, or rely on the instance backup (BackItUp) for the files.`;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,mBAAkB;AAClB,yBAA2B;AAE3B,2BAAwB;AACxB,wBAAsC;AAG/B,MAAM,uBAAuB;AAG7B,MAAM,qBAAqB;AAG3B,MAAM,gBAAgB;AAGtB,MAAM,wBAAwB;AAGrC,MAAM,2BAA2B,CAAC,GAAG,CAAC;AAkFtC,SAAS,UAAU,MAA+B;AACjD,aAAO,+BAAW,QAAQ,EAAE,OAAO,IAAI,EAAE,OAAO,KAAK;AACtD;AAQA,SAAS,oBAAoB,SAA6C;AACzE,MAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,MAAM,IAAI;AACzD,UAAM,IAAI,MAAM,+CAA+C;AAAA,EAChE;AACA,MAAI,QAAQ,SAAS,IAAI,KAAK,QAAQ,WAAW,GAAG,KAAK,aAAa,KAAK,OAAO,GAAG;AACpF,UAAM,IAAI,MAAM,iDAAiD,OAAO,EAAE;AAAA,EAC3E;AACA,aAAW,WAAW,QAAQ,MAAM,GAAG,GAAG;AACzC,QAAI,YAAY,QAAQ,YAA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