@eutobias/serenojs 0.1.0 → 0.1.2
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 +51 -7
- package/admin-dist/assets/{index-B3EgqtT6.js → index-Ddgw58Iy.js} +1 -1
- package/admin-dist/index.html +1 -1
- package/dist/config.d.ts +7 -0
- package/dist/config.js +1 -0
- package/dist/core/backup.server.d.ts +5 -2
- package/dist/core/backup.server.js +279 -12
- package/dist/core/schema-codegen.server.d.ts +17 -0
- package/dist/core/schema-codegen.server.js +155 -0
- package/dist/ui/admin/i18n.js +4 -4
- package/package.json +4 -4
- package/src/config.ts +4 -0
- package/src/core/backup.server.ts +358 -17
- package/src/core/schema-codegen.server.ts +187 -0
- package/src/ui/admin/i18n.tsx +4 -4
package/src/config.ts
CHANGED
|
@@ -53,6 +53,8 @@ export type CmsConfig = {
|
|
|
53
53
|
intervalHours?: number;
|
|
54
54
|
keep?: number;
|
|
55
55
|
};
|
|
56
|
+
/** Host directory where restore writes the restored schema modules. */
|
|
57
|
+
schemas?: { path?: string };
|
|
56
58
|
db?: { path?: string };
|
|
57
59
|
};
|
|
58
60
|
|
|
@@ -72,6 +74,7 @@ export type ResolvedCmsConfig = {
|
|
|
72
74
|
intervalHours: number;
|
|
73
75
|
keep: number;
|
|
74
76
|
};
|
|
77
|
+
schemas: { path: string };
|
|
75
78
|
db: { path: string };
|
|
76
79
|
};
|
|
77
80
|
|
|
@@ -110,6 +113,7 @@ export function resolveCmsConfig(config: CmsConfig): ResolvedCmsConfig {
|
|
|
110
113
|
intervalHours: config.backup?.intervalHours ?? 24,
|
|
111
114
|
keep: config.backup?.keep ?? 10,
|
|
112
115
|
},
|
|
116
|
+
schemas: { path: config.schemas?.path ?? "src/schemas" },
|
|
113
117
|
db: { path: config.db?.path ?? ".data/admin.db" },
|
|
114
118
|
};
|
|
115
119
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Schemas, database and uploaded-asset backup and restore.
|
|
3
3
|
*
|
|
4
4
|
* A backup is a single gzip-compressed JSON archive (`<name>.serenojs`) that
|
|
5
5
|
* bundles:
|
|
6
|
+
* - the collection descriptors from `src/schemas` (the source of truth),
|
|
6
7
|
* - a consistent SQLite snapshot of `.data/admin.db` (via `VACUUM INTO`),
|
|
7
8
|
* - every file under `public/images` (committed assets) and `public/files`
|
|
8
9
|
* (runtime uploads), stored as base64.
|
|
@@ -18,10 +19,16 @@ import { join, relative, resolve, sep } from "node:path";
|
|
|
18
19
|
import { gunzipSync, gzipSync } from "node:zlib";
|
|
19
20
|
|
|
20
21
|
import { getDb } from "./db.server.js";
|
|
21
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
writeSchemaFiles,
|
|
24
|
+
type BackupSchemas,
|
|
25
|
+
type SchemaWriteResult,
|
|
26
|
+
} from "./schema-codegen.server.js";
|
|
27
|
+
import { configureCms, getCmsConfig } from "../runtime.js";
|
|
28
|
+
import type { CollectionDef, FieldDef, FieldType } from "./types.js";
|
|
22
29
|
|
|
23
30
|
export const BACKUP_FORMAT = "serenojs-backup";
|
|
24
|
-
export const BACKUP_VERSION =
|
|
31
|
+
export const BACKUP_VERSION = 2;
|
|
25
32
|
export const BACKUP_EXTENSION = ".serenojs";
|
|
26
33
|
|
|
27
34
|
export const BACKUP_DIR = resolve(process.cwd(), ".data/backups");
|
|
@@ -54,6 +61,8 @@ export type BackupManifest = {
|
|
|
54
61
|
createdAt: string;
|
|
55
62
|
databaseBytes: number;
|
|
56
63
|
assets: number;
|
|
64
|
+
/** Number of schema modules written during restore. */
|
|
65
|
+
schemas: number;
|
|
57
66
|
};
|
|
58
67
|
|
|
59
68
|
type BackupAsset = { path: string; data: string };
|
|
@@ -64,6 +73,8 @@ type BackupPayload = {
|
|
|
64
73
|
createdAt: string;
|
|
65
74
|
database: string;
|
|
66
75
|
assets: BackupAsset[];
|
|
76
|
+
/** Collection descriptors. Absent on archives created by older versions. */
|
|
77
|
+
schemas?: BackupSchemas;
|
|
67
78
|
};
|
|
68
79
|
|
|
69
80
|
const NAME_RE = /^[a-zA-Z0-9._-]+\.serenojs$/;
|
|
@@ -127,6 +138,7 @@ function buildPayload(): BackupPayload {
|
|
|
127
138
|
createdAt: new Date().toISOString(),
|
|
128
139
|
database: database.toString("base64"),
|
|
129
140
|
assets,
|
|
141
|
+
schemas: currentSchemas(),
|
|
130
142
|
};
|
|
131
143
|
}
|
|
132
144
|
|
|
@@ -280,13 +292,325 @@ function quoteIdent(name: string): string {
|
|
|
280
292
|
return `"${name.replace(/"/g, '""')}"`;
|
|
281
293
|
}
|
|
282
294
|
|
|
295
|
+
/** Tables declared in an attached schema (excluding SQLite internals). */
|
|
296
|
+
function attachedTables(
|
|
297
|
+
db: ReturnType<typeof getDb>,
|
|
298
|
+
schema: "main" | "restore",
|
|
299
|
+
): { name: string; sql: string | null }[] {
|
|
300
|
+
return db
|
|
301
|
+
.prepare(
|
|
302
|
+
`SELECT name, sql FROM ${schema}.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,
|
|
303
|
+
)
|
|
304
|
+
.all() as { name: string; sql: string | null }[];
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Recreate a table that does not exist in the live database yet. */
|
|
308
|
+
function createMissingTable(
|
|
309
|
+
db: ReturnType<typeof getDb>,
|
|
310
|
+
table: { name: string; sql: string | null },
|
|
311
|
+
): void {
|
|
312
|
+
if (!table.sql) return;
|
|
313
|
+
db.exec(table.sql);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Add columns that exist in the backup but not in the live table. Without this,
|
|
318
|
+
* data stored in newer columns would be silently dropped on restore.
|
|
319
|
+
*/
|
|
320
|
+
function addMissingColumns(
|
|
321
|
+
db: ReturnType<typeof getDb>,
|
|
322
|
+
table: string,
|
|
323
|
+
target: Set<string>,
|
|
324
|
+
): void {
|
|
325
|
+
const source = db
|
|
326
|
+
.prepare(`PRAGMA restore.table_info(${quoteIdent(table)})`)
|
|
327
|
+
.all() as {
|
|
328
|
+
name: string;
|
|
329
|
+
type: string;
|
|
330
|
+
notnull: number;
|
|
331
|
+
dflt_value: string | null;
|
|
332
|
+
}[];
|
|
333
|
+
|
|
334
|
+
for (const column of source) {
|
|
335
|
+
if (target.has(column.name)) continue;
|
|
336
|
+
let definition = `${quoteIdent(column.name)} ${column.type || "TEXT"}`;
|
|
337
|
+
if (column.dflt_value !== null) {
|
|
338
|
+
definition += ` NOT NULL DEFAULT ${column.dflt_value}`;
|
|
339
|
+
}
|
|
340
|
+
// SQLite cannot add a NOT NULL column without a default; keep it nullable.
|
|
341
|
+
db.exec(`ALTER TABLE main.${quoteIdent(table)} ADD COLUMN ${definition}`);
|
|
342
|
+
target.add(column.name);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Recreate indexes/triggers from the backup whose names are absent live. */
|
|
347
|
+
function createMissingSchemaObjects(db: ReturnType<typeof getDb>): void {
|
|
348
|
+
const existing = new Set(
|
|
349
|
+
(
|
|
350
|
+
db
|
|
351
|
+
.prepare(
|
|
352
|
+
`SELECT name FROM main.sqlite_master WHERE type IN ('index', 'trigger')`,
|
|
353
|
+
)
|
|
354
|
+
.all() as { name: string }[]
|
|
355
|
+
).map((row) => row.name),
|
|
356
|
+
);
|
|
357
|
+
const objects = db
|
|
358
|
+
.prepare(
|
|
359
|
+
`SELECT name, sql FROM restore.sqlite_master WHERE type IN ('index', 'trigger') AND sql IS NOT NULL`,
|
|
360
|
+
)
|
|
361
|
+
.all() as { name: string; sql: string }[];
|
|
362
|
+
|
|
363
|
+
for (const object of objects) {
|
|
364
|
+
if (existing.has(object.name)) continue;
|
|
365
|
+
db.exec(object.sql);
|
|
366
|
+
existing.add(object.name);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Current descriptors, persisted inside every new backup. */
|
|
371
|
+
function currentSchemas(): BackupSchemas {
|
|
372
|
+
const config = getCmsConfig();
|
|
373
|
+
return {
|
|
374
|
+
title: config.title,
|
|
375
|
+
defaultLocale: config.defaultLocale,
|
|
376
|
+
locales: config.locales,
|
|
377
|
+
collections: config.collections,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Validate the schema section of an uploaded archive. */
|
|
382
|
+
function normalizeSchemas(
|
|
383
|
+
value: unknown,
|
|
384
|
+
fallback: BackupSchemas,
|
|
385
|
+
): BackupSchemas | null {
|
|
386
|
+
if (!value || typeof value !== "object") return null;
|
|
387
|
+
const record = value as Partial<BackupSchemas>;
|
|
388
|
+
if (!Array.isArray(record.collections)) return null;
|
|
389
|
+
|
|
390
|
+
const locales = Array.isArray(record.locales)
|
|
391
|
+
? record.locales.filter(
|
|
392
|
+
(locale): locale is { code: string; label: string } =>
|
|
393
|
+
Boolean(locale) &&
|
|
394
|
+
typeof locale === "object" &&
|
|
395
|
+
typeof (locale as { code?: unknown }).code === "string" &&
|
|
396
|
+
typeof (locale as { label?: unknown }).label === "string",
|
|
397
|
+
)
|
|
398
|
+
: fallback.locales;
|
|
399
|
+
const collections = record.collections.filter(
|
|
400
|
+
(collection): collection is CollectionDef =>
|
|
401
|
+
Boolean(collection) &&
|
|
402
|
+
typeof collection === "object" &&
|
|
403
|
+
typeof (collection as { slug?: unknown }).slug === "string" &&
|
|
404
|
+
typeof (collection as { label?: unknown }).label === "string" &&
|
|
405
|
+
Array.isArray((collection as { fields?: unknown }).fields),
|
|
406
|
+
);
|
|
407
|
+
// A malformed archive must not overwrite the host schemas with a partial set.
|
|
408
|
+
if (collections.length !== record.collections.length) return null;
|
|
409
|
+
|
|
410
|
+
return {
|
|
411
|
+
title: typeof record.title === "string" && record.title ? record.title : fallback.title,
|
|
412
|
+
locales: locales.length > 0 ? locales : fallback.locales,
|
|
413
|
+
defaultLocale:
|
|
414
|
+
typeof record.defaultLocale === "string" && record.defaultLocale
|
|
415
|
+
? record.defaultLocale
|
|
416
|
+
: fallback.defaultLocale,
|
|
417
|
+
collections,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function humanize(name: string): string {
|
|
422
|
+
const words = name
|
|
423
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
424
|
+
.replace(/[_-]+/g, " ")
|
|
425
|
+
.trim()
|
|
426
|
+
.split(/\s+/)
|
|
427
|
+
.filter(Boolean);
|
|
428
|
+
if (words.length === 0) return name;
|
|
429
|
+
return words
|
|
430
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
431
|
+
.join(" ");
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function inferFieldType(sqlType: string, samples: unknown[]): FieldType {
|
|
435
|
+
const type = (sqlType || "").toUpperCase();
|
|
436
|
+
if (type.includes("INT")) {
|
|
437
|
+
const numbers = samples.map((value) => Number(value));
|
|
438
|
+
if (
|
|
439
|
+
numbers.length > 0 &&
|
|
440
|
+
numbers.every((value) => value === 0 || value === 1)
|
|
441
|
+
) {
|
|
442
|
+
return "boolean";
|
|
443
|
+
}
|
|
444
|
+
return "number";
|
|
445
|
+
}
|
|
446
|
+
if (
|
|
447
|
+
type.includes("REAL") ||
|
|
448
|
+
type.includes("NUM") ||
|
|
449
|
+
type.includes("DEC") ||
|
|
450
|
+
type.includes("FLOA") ||
|
|
451
|
+
type.includes("DOUB")
|
|
452
|
+
) {
|
|
453
|
+
return "number";
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
for (const value of samples) {
|
|
457
|
+
if (typeof value !== "string") continue;
|
|
458
|
+
const text = value.trim();
|
|
459
|
+
if (!text) continue;
|
|
460
|
+
if (
|
|
461
|
+
(text.startsWith("/files/") || text.startsWith("/images/")) &&
|
|
462
|
+
/\.(png|jpe?g|gif|webp|avif|svg|pdf)(\?|$)/i.test(text)
|
|
463
|
+
) {
|
|
464
|
+
return "media";
|
|
465
|
+
}
|
|
466
|
+
if (text.startsWith("[") && text.endsWith("]")) {
|
|
467
|
+
try {
|
|
468
|
+
const parsed: unknown = JSON.parse(text);
|
|
469
|
+
if (Array.isArray(parsed) && parsed.length > 0) {
|
|
470
|
+
if (
|
|
471
|
+
parsed.every(
|
|
472
|
+
(entry) =>
|
|
473
|
+
Boolean(entry) &&
|
|
474
|
+
typeof entry === "object" &&
|
|
475
|
+
typeof (entry as { url?: unknown }).url === "string",
|
|
476
|
+
)
|
|
477
|
+
) {
|
|
478
|
+
return "media-list";
|
|
479
|
+
}
|
|
480
|
+
if (parsed.every((entry) => typeof entry === "string")) {
|
|
481
|
+
return "list";
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
} catch {
|
|
485
|
+
// Not JSON; keep it as text.
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return "text";
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Reconstruct descriptors from the backup database for archives created before
|
|
494
|
+
* schemas were embedded. Types are inferred from SQLite columns and samples.
|
|
495
|
+
*/
|
|
496
|
+
function inferSchemas(
|
|
497
|
+
db: ReturnType<typeof getDb>,
|
|
498
|
+
schema: "restore",
|
|
499
|
+
fallback: BackupSchemas,
|
|
500
|
+
): BackupSchemas {
|
|
501
|
+
const localeCodes = [...fallback.locales.map((locale) => locale.code)].sort(
|
|
502
|
+
(a, b) => b.length - a.length,
|
|
503
|
+
);
|
|
504
|
+
const collections: CollectionDef[] = [];
|
|
505
|
+
|
|
506
|
+
for (const table of attachedTables(db, schema)) {
|
|
507
|
+
if (!table.name.startsWith("c_")) continue;
|
|
508
|
+
const slug = table.name.slice(2);
|
|
509
|
+
const columns = db
|
|
510
|
+
.prepare(`PRAGMA ${schema}.table_info(${quoteIdent(table.name)})`)
|
|
511
|
+
.all() as { name: string; type: string }[];
|
|
512
|
+
const rows = db
|
|
513
|
+
.prepare(`SELECT * FROM ${schema}.${quoteIdent(table.name)} LIMIT 100`)
|
|
514
|
+
.all() as Record<string, unknown>[];
|
|
515
|
+
|
|
516
|
+
type Group = {
|
|
517
|
+
base: string;
|
|
518
|
+
localized: boolean;
|
|
519
|
+
locales: Set<string>;
|
|
520
|
+
sqlType: string;
|
|
521
|
+
samples: unknown[];
|
|
522
|
+
};
|
|
523
|
+
const groups = new Map<string, Group>();
|
|
524
|
+
|
|
525
|
+
for (const column of columns) {
|
|
526
|
+
if (column.name === "id" || column.name === "created_at" || column.name === "updated_at") {
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
let base = column.name;
|
|
530
|
+
let localized = false;
|
|
531
|
+
let locale: string | null = null;
|
|
532
|
+
for (const code of localeCodes) {
|
|
533
|
+
if (column.name.endsWith(`_${code}`)) {
|
|
534
|
+
base = column.name.slice(0, -code.length - 1);
|
|
535
|
+
localized = true;
|
|
536
|
+
locale = code;
|
|
537
|
+
break;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
let group = groups.get(base);
|
|
542
|
+
if (!group) {
|
|
543
|
+
group = { base, localized: false, locales: new Set(), sqlType: column.type, samples: [] };
|
|
544
|
+
groups.set(base, group);
|
|
545
|
+
}
|
|
546
|
+
if (localized && locale) {
|
|
547
|
+
group.localized = true;
|
|
548
|
+
group.locales.add(locale);
|
|
549
|
+
}
|
|
550
|
+
if (!group.sqlType) group.sqlType = column.type;
|
|
551
|
+
for (const row of rows) {
|
|
552
|
+
const value = row[column.name];
|
|
553
|
+
if (value !== null && value !== undefined) group.samples.push(value);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const fields: FieldDef[] = [];
|
|
558
|
+
const usedLocales = new Set<string>();
|
|
559
|
+
for (const group of groups.values()) {
|
|
560
|
+
fields.push({
|
|
561
|
+
name: group.base,
|
|
562
|
+
label: humanize(group.base),
|
|
563
|
+
type: inferFieldType(group.sqlType, group.samples.slice(0, 50)),
|
|
564
|
+
localized: group.localized,
|
|
565
|
+
});
|
|
566
|
+
for (const code of group.locales) usedLocales.add(code);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const collection: CollectionDef = {
|
|
570
|
+
slug,
|
|
571
|
+
label: humanize(slug),
|
|
572
|
+
fields,
|
|
573
|
+
};
|
|
574
|
+
if (usedLocales.size > 0) {
|
|
575
|
+
collection.locales = fallback.locales
|
|
576
|
+
.map((locale) => locale.code)
|
|
577
|
+
.filter((code) => usedLocales.has(code));
|
|
578
|
+
}
|
|
579
|
+
collections.push(collection);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
return {
|
|
583
|
+
title: fallback.title,
|
|
584
|
+
defaultLocale: fallback.defaultLocale,
|
|
585
|
+
locales: fallback.locales,
|
|
586
|
+
collections,
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function schemaDirectory(): string {
|
|
591
|
+
return resolve(process.cwd(), getCmsConfig().schemas.path);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** Make the restored descriptors active immediately, not only after reboot. */
|
|
595
|
+
function applySchemas(schemas: BackupSchemas): void {
|
|
596
|
+
const current = getCmsConfig();
|
|
597
|
+
configureCms({
|
|
598
|
+
...current,
|
|
599
|
+
title: schemas.title,
|
|
600
|
+
collections: schemas.collections,
|
|
601
|
+
locales: schemas.locales,
|
|
602
|
+
defaultLocale: schemas.defaultLocale,
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
|
|
283
606
|
/**
|
|
284
607
|
* Restore a backup archive.
|
|
285
608
|
*
|
|
286
609
|
* Instead of replacing the SQLite file on disk (which conflicts with the live
|
|
287
610
|
* connection and any duplicated module instances), the uploaded database is
|
|
288
611
|
* attached and its tables are copied into the running database inside a single
|
|
289
|
-
* transaction.
|
|
612
|
+
* transaction. The schema modules are rewritten to `schemas.path` and bundled
|
|
613
|
+
* assets to `public/`.
|
|
290
614
|
*/
|
|
291
615
|
export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
292
616
|
const payload = parsePayload(buffer);
|
|
@@ -305,6 +629,8 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
305
629
|
}
|
|
306
630
|
|
|
307
631
|
const db = getDb();
|
|
632
|
+
const fallback = currentSchemas();
|
|
633
|
+
let schemas = normalizeSchemas(payload.schemas, fallback);
|
|
308
634
|
const tmp = join(
|
|
309
635
|
tmpdir(),
|
|
310
636
|
`serenojs-restore-${Date.now()}-${Math.random().toString(16).slice(2)}.db`,
|
|
@@ -321,16 +647,10 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
321
647
|
}
|
|
322
648
|
|
|
323
649
|
try {
|
|
324
|
-
const
|
|
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
|
-
);
|
|
650
|
+
const restoredTables = attachedTables(db, "restore");
|
|
651
|
+
const restored = new Set(restoredTables.map((table) => table.name));
|
|
333
652
|
const existing = new Set(mainTables(db));
|
|
653
|
+
schemas ??= inferSchemas(db, "restore", fallback);
|
|
334
654
|
|
|
335
655
|
db.exec("BEGIN");
|
|
336
656
|
try {
|
|
@@ -340,12 +660,18 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
340
660
|
db.exec(`DELETE FROM main.${quoteIdent(table)}`);
|
|
341
661
|
}
|
|
342
662
|
}
|
|
343
|
-
//
|
|
663
|
+
// Recreate missing tables so the backup schema itself is restored.
|
|
664
|
+
for (const table of restoredTables) {
|
|
665
|
+
if (existing.has(table.name)) continue;
|
|
666
|
+
createMissingTable(db, table);
|
|
667
|
+
existing.add(table.name);
|
|
668
|
+
}
|
|
669
|
+
// Copy every shared table, column by column.
|
|
344
670
|
for (const table of restored) {
|
|
345
|
-
|
|
346
|
-
|
|
671
|
+
const target = new Set(tableColumns(db, "main", table));
|
|
672
|
+
addMissingColumns(db, table, target);
|
|
347
673
|
const source = new Set(tableColumns(db, "restore", table));
|
|
348
|
-
const columns = target.filter((column) => source.has(column));
|
|
674
|
+
const columns = [...target].filter((column) => source.has(column));
|
|
349
675
|
if (columns.length === 0) continue;
|
|
350
676
|
const list = columns.map(quoteIdent).join(", ");
|
|
351
677
|
db.exec(`DELETE FROM main.${quoteIdent(table)}`);
|
|
@@ -353,6 +679,8 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
353
679
|
`INSERT INTO main.${quoteIdent(table)} (${list}) SELECT ${list} FROM restore.${quoteIdent(table)}`,
|
|
354
680
|
);
|
|
355
681
|
}
|
|
682
|
+
// Restore indexes/triggers declared by the backup.
|
|
683
|
+
createMissingSchemaObjects(db);
|
|
356
684
|
db.exec("COMMIT");
|
|
357
685
|
} catch (error) {
|
|
358
686
|
db.exec("ROLLBACK");
|
|
@@ -370,12 +698,25 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
370
698
|
writeAsset(asset.path, Buffer.from(asset.data, "base64"));
|
|
371
699
|
}
|
|
372
700
|
|
|
701
|
+
const restoredSchemas = schemas ?? fallback;
|
|
702
|
+
let written: SchemaWriteResult;
|
|
703
|
+
try {
|
|
704
|
+
written = writeSchemaFiles(schemaDirectory(), restoredSchemas);
|
|
705
|
+
} catch (error) {
|
|
706
|
+
throw new BackupError(
|
|
707
|
+
`Banco e arquivos restaurados, mas não foi possível gravar os schemas: ${(error as Error).message}`,
|
|
708
|
+
500,
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
applySchemas(restoredSchemas);
|
|
712
|
+
|
|
373
713
|
return {
|
|
374
714
|
format: payload.format,
|
|
375
715
|
version: payload.version,
|
|
376
716
|
createdAt: payload.createdAt,
|
|
377
717
|
databaseBytes: database.length,
|
|
378
718
|
assets: payload.assets.length,
|
|
719
|
+
schemas: written.files,
|
|
379
720
|
};
|
|
380
721
|
}
|
|
381
722
|
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema source-code generation used by the backup restore routine.
|
|
3
|
+
*
|
|
4
|
+
* The collection descriptors in `src/schemas` are the source of truth for the
|
|
5
|
+
* whole CMS, so a backup stores them and restore writes them back as TypeScript
|
|
6
|
+
* modules. Server-only: uses the filesystem.
|
|
7
|
+
*/
|
|
8
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
|
|
11
|
+
import type { LocaleDef } from "../config.js";
|
|
12
|
+
import type { CollectionDef } from "./types.js";
|
|
13
|
+
|
|
14
|
+
export type BackupSchemas = {
|
|
15
|
+
title: string;
|
|
16
|
+
defaultLocale: string;
|
|
17
|
+
locales: LocaleDef[];
|
|
18
|
+
collections: CollectionDef[];
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type SchemaWriteResult = {
|
|
22
|
+
files: number;
|
|
23
|
+
collections: number;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const RESERVED_IDENTIFIERS = new Set([
|
|
27
|
+
"break",
|
|
28
|
+
"case",
|
|
29
|
+
"catch",
|
|
30
|
+
"class",
|
|
31
|
+
"const",
|
|
32
|
+
"continue",
|
|
33
|
+
"debugger",
|
|
34
|
+
"default",
|
|
35
|
+
"delete",
|
|
36
|
+
"do",
|
|
37
|
+
"else",
|
|
38
|
+
"enum",
|
|
39
|
+
"export",
|
|
40
|
+
"extends",
|
|
41
|
+
"false",
|
|
42
|
+
"finally",
|
|
43
|
+
"for",
|
|
44
|
+
"function",
|
|
45
|
+
"if",
|
|
46
|
+
"implements",
|
|
47
|
+
"import",
|
|
48
|
+
"in",
|
|
49
|
+
"instanceof",
|
|
50
|
+
"interface",
|
|
51
|
+
"let",
|
|
52
|
+
"new",
|
|
53
|
+
"null",
|
|
54
|
+
"package",
|
|
55
|
+
"private",
|
|
56
|
+
"protected",
|
|
57
|
+
"public",
|
|
58
|
+
"return",
|
|
59
|
+
"static",
|
|
60
|
+
"super",
|
|
61
|
+
"switch",
|
|
62
|
+
"this",
|
|
63
|
+
"throw",
|
|
64
|
+
"true",
|
|
65
|
+
"try",
|
|
66
|
+
"typeof",
|
|
67
|
+
"var",
|
|
68
|
+
"void",
|
|
69
|
+
"while",
|
|
70
|
+
"with",
|
|
71
|
+
"yield",
|
|
72
|
+
]);
|
|
73
|
+
|
|
74
|
+
function identifier(raw: string, fallback: string): string {
|
|
75
|
+
let value = raw.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
76
|
+
if (!value) value = fallback;
|
|
77
|
+
if (/^[0-9]/.test(value)) value = `_${value}`;
|
|
78
|
+
if (RESERVED_IDENTIFIERS.has(value)) value = `${value}_`;
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function fileBase(raw: string): string {
|
|
83
|
+
const value = raw.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/^[-_]+/, "");
|
|
84
|
+
return value || "collection";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function literal(value: unknown): string {
|
|
88
|
+
return JSON.stringify(value, null, 2) ?? "null";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function collectionModule(exportName: string, collection: CollectionDef): string {
|
|
92
|
+
return [
|
|
93
|
+
`import type { CollectionDef } from "@eutobias/serenojs/config";`,
|
|
94
|
+
"",
|
|
95
|
+
`export const ${exportName}: CollectionDef = ${literal(collection)};`,
|
|
96
|
+
"",
|
|
97
|
+
].join("\n");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function localesModule(schemas: BackupSchemas): string {
|
|
101
|
+
return [
|
|
102
|
+
`/** Locale registry restored from a SerenoJS backup. */`,
|
|
103
|
+
"",
|
|
104
|
+
`export type LocaleDef = {`,
|
|
105
|
+
` code: string;`,
|
|
106
|
+
` label: string;`,
|
|
107
|
+
`};`,
|
|
108
|
+
"",
|
|
109
|
+
`export const locales: LocaleDef[] = ${literal(schemas.locales)};`,
|
|
110
|
+
"",
|
|
111
|
+
`/** Locale used as fallback and for the seed of legacy single-column data. */`,
|
|
112
|
+
`export const defaultLocale = ${literal(schemas.defaultLocale)};`,
|
|
113
|
+
"",
|
|
114
|
+
`/** Display label for a locale code (falls back to the uppercased code). */`,
|
|
115
|
+
`export function localeLabel(code: string): string {`,
|
|
116
|
+
` return (`,
|
|
117
|
+
` locales.find((locale) => locale.code === code)?.label ?? code.toUpperCase()`,
|
|
118
|
+
` );`,
|
|
119
|
+
`}`,
|
|
120
|
+
"",
|
|
121
|
+
].join("\n");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function indexModule(
|
|
125
|
+
schemas: BackupSchemas,
|
|
126
|
+
entries: { base: string; exportName: string }[],
|
|
127
|
+
): string {
|
|
128
|
+
const imports = entries
|
|
129
|
+
.map(({ base, exportName }) => `import { ${exportName} } from "./${base}";`)
|
|
130
|
+
.join("\n");
|
|
131
|
+
const values = entries.map(({ exportName }) => exportName).join(", ");
|
|
132
|
+
|
|
133
|
+
return [
|
|
134
|
+
`import type { CollectionDef } from "@eutobias/serenojs/config";`,
|
|
135
|
+
"",
|
|
136
|
+
imports,
|
|
137
|
+
"",
|
|
138
|
+
`export { defaultLocale, localeLabel, locales } from "./locales";`,
|
|
139
|
+
`export type { LocaleDef } from "./locales";`,
|
|
140
|
+
"",
|
|
141
|
+
`/** Title shown across the admin panel. */`,
|
|
142
|
+
`export const schemaTitle = ${literal(schemas.title)};`,
|
|
143
|
+
"",
|
|
144
|
+
`/** Every collection available in the admin/API. */`,
|
|
145
|
+
`export const collections: CollectionDef[] = [${values}];`,
|
|
146
|
+
"",
|
|
147
|
+
].join("\n");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Write the backup schemas into `dir` as the conventional starter layout:
|
|
152
|
+
* `index.ts`, `locales.ts` and one module per collection.
|
|
153
|
+
*/
|
|
154
|
+
export function writeSchemaFiles(
|
|
155
|
+
dir: string,
|
|
156
|
+
schemas: BackupSchemas,
|
|
157
|
+
): SchemaWriteResult {
|
|
158
|
+
mkdirSync(dir, { recursive: true });
|
|
159
|
+
|
|
160
|
+
const usedFiles = new Set<string>(["index", "locales"]);
|
|
161
|
+
const usedExports = new Set<string>();
|
|
162
|
+
const entries: { base: string; exportName: string }[] = [];
|
|
163
|
+
|
|
164
|
+
for (const collection of schemas.collections) {
|
|
165
|
+
const rawBase = fileBase(collection.slug);
|
|
166
|
+
let base = rawBase;
|
|
167
|
+
let suffix = 2;
|
|
168
|
+
while (usedFiles.has(base)) base = `${rawBase}_${suffix++}`;
|
|
169
|
+
usedFiles.add(base);
|
|
170
|
+
|
|
171
|
+
const rawExport = identifier(collection.slug, "collection");
|
|
172
|
+
let exportName = rawExport;
|
|
173
|
+
suffix = 2;
|
|
174
|
+
while (usedExports.has(exportName)) {
|
|
175
|
+
exportName = `${rawExport}_${suffix++}`;
|
|
176
|
+
}
|
|
177
|
+
usedExports.add(exportName);
|
|
178
|
+
|
|
179
|
+
writeFileSync(join(dir, `${base}.ts`), collectionModule(exportName, collection), "utf8");
|
|
180
|
+
entries.push({ base, exportName });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
writeFileSync(join(dir, "locales.ts"), localesModule(schemas), "utf8");
|
|
184
|
+
writeFileSync(join(dir, "index.ts"), indexModule(schemas, entries), "utf8");
|
|
185
|
+
|
|
186
|
+
return { files: entries.length + 2, collections: entries.length };
|
|
187
|
+
}
|