@eutobias/serenojs 0.0.0-stage → 0.1.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.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +682 -2
  3. package/admin-dist/assets/index-B3EgqtT6.js +9 -0
  4. package/admin-dist/assets/index-D2m0Eb4k.css +2 -0
  5. package/admin-dist/index.html +17 -0
  6. package/dist/auth/auth.server.d.ts +31 -0
  7. package/dist/auth/auth.server.js +141 -0
  8. package/dist/auth/config.d.ts +32 -0
  9. package/dist/auth/config.js +25 -0
  10. package/dist/auth/cookies.server.d.ts +7 -0
  11. package/dist/auth/cookies.server.js +65 -0
  12. package/dist/auth/http.server.d.ts +8 -0
  13. package/dist/auth/http.server.js +30 -0
  14. package/dist/auth/password.server.d.ts +2 -0
  15. package/dist/auth/password.server.js +21 -0
  16. package/dist/auth/session.server.d.ts +2 -0
  17. package/dist/auth/session.server.js +14 -0
  18. package/dist/auth/users.server.d.ts +16 -0
  19. package/dist/auth/users.server.js +123 -0
  20. package/dist/config.d.ts +91 -0
  21. package/dist/config.js +39 -0
  22. package/dist/core/backup.server.d.ts +52 -0
  23. package/dist/core/backup.server.js +349 -0
  24. package/dist/core/db.server.d.ts +24 -0
  25. package/dist/core/db.server.js +526 -0
  26. package/dist/core/media.d.ts +22 -0
  27. package/dist/core/media.js +76 -0
  28. package/dist/core/media.server.d.ts +18 -0
  29. package/dist/core/media.server.js +102 -0
  30. package/dist/core/schema.d.ts +26 -0
  31. package/dist/core/schema.js +99 -0
  32. package/dist/core/types.d.ts +143 -0
  33. package/dist/core/types.js +1 -0
  34. package/dist/core/validation.d.ts +16 -0
  35. package/dist/core/validation.js +192 -0
  36. package/dist/locale.d.ts +2 -0
  37. package/dist/locale.js +14 -0
  38. package/dist/runtime.d.ts +8 -0
  39. package/dist/runtime.js +37 -0
  40. package/dist/server/app.d.ts +20 -0
  41. package/dist/server/app.js +661 -0
  42. package/dist/ui/admin/admin-shell.d.ts +16 -0
  43. package/dist/ui/admin/admin-shell.js +38 -0
  44. package/dist/ui/admin/backup-manager.d.ts +5 -0
  45. package/dist/ui/admin/backup-manager.js +165 -0
  46. package/dist/ui/admin/collection-icon.d.ts +22 -0
  47. package/dist/ui/admin/collection-icon.js +34 -0
  48. package/dist/ui/admin/collection-manager.d.ts +7 -0
  49. package/dist/ui/admin/collection-manager.js +212 -0
  50. package/dist/ui/admin/display.d.ts +7 -0
  51. package/dist/ui/admin/display.js +65 -0
  52. package/dist/ui/admin/field-control.d.ts +14 -0
  53. package/dist/ui/admin/field-control.js +58 -0
  54. package/dist/ui/admin/i18n.d.ts +27 -0
  55. package/dist/ui/admin/i18n.js +324 -0
  56. package/dist/ui/admin/item-form.d.ts +20 -0
  57. package/dist/ui/admin/item-form.js +60 -0
  58. package/dist/ui/admin/list-control.d.ts +13 -0
  59. package/dist/ui/admin/list-control.js +31 -0
  60. package/dist/ui/admin/locales.d.ts +4 -0
  61. package/dist/ui/admin/locales.js +8 -0
  62. package/dist/ui/admin/login-form.d.ts +3 -0
  63. package/dist/ui/admin/login-form.js +52 -0
  64. package/dist/ui/admin/media-control.d.ts +14 -0
  65. package/dist/ui/admin/media-control.js +74 -0
  66. package/dist/ui/admin/media-list-control.d.ts +14 -0
  67. package/dist/ui/admin/media-list-control.js +91 -0
  68. package/dist/ui/admin/pagination.d.ts +11 -0
  69. package/dist/ui/admin/pagination.js +14 -0
  70. package/dist/ui/admin/relation-control.d.ts +14 -0
  71. package/dist/ui/admin/relation-control.js +33 -0
  72. package/dist/ui/admin/router.d.ts +17 -0
  73. package/dist/ui/admin/router.js +58 -0
  74. package/dist/ui/admin/runtime.d.ts +28 -0
  75. package/dist/ui/admin/runtime.js +29 -0
  76. package/dist/ui/admin/sidebar.d.ts +13 -0
  77. package/dist/ui/admin/sidebar.js +29 -0
  78. package/dist/ui/admin/standalone-manager.d.ts +11 -0
  79. package/dist/ui/admin/standalone-manager.js +51 -0
  80. package/dist/ui/admin/table.d.ts +21 -0
  81. package/dist/ui/admin/table.js +23 -0
  82. package/dist/ui/admin/toast.d.ts +16 -0
  83. package/dist/ui/admin/toast.js +59 -0
  84. package/dist/ui/admin/users-manager.d.ts +6 -0
  85. package/dist/ui/admin/users-manager.js +157 -0
  86. package/dist/ui/badge.d.ts +9 -0
  87. package/dist/ui/badge.js +14 -0
  88. package/dist/ui/box.d.ts +17 -0
  89. package/dist/ui/box.js +14 -0
  90. package/dist/ui/button.d.ts +25 -0
  91. package/dist/ui/button.js +28 -0
  92. package/dist/ui/card.d.ts +45 -0
  93. package/dist/ui/card.js +49 -0
  94. package/dist/ui/container.d.ts +13 -0
  95. package/dist/ui/container.js +13 -0
  96. package/dist/ui/drawer.d.ts +15 -0
  97. package/dist/ui/drawer.js +31 -0
  98. package/dist/ui/field-wrapper.d.ts +15 -0
  99. package/dist/ui/field-wrapper.js +11 -0
  100. package/dist/ui/index.d.ts +8 -0
  101. package/dist/ui/index.js +8 -0
  102. package/dist/ui/text.d.ts +19 -0
  103. package/dist/ui/text.js +40 -0
  104. package/package.json +81 -3
  105. package/src/admin/app.tsx +371 -0
  106. package/src/admin/index.html +16 -0
  107. package/src/admin/main.tsx +42 -0
  108. package/src/admin/styles.css +9 -0
  109. package/src/auth/auth.server.ts +203 -0
  110. package/src/auth/config.ts +46 -0
  111. package/src/auth/cookies.server.ts +84 -0
  112. package/src/auth/http.server.ts +32 -0
  113. package/src/auth/password.server.ts +25 -0
  114. package/src/auth/session.server.ts +16 -0
  115. package/src/auth/users.server.ts +159 -0
  116. package/src/config.ts +120 -0
  117. package/src/core/backup.server.ts +446 -0
  118. package/src/core/db.server.ts +685 -0
  119. package/src/core/media.server.ts +136 -0
  120. package/src/core/media.ts +91 -0
  121. package/src/core/schema.ts +126 -0
  122. package/src/core/types.ts +194 -0
  123. package/src/core/validation.ts +215 -0
  124. package/src/global.d.ts +1 -0
  125. package/src/locale.ts +16 -0
  126. package/src/runtime.ts +54 -0
  127. package/src/server/app.ts +737 -0
  128. package/src/ui/admin/admin-shell.tsx +106 -0
  129. package/src/ui/admin/backup-manager.tsx +327 -0
  130. package/src/ui/admin/collection-icon.tsx +69 -0
  131. package/src/ui/admin/collection-manager.tsx +408 -0
  132. package/src/ui/admin/display.tsx +138 -0
  133. package/src/ui/admin/field-control.tsx +214 -0
  134. package/src/ui/admin/i18n.tsx +401 -0
  135. package/src/ui/admin/item-form.tsx +200 -0
  136. package/src/ui/admin/list-control.tsx +121 -0
  137. package/src/ui/admin/locales.ts +12 -0
  138. package/src/ui/admin/login-form.tsx +98 -0
  139. package/src/ui/admin/media-control.tsx +161 -0
  140. package/src/ui/admin/media-list-control.tsx +242 -0
  141. package/src/ui/admin/pagination.tsx +58 -0
  142. package/src/ui/admin/relation-control.tsx +142 -0
  143. package/src/ui/admin/router.tsx +105 -0
  144. package/src/ui/admin/runtime.tsx +58 -0
  145. package/src/ui/admin/sidebar.tsx +178 -0
  146. package/src/ui/admin/standalone-manager.tsx +103 -0
  147. package/src/ui/admin/table.tsx +129 -0
  148. package/src/ui/admin/toast.tsx +126 -0
  149. package/src/ui/admin/users-manager.tsx +344 -0
  150. package/src/ui/badge.tsx +27 -0
  151. package/src/ui/box.tsx +33 -0
  152. package/src/ui/button.tsx +77 -0
  153. package/src/ui/card.tsx +92 -0
  154. package/src/ui/container.tsx +28 -0
  155. package/src/ui/drawer.tsx +104 -0
  156. package/src/ui/field-wrapper.tsx +54 -0
  157. package/src/ui/index.ts +8 -0
  158. package/src/ui/text.tsx +93 -0
@@ -0,0 +1,446 @@
1
+ /**
2
+ * Database + uploaded-assets backup and restore.
3
+ *
4
+ * A backup is a single gzip-compressed JSON archive (`<name>.serenojs`) that
5
+ * bundles:
6
+ * - a consistent SQLite snapshot of `.data/admin.db` (via `VACUUM INTO`),
7
+ * - every file under `public/images` (committed assets) and `public/files`
8
+ * (runtime uploads), stored as base64.
9
+ *
10
+ * The module also runs a lightweight scheduler that drops a fresh backup into
11
+ * `.data/backups` on startup (when overdue) and then every N hours.
12
+ *
13
+ * Server-only: reads/writes the filesystem and talks to the DB layer.
14
+ */
15
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join, relative, resolve, sep } from "node:path";
18
+ import { gunzipSync, gzipSync } from "node:zlib";
19
+
20
+ import { getDb } from "./db.server.js";
21
+ import { getCmsConfig } from "../runtime.js";
22
+
23
+ export const BACKUP_FORMAT = "serenojs-backup";
24
+ export const BACKUP_VERSION = 1;
25
+ export const BACKUP_EXTENSION = ".serenojs";
26
+
27
+ export const BACKUP_DIR = resolve(process.cwd(), ".data/backups");
28
+ export const PUBLIC_DIR = resolve(process.cwd(), "public");
29
+
30
+ /** Directories (relative to `public/`) included in a backup. */
31
+ const ASSET_DIRS = ["images", "files"] as const;
32
+
33
+ const SQLITE_MAGIC = "SQLite format 3\u0000";
34
+
35
+ export class BackupError extends Error {
36
+ status: number;
37
+ constructor(message: string, status = 422) {
38
+ super(message);
39
+ this.status = status;
40
+ }
41
+ }
42
+
43
+ export type BackupInfo = {
44
+ name: string;
45
+ size: number;
46
+ createdAt: string;
47
+ /** Number of bundled assets, or `null` when unknown (list view). */
48
+ assets: number | null;
49
+ };
50
+
51
+ export type BackupManifest = {
52
+ format: string;
53
+ version: number;
54
+ createdAt: string;
55
+ databaseBytes: number;
56
+ assets: number;
57
+ };
58
+
59
+ type BackupAsset = { path: string; data: string };
60
+
61
+ type BackupPayload = {
62
+ format: string;
63
+ version: number;
64
+ createdAt: string;
65
+ database: string;
66
+ assets: BackupAsset[];
67
+ };
68
+
69
+ const NAME_RE = /^[a-zA-Z0-9._-]+\.serenojs$/;
70
+
71
+ function nowStamp(): string {
72
+ return new Date().toISOString().replace(/[:.]/g, "-");
73
+ }
74
+
75
+ function ensureDir(dir: string): void {
76
+ mkdirSync(dir, { recursive: true });
77
+ }
78
+
79
+ /** Recursively collect files under `dir`, keyed by their path relative to `base`. */
80
+ function collectFiles(dir: string, base: string, out: Map<string, string>): void {
81
+ if (!existsSync(dir)) return;
82
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
83
+ const full = join(dir, entry.name);
84
+ if (entry.isDirectory()) {
85
+ collectFiles(full, base, out);
86
+ } else if (entry.isFile()) {
87
+ const rel = relative(base, full).split(sep).join("/");
88
+ out.set(rel, full);
89
+ }
90
+ }
91
+ }
92
+
93
+ /** Consistent snapshot of the live database file. */
94
+ function snapshotDatabase(): Buffer {
95
+ const db = getDb();
96
+ const tmp = join(
97
+ tmpdir(),
98
+ `serenojs-${Date.now()}-${Math.random().toString(16).slice(2)}.db`,
99
+ );
100
+ try {
101
+ // `VACUUM INTO` writes a transactionally consistent copy, WAL included.
102
+ db.exec(`VACUUM INTO '${tmp.replace(/'/g, "''")}'`);
103
+ return readFileSync(tmp);
104
+ } finally {
105
+ rmSync(tmp, { force: true });
106
+ }
107
+ }
108
+
109
+ /** Build the raw (uncompressed) `.serenojs` payload. */
110
+ function buildPayload(): BackupPayload {
111
+ const database = snapshotDatabase();
112
+
113
+ const files = new Map<string, string>();
114
+ for (const dir of ASSET_DIRS) {
115
+ collectFiles(join(PUBLIC_DIR, dir), PUBLIC_DIR, files);
116
+ }
117
+
118
+ const assets: BackupAsset[] = [];
119
+ for (const [path, full] of files) {
120
+ assets.push({ path, data: readFileSync(full).toString("base64") });
121
+ }
122
+ assets.sort((a, b) => a.path.localeCompare(b.path));
123
+
124
+ return {
125
+ format: BACKUP_FORMAT,
126
+ version: BACKUP_VERSION,
127
+ createdAt: new Date().toISOString(),
128
+ database: database.toString("base64"),
129
+ assets,
130
+ };
131
+ }
132
+
133
+ /** Create an in-memory backup archive (gzip). */
134
+ export function createBackupBuffer(): Buffer {
135
+ return gzipSync(Buffer.from(JSON.stringify(buildPayload()), "utf8"));
136
+ }
137
+
138
+ /** Create a backup and persist it under `.data/backups`. Returns its metadata. */
139
+ export function createBackup(): BackupInfo {
140
+ ensureDir(BACKUP_DIR);
141
+ const name = `backup-${nowStamp()}-${Math.random().toString(16).slice(2, 8)}${BACKUP_EXTENSION}`;
142
+ const buffer = createBackupBuffer();
143
+ const path = join(BACKUP_DIR, name);
144
+ writeFileSync(path, buffer);
145
+
146
+ const info = inspectBackup(buffer);
147
+ return { name, size: buffer.length, ...info };}
148
+
149
+ function inspectBackup(buffer: Buffer): { createdAt: string; assets: number } {
150
+ const payload = parsePayload(buffer);
151
+ return { createdAt: payload.createdAt, assets: payload.assets.length };
152
+ }
153
+
154
+ function parsePayload(buffer: Buffer): BackupPayload {
155
+ let json: unknown;
156
+ try {
157
+ json = JSON.parse(gunzipSync(buffer).toString("utf8"));
158
+ } catch {
159
+ throw new BackupError("Arquivo de backup inválido ou corrompido.");
160
+ }
161
+
162
+ const payload = json as Partial<BackupPayload>;
163
+ if (
164
+ payload?.format !== BACKUP_FORMAT ||
165
+ typeof payload.database !== "string" ||
166
+ !Array.isArray(payload.assets)
167
+ ) {
168
+ throw new BackupError("Formato de backup não reconhecido.");
169
+ }
170
+ return payload as BackupPayload;
171
+ }
172
+
173
+ /** List stored backups, newest first. */
174
+ export function listBackups(): BackupInfo[] {
175
+ if (!existsSync(BACKUP_DIR)) return [];
176
+ return readdirSync(BACKUP_DIR)
177
+ .filter((name) => NAME_RE.test(name))
178
+ .map((name) => {
179
+ const full = join(BACKUP_DIR, name);
180
+ const stat = statSync(full);
181
+ return {
182
+ name,
183
+ size: stat.size,
184
+ createdAt: stat.mtime.toISOString(),
185
+ assets: null,
186
+ } satisfies BackupInfo;
187
+ })
188
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
189
+ }
190
+
191
+ function safeBackupPath(name: string): string {
192
+ if (!NAME_RE.test(name)) {
193
+ throw new BackupError("Nome de backup inválido.", 400);
194
+ }
195
+ const full = join(BACKUP_DIR, name);
196
+ if (!full.startsWith(BACKUP_DIR)) {
197
+ throw new BackupError("Nome de backup inválido.", 400);
198
+ }
199
+ if (!existsSync(full)) {
200
+ throw new BackupError("Backup não encontrado.", 404);
201
+ }
202
+ return full;
203
+ }
204
+
205
+ /** Read a stored backup into memory. */
206
+ export function readBackup(name: string): { info: BackupInfo; buffer: Buffer } {
207
+ const full = safeBackupPath(name);
208
+ const buffer = readFileSync(full);
209
+ const stat = statSync(full);
210
+ return {
211
+ info: {
212
+ name,
213
+ size: stat.size,
214
+ createdAt: stat.mtime.toISOString(),
215
+ assets: null,
216
+ },
217
+ buffer,
218
+ };
219
+ }
220
+
221
+ /** Delete a stored backup. Returns true when a file was removed. */
222
+ export function deleteBackup(name: string): boolean {
223
+ const full = safeBackupPath(name);
224
+ rmSync(full, { force: true });
225
+ return true;
226
+ }
227
+
228
+ /** Keep only the `keep` most recent backups. */
229
+ export function pruneBackups(keep: number): number {
230
+ const limit = Math.max(1, Math.floor(keep));
231
+ const list = listBackups();
232
+ let removed = 0;
233
+ for (const backup of list.slice(limit)) {
234
+ rmSync(join(BACKUP_DIR, backup.name), { force: true });
235
+ removed += 1;
236
+ }
237
+ return removed;
238
+ }
239
+
240
+ function writeAsset(path: string, data: Buffer): void {
241
+ const normalized = path.replace(/\\/g, "/");
242
+ if (
243
+ normalized.includes("..") ||
244
+ !ASSET_DIRS.some((dir) => normalized.startsWith(`${dir}/`))
245
+ ) {
246
+ throw new BackupError(`Caminho de arquivo inválido no backup: ${path}`);
247
+ }
248
+ const target = resolve(PUBLIC_DIR, normalized);
249
+ if (!target.startsWith(PUBLIC_DIR + sep)) {
250
+ throw new BackupError(`Caminho de arquivo inválido no backup: ${path}`);
251
+ }
252
+ ensureDir(resolve(target, ".."));
253
+ writeFileSync(target, data);
254
+ }
255
+
256
+ /** Table names present in `main` (excluding SQLite internals). */
257
+ function mainTables(db: ReturnType<typeof getDb>): string[] {
258
+ return (
259
+ db
260
+ .prepare(
261
+ `SELECT name FROM main.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,
262
+ )
263
+ .all() as { name: string }[]
264
+ ).map((row) => row.name);
265
+ }
266
+
267
+ function tableColumns(
268
+ db: ReturnType<typeof getDb>,
269
+ schema: "main" | "restore",
270
+ table: string,
271
+ ): string[] {
272
+ return (
273
+ db.prepare(`PRAGMA ${schema}.table_info(${quoteIdent(table)})`).all() as {
274
+ name: string;
275
+ }[]
276
+ ).map((row) => row.name);
277
+ }
278
+
279
+ function quoteIdent(name: string): string {
280
+ return `"${name.replace(/"/g, '""')}"`;
281
+ }
282
+
283
+ /**
284
+ * Restore a backup archive.
285
+ *
286
+ * Instead of replacing the SQLite file on disk (which conflicts with the live
287
+ * connection and any duplicated module instances), the uploaded database is
288
+ * attached and its tables are copied into the running database inside a single
289
+ * transaction. Bundled assets are rewritten to `public/`.
290
+ */
291
+ export function restoreBackup(buffer: Buffer): BackupManifest {
292
+ const payload = parsePayload(buffer);
293
+
294
+ let database: Buffer;
295
+ try {
296
+ database = Buffer.from(payload.database, "base64");
297
+ } catch {
298
+ throw new BackupError("Banco de dados do backup é inválido.");
299
+ }
300
+ if (
301
+ database.length < SQLITE_MAGIC.length ||
302
+ database.subarray(0, SQLITE_MAGIC.length).toString("latin1") !== SQLITE_MAGIC
303
+ ) {
304
+ throw new BackupError("Banco de dados do backup é inválido.");
305
+ }
306
+
307
+ const db = getDb();
308
+ const tmp = join(
309
+ tmpdir(),
310
+ `serenojs-restore-${Date.now()}-${Math.random().toString(16).slice(2)}.db`,
311
+ );
312
+ writeFileSync(tmp, database);
313
+
314
+ try {
315
+ db.exec(`ATTACH DATABASE '${tmp.replace(/'/g, "''")}' AS restore`);
316
+ } catch (error) {
317
+ rmSync(tmp, { force: true });
318
+ throw new BackupError(
319
+ `Não foi possível ler o banco do backup: ${(error as Error).message}`,
320
+ );
321
+ }
322
+
323
+ try {
324
+ const restored = new Set(
325
+ (
326
+ db
327
+ .prepare(
328
+ `SELECT name FROM restore.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,
329
+ )
330
+ .all() as { name: string }[]
331
+ ).map((row) => row.name),
332
+ );
333
+ const existing = new Set(mainTables(db));
334
+
335
+ db.exec("BEGIN");
336
+ try {
337
+ // Wipe tables that are not part of the backup.
338
+ for (const table of existing) {
339
+ if (!restored.has(table)) {
340
+ db.exec(`DELETE FROM main.${quoteIdent(table)}`);
341
+ }
342
+ }
343
+ // Copy every shared table, column by column (intersection).
344
+ for (const table of restored) {
345
+ if (!existing.has(table)) continue;
346
+ const target = tableColumns(db, "main", table);
347
+ const source = new Set(tableColumns(db, "restore", table));
348
+ const columns = target.filter((column) => source.has(column));
349
+ if (columns.length === 0) continue;
350
+ const list = columns.map(quoteIdent).join(", ");
351
+ db.exec(`DELETE FROM main.${quoteIdent(table)}`);
352
+ db.exec(
353
+ `INSERT INTO main.${quoteIdent(table)} (${list}) SELECT ${list} FROM restore.${quoteIdent(table)}`,
354
+ );
355
+ }
356
+ db.exec("COMMIT");
357
+ } catch (error) {
358
+ db.exec("ROLLBACK");
359
+ throw error;
360
+ }
361
+ } finally {
362
+ db.exec("DETACH DATABASE restore");
363
+ rmSync(tmp, { force: true });
364
+ }
365
+
366
+ for (const asset of payload.assets) {
367
+ if (!asset || typeof asset.path !== "string" || typeof asset.data !== "string") {
368
+ continue;
369
+ }
370
+ writeAsset(asset.path, Buffer.from(asset.data, "base64"));
371
+ }
372
+
373
+ return {
374
+ format: payload.format,
375
+ version: payload.version,
376
+ createdAt: payload.createdAt,
377
+ databaseBytes: database.length,
378
+ assets: payload.assets.length,
379
+ };
380
+ }
381
+
382
+ /* -------------------------------------------------------------------------- */
383
+ /* Scheduled routine */
384
+ /* -------------------------------------------------------------------------- */
385
+
386
+ function backupDisabled(): boolean {
387
+ return (
388
+ process.env.ADMIN_BACKUP === "false" || !getCmsConfig().backup.enabled
389
+ );
390
+ }
391
+
392
+ function intervalHours(): number {
393
+ return Number(
394
+ process.env.ADMIN_BACKUP_INTERVAL_HOURS ??
395
+ getCmsConfig().backup.intervalHours,
396
+ );
397
+ }
398
+
399
+ function keepCount(): number {
400
+ return Number(process.env.ADMIN_BACKUP_KEEP ?? getCmsConfig().backup.keep);
401
+ }
402
+
403
+ const globalScope = globalThis as typeof globalThis & {
404
+ [key: symbol]: boolean | undefined;
405
+ };
406
+ const SCHEDULER_KEY = Symbol.for("serenojs.backup-scheduler");
407
+
408
+ function intervalMs(): number {
409
+ const configured = intervalHours();
410
+ const hours = Number.isFinite(configured) && configured > 0 ? configured : 24;
411
+ return hours * 60 * 60 * 1000;
412
+ }
413
+
414
+ function isDue(): boolean {
415
+ const [latest] = listBackups();
416
+ if (!latest) return true;
417
+ const age = Date.now() - new Date(latest.createdAt).getTime();
418
+ return age >= intervalMs();
419
+ }
420
+
421
+ function runBackup(): void {
422
+ try {
423
+ createBackup();
424
+ const keep = keepCount();
425
+ pruneBackups(Number.isFinite(keep) && keep > 0 ? keep : 10);
426
+ } catch (error) {
427
+ console.error("[backup] falha ao criar backup automático:", error);
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Start the periodic backup routine. Idempotent: safe to call on every request
433
+ * or module load, only the first call schedules anything.
434
+ */
435
+ export function startBackupScheduler(): void {
436
+ if (backupDisabled()) return;
437
+ if (globalScope[SCHEDULER_KEY]) return;
438
+ globalScope[SCHEDULER_KEY] = true;
439
+
440
+ // Defer the first run so it never blocks the request that triggers startup.
441
+ setTimeout(() => {
442
+ if (isDue()) runBackup();
443
+ const timer = setInterval(runBackup, intervalMs());
444
+ timer.unref?.();
445
+ }, 2_000).unref?.();
446
+ }