@eutobias/serenojs 0.1.1 → 0.1.4
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 +30 -11
- package/admin-dist/assets/index-CEMJnHOP.js +22 -0
- package/admin-dist/assets/index-Di8sAvwO.css +2 -0
- package/admin-dist/assets/marked.esm-BBttRptN.js +77 -0
- package/admin-dist/assets/purify.es-Bz-uQoIK.js +3 -0
- package/admin-dist/index.html +2 -2
- package/dist/config.d.ts +9 -2
- package/dist/config.js +1 -0
- package/dist/core/backup.server.d.ts +5 -2
- package/dist/core/backup.server.js +346 -12
- package/dist/core/db.server.js +29 -1
- package/dist/core/schema-codegen.server.d.ts +17 -0
- package/dist/core/schema-codegen.server.js +155 -0
- package/dist/core/schema.js +8 -1
- package/dist/core/types.d.ts +15 -4
- package/dist/core/validation.js +61 -0
- package/dist/ui/admin/collection-manager.js +1 -1
- package/dist/ui/admin/display.js +7 -0
- package/dist/ui/admin/field-control.d.ts +3 -1
- package/dist/ui/admin/field-control.js +10 -2
- package/dist/ui/admin/i18n.js +30 -4
- package/dist/ui/admin/object-list-control.d.ts +15 -0
- package/dist/ui/admin/object-list-control.js +42 -0
- package/dist/ui/admin/rich-text-control.d.ts +15 -0
- package/dist/ui/admin/rich-text-control.js +62 -0
- package/dist/ui/admin/rich-text-icons.d.ts +8 -0
- package/dist/ui/admin/rich-text-icons.js +18 -0
- package/dist/ui/index.d.ts +1 -0
- package/dist/ui/index.js +1 -0
- package/dist/ui/markdown-preview.d.ts +10 -0
- package/dist/ui/markdown-preview.js +34 -0
- package/package.json +4 -1
- package/src/admin/styles.css +152 -0
- package/src/config.ts +6 -1
- package/src/core/backup.server.ts +435 -17
- package/src/core/db.server.ts +34 -1
- package/src/core/schema-codegen.server.ts +187 -0
- package/src/core/schema.ts +8 -1
- package/src/core/types.ts +18 -3
- package/src/core/validation.ts +71 -0
- package/src/ui/admin/collection-manager.tsx +1 -0
- package/src/ui/admin/display.tsx +13 -1
- package/src/ui/admin/field-control.tsx +43 -2
- package/src/ui/admin/i18n.tsx +32 -4
- package/src/ui/admin/object-list-control.tsx +154 -0
- package/src/ui/admin/rich-text-control.tsx +173 -0
- package/src/ui/admin/rich-text-icons.tsx +125 -0
- package/src/ui/index.ts +1 -0
- package/src/ui/markdown-preview.tsx +42 -0
- package/admin-dist/assets/index-B3EgqtT6.js +0 -9
- package/admin-dist/assets/index-D2m0Eb4k.css +0 -2
|
@@ -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,17 @@ 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 { isMediaUrl } from "./media.js";
|
|
29
|
+
import type { CollectionDef, FieldDef, FieldType } from "./types.js";
|
|
22
30
|
|
|
23
31
|
export const BACKUP_FORMAT = "serenojs-backup";
|
|
24
|
-
export const BACKUP_VERSION =
|
|
32
|
+
export const BACKUP_VERSION = 2;
|
|
25
33
|
export const BACKUP_EXTENSION = ".serenojs";
|
|
26
34
|
|
|
27
35
|
export const BACKUP_DIR = resolve(process.cwd(), ".data/backups");
|
|
@@ -54,6 +62,8 @@ export type BackupManifest = {
|
|
|
54
62
|
createdAt: string;
|
|
55
63
|
databaseBytes: number;
|
|
56
64
|
assets: number;
|
|
65
|
+
/** Number of schema modules written during restore. */
|
|
66
|
+
schemas: number;
|
|
57
67
|
};
|
|
58
68
|
|
|
59
69
|
type BackupAsset = { path: string; data: string };
|
|
@@ -64,6 +74,8 @@ type BackupPayload = {
|
|
|
64
74
|
createdAt: string;
|
|
65
75
|
database: string;
|
|
66
76
|
assets: BackupAsset[];
|
|
77
|
+
/** Collection descriptors. Absent on archives created by older versions. */
|
|
78
|
+
schemas?: BackupSchemas;
|
|
67
79
|
};
|
|
68
80
|
|
|
69
81
|
const NAME_RE = /^[a-zA-Z0-9._-]+\.serenojs$/;
|
|
@@ -127,6 +139,7 @@ function buildPayload(): BackupPayload {
|
|
|
127
139
|
createdAt: new Date().toISOString(),
|
|
128
140
|
database: database.toString("base64"),
|
|
129
141
|
assets,
|
|
142
|
+
schemas: currentSchemas(),
|
|
130
143
|
};
|
|
131
144
|
}
|
|
132
145
|
|
|
@@ -280,13 +293,401 @@ function quoteIdent(name: string): string {
|
|
|
280
293
|
return `"${name.replace(/"/g, '""')}"`;
|
|
281
294
|
}
|
|
282
295
|
|
|
296
|
+
/** Tables declared in an attached schema (excluding SQLite internals). */
|
|
297
|
+
function attachedTables(
|
|
298
|
+
db: ReturnType<typeof getDb>,
|
|
299
|
+
schema: "main" | "restore",
|
|
300
|
+
): { name: string; sql: string | null }[] {
|
|
301
|
+
return db
|
|
302
|
+
.prepare(
|
|
303
|
+
`SELECT name, sql FROM ${schema}.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,
|
|
304
|
+
)
|
|
305
|
+
.all() as { name: string; sql: string | null }[];
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Recreate a table that does not exist in the live database yet. */
|
|
309
|
+
function createMissingTable(
|
|
310
|
+
db: ReturnType<typeof getDb>,
|
|
311
|
+
table: { name: string; sql: string | null },
|
|
312
|
+
): void {
|
|
313
|
+
if (!table.sql) return;
|
|
314
|
+
db.exec(table.sql);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Add columns that exist in the backup but not in the live table. Without this,
|
|
319
|
+
* data stored in newer columns would be silently dropped on restore.
|
|
320
|
+
*/
|
|
321
|
+
function addMissingColumns(
|
|
322
|
+
db: ReturnType<typeof getDb>,
|
|
323
|
+
table: string,
|
|
324
|
+
target: Set<string>,
|
|
325
|
+
): void {
|
|
326
|
+
const source = db
|
|
327
|
+
.prepare(`PRAGMA restore.table_info(${quoteIdent(table)})`)
|
|
328
|
+
.all() as {
|
|
329
|
+
name: string;
|
|
330
|
+
type: string;
|
|
331
|
+
notnull: number;
|
|
332
|
+
dflt_value: string | null;
|
|
333
|
+
}[];
|
|
334
|
+
|
|
335
|
+
for (const column of source) {
|
|
336
|
+
if (target.has(column.name)) continue;
|
|
337
|
+
let definition = `${quoteIdent(column.name)} ${column.type || "TEXT"}`;
|
|
338
|
+
if (column.dflt_value !== null) {
|
|
339
|
+
definition += ` NOT NULL DEFAULT ${column.dflt_value}`;
|
|
340
|
+
}
|
|
341
|
+
// SQLite cannot add a NOT NULL column without a default; keep it nullable.
|
|
342
|
+
db.exec(`ALTER TABLE main.${quoteIdent(table)} ADD COLUMN ${definition}`);
|
|
343
|
+
target.add(column.name);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Recreate indexes/triggers from the backup whose names are absent live. */
|
|
348
|
+
function createMissingSchemaObjects(db: ReturnType<typeof getDb>): void {
|
|
349
|
+
const existing = new Set(
|
|
350
|
+
(
|
|
351
|
+
db
|
|
352
|
+
.prepare(
|
|
353
|
+
`SELECT name FROM main.sqlite_master WHERE type IN ('index', 'trigger')`,
|
|
354
|
+
)
|
|
355
|
+
.all() as { name: string }[]
|
|
356
|
+
).map((row) => row.name),
|
|
357
|
+
);
|
|
358
|
+
const objects = db
|
|
359
|
+
.prepare(
|
|
360
|
+
`SELECT name, sql FROM restore.sqlite_master WHERE type IN ('index', 'trigger') AND sql IS NOT NULL`,
|
|
361
|
+
)
|
|
362
|
+
.all() as { name: string; sql: string }[];
|
|
363
|
+
|
|
364
|
+
for (const object of objects) {
|
|
365
|
+
if (existing.has(object.name)) continue;
|
|
366
|
+
db.exec(object.sql);
|
|
367
|
+
existing.add(object.name);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Current descriptors, persisted inside every new backup. */
|
|
372
|
+
function currentSchemas(): BackupSchemas {
|
|
373
|
+
const config = getCmsConfig();
|
|
374
|
+
return {
|
|
375
|
+
title: config.title,
|
|
376
|
+
defaultLocale: config.defaultLocale,
|
|
377
|
+
locales: config.locales,
|
|
378
|
+
collections: config.collections,
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Validate the schema section of an uploaded archive. */
|
|
383
|
+
function normalizeSchemas(
|
|
384
|
+
value: unknown,
|
|
385
|
+
fallback: BackupSchemas,
|
|
386
|
+
): BackupSchemas | null {
|
|
387
|
+
if (!value || typeof value !== "object") return null;
|
|
388
|
+
const record = value as Partial<BackupSchemas>;
|
|
389
|
+
if (!Array.isArray(record.collections)) return null;
|
|
390
|
+
|
|
391
|
+
const locales = Array.isArray(record.locales)
|
|
392
|
+
? record.locales.filter(
|
|
393
|
+
(locale): locale is { code: string; label: string } =>
|
|
394
|
+
Boolean(locale) &&
|
|
395
|
+
typeof locale === "object" &&
|
|
396
|
+
typeof (locale as { code?: unknown }).code === "string" &&
|
|
397
|
+
typeof (locale as { label?: unknown }).label === "string",
|
|
398
|
+
)
|
|
399
|
+
: fallback.locales;
|
|
400
|
+
const collections = record.collections.filter(
|
|
401
|
+
(collection): collection is CollectionDef =>
|
|
402
|
+
Boolean(collection) &&
|
|
403
|
+
typeof collection === "object" &&
|
|
404
|
+
typeof (collection as { slug?: unknown }).slug === "string" &&
|
|
405
|
+
typeof (collection as { label?: unknown }).label === "string" &&
|
|
406
|
+
Array.isArray((collection as { fields?: unknown }).fields),
|
|
407
|
+
);
|
|
408
|
+
// A malformed archive must not overwrite the host schemas with a partial set.
|
|
409
|
+
if (collections.length !== record.collections.length) return null;
|
|
410
|
+
|
|
411
|
+
return {
|
|
412
|
+
title: typeof record.title === "string" && record.title ? record.title : fallback.title,
|
|
413
|
+
locales: locales.length > 0 ? locales : fallback.locales,
|
|
414
|
+
defaultLocale:
|
|
415
|
+
typeof record.defaultLocale === "string" && record.defaultLocale
|
|
416
|
+
? record.defaultLocale
|
|
417
|
+
: fallback.defaultLocale,
|
|
418
|
+
collections,
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function humanize(name: string): string {
|
|
423
|
+
const words = name
|
|
424
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
425
|
+
.replace(/[_-]+/g, " ")
|
|
426
|
+
.trim()
|
|
427
|
+
.split(/\s+/)
|
|
428
|
+
.filter(Boolean);
|
|
429
|
+
if (words.length === 0) return name;
|
|
430
|
+
return words
|
|
431
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
432
|
+
.join(" ");
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function inferFieldType(sqlType: string, samples: unknown[]): FieldType {
|
|
436
|
+
const type = (sqlType || "").toUpperCase();
|
|
437
|
+
if (type.includes("INT")) {
|
|
438
|
+
const numbers = samples.map((value) => Number(value));
|
|
439
|
+
if (
|
|
440
|
+
numbers.length > 0 &&
|
|
441
|
+
numbers.every((value) => value === 0 || value === 1)
|
|
442
|
+
) {
|
|
443
|
+
return "boolean";
|
|
444
|
+
}
|
|
445
|
+
return "number";
|
|
446
|
+
}
|
|
447
|
+
if (
|
|
448
|
+
type.includes("REAL") ||
|
|
449
|
+
type.includes("NUM") ||
|
|
450
|
+
type.includes("DEC") ||
|
|
451
|
+
type.includes("FLOA") ||
|
|
452
|
+
type.includes("DOUB")
|
|
453
|
+
) {
|
|
454
|
+
return "number";
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
for (const value of samples) {
|
|
458
|
+
if (typeof value !== "string") continue;
|
|
459
|
+
const text = value.trim();
|
|
460
|
+
if (!text) continue;
|
|
461
|
+
if (
|
|
462
|
+
(text.startsWith("/files/") || text.startsWith("/images/")) &&
|
|
463
|
+
/\.(png|jpe?g|gif|webp|avif|svg|pdf)(\?|$)/i.test(text)
|
|
464
|
+
) {
|
|
465
|
+
return "media";
|
|
466
|
+
}
|
|
467
|
+
if (text.startsWith("[") && text.endsWith("]")) {
|
|
468
|
+
try {
|
|
469
|
+
const parsed: unknown = JSON.parse(text);
|
|
470
|
+
if (Array.isArray(parsed) && parsed.length > 0) {
|
|
471
|
+
if (
|
|
472
|
+
parsed.every(
|
|
473
|
+
(entry) =>
|
|
474
|
+
Boolean(entry) &&
|
|
475
|
+
typeof entry === "object" &&
|
|
476
|
+
!Array.isArray(entry) &&
|
|
477
|
+
typeof (entry as { url?: unknown }).url === "string" &&
|
|
478
|
+
isMediaUrl((entry as { url: string }).url) &&
|
|
479
|
+
Object.keys(entry as Record<string, unknown>).every((key) =>
|
|
480
|
+
["url", "alt", "primary"].includes(key),
|
|
481
|
+
),
|
|
482
|
+
)
|
|
483
|
+
) {
|
|
484
|
+
return "media-list";
|
|
485
|
+
}
|
|
486
|
+
if (
|
|
487
|
+
parsed.every(
|
|
488
|
+
(entry) =>
|
|
489
|
+
Boolean(entry) &&
|
|
490
|
+
typeof entry === "object" &&
|
|
491
|
+
!Array.isArray(entry),
|
|
492
|
+
)
|
|
493
|
+
) {
|
|
494
|
+
return "object-list";
|
|
495
|
+
}
|
|
496
|
+
if (parsed.every((entry) => typeof entry === "string")) {
|
|
497
|
+
return "list";
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
} catch {
|
|
501
|
+
// Not JSON; keep it as text.
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
return "text";
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Approximate type of a value found inside an inferred `object-list`. */
|
|
509
|
+
function inferScalarType(samples: unknown[]): FieldType {
|
|
510
|
+
if (samples.length > 0 && samples.every((value) => typeof value === "boolean")) {
|
|
511
|
+
return "boolean";
|
|
512
|
+
}
|
|
513
|
+
if (samples.length > 0 && samples.every((value) => typeof value === "number")) {
|
|
514
|
+
return "number";
|
|
515
|
+
}
|
|
516
|
+
if (
|
|
517
|
+
samples.length > 0 &&
|
|
518
|
+
samples.every(
|
|
519
|
+
(value) =>
|
|
520
|
+
Array.isArray(value) &&
|
|
521
|
+
value.every((entry) => typeof entry === "string"),
|
|
522
|
+
)
|
|
523
|
+
) {
|
|
524
|
+
return "list";
|
|
525
|
+
}
|
|
526
|
+
return "text";
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** Reconstruct the subfields of an inferred `object-list` from raw samples. */
|
|
530
|
+
function inferObjectFields(samples: unknown[]): FieldDef[] {
|
|
531
|
+
const values = new Map<string, unknown[]>();
|
|
532
|
+
for (const sample of samples) {
|
|
533
|
+
if (typeof sample !== "string") continue;
|
|
534
|
+
try {
|
|
535
|
+
const parsed: unknown = JSON.parse(sample);
|
|
536
|
+
if (!Array.isArray(parsed)) continue;
|
|
537
|
+
for (const entry of parsed) {
|
|
538
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
539
|
+
for (const [key, value] of Object.entries(
|
|
540
|
+
entry as Record<string, unknown>,
|
|
541
|
+
)) {
|
|
542
|
+
const list = values.get(key) ?? [];
|
|
543
|
+
if (value !== null && value !== undefined) list.push(value);
|
|
544
|
+
values.set(key, list);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
} catch {
|
|
548
|
+
// Not JSON; ignore this sample.
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return [...values.entries()].map(([name, entries]) => ({
|
|
552
|
+
name,
|
|
553
|
+
label: humanize(name),
|
|
554
|
+
type: inferScalarType(entries),
|
|
555
|
+
localized: false,
|
|
556
|
+
}));
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Reconstruct descriptors from the backup database for archives created before
|
|
561
|
+
* schemas were embedded. Types are inferred from SQLite columns and samples.
|
|
562
|
+
*/
|
|
563
|
+
function inferSchemas(
|
|
564
|
+
db: ReturnType<typeof getDb>,
|
|
565
|
+
schema: "restore",
|
|
566
|
+
fallback: BackupSchemas,
|
|
567
|
+
): BackupSchemas {
|
|
568
|
+
const localeCodes = [...fallback.locales.map((locale) => locale.code)].sort(
|
|
569
|
+
(a, b) => b.length - a.length,
|
|
570
|
+
);
|
|
571
|
+
const collections: CollectionDef[] = [];
|
|
572
|
+
|
|
573
|
+
for (const table of attachedTables(db, schema)) {
|
|
574
|
+
if (!table.name.startsWith("c_")) continue;
|
|
575
|
+
const slug = table.name.slice(2);
|
|
576
|
+
const columns = db
|
|
577
|
+
.prepare(`PRAGMA ${schema}.table_info(${quoteIdent(table.name)})`)
|
|
578
|
+
.all() as { name: string; type: string }[];
|
|
579
|
+
const rows = db
|
|
580
|
+
.prepare(`SELECT * FROM ${schema}.${quoteIdent(table.name)} LIMIT 100`)
|
|
581
|
+
.all() as Record<string, unknown>[];
|
|
582
|
+
|
|
583
|
+
type Group = {
|
|
584
|
+
base: string;
|
|
585
|
+
localized: boolean;
|
|
586
|
+
locales: Set<string>;
|
|
587
|
+
sqlType: string;
|
|
588
|
+
samples: unknown[];
|
|
589
|
+
};
|
|
590
|
+
const groups = new Map<string, Group>();
|
|
591
|
+
|
|
592
|
+
for (const column of columns) {
|
|
593
|
+
if (column.name === "id" || column.name === "created_at" || column.name === "updated_at") {
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
let base = column.name;
|
|
597
|
+
let localized = false;
|
|
598
|
+
let locale: string | null = null;
|
|
599
|
+
for (const code of localeCodes) {
|
|
600
|
+
if (column.name.endsWith(`_${code}`)) {
|
|
601
|
+
base = column.name.slice(0, -code.length - 1);
|
|
602
|
+
localized = true;
|
|
603
|
+
locale = code;
|
|
604
|
+
break;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
let group = groups.get(base);
|
|
609
|
+
if (!group) {
|
|
610
|
+
group = { base, localized: false, locales: new Set(), sqlType: column.type, samples: [] };
|
|
611
|
+
groups.set(base, group);
|
|
612
|
+
}
|
|
613
|
+
if (localized && locale) {
|
|
614
|
+
group.localized = true;
|
|
615
|
+
group.locales.add(locale);
|
|
616
|
+
}
|
|
617
|
+
if (!group.sqlType) group.sqlType = column.type;
|
|
618
|
+
for (const row of rows) {
|
|
619
|
+
const value = row[column.name];
|
|
620
|
+
if (value !== null && value !== undefined) group.samples.push(value);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
const fields: FieldDef[] = [];
|
|
625
|
+
const usedLocales = new Set<string>();
|
|
626
|
+
for (const group of groups.values()) {
|
|
627
|
+
const type = inferFieldType(group.sqlType, group.samples.slice(0, 50));
|
|
628
|
+
const field: FieldDef = {
|
|
629
|
+
name: group.base,
|
|
630
|
+
label: humanize(group.base),
|
|
631
|
+
type,
|
|
632
|
+
localized: group.localized,
|
|
633
|
+
};
|
|
634
|
+
if (type === "object-list") {
|
|
635
|
+
const inferred = inferObjectFields(group.samples.slice(0, 50));
|
|
636
|
+
if (inferred.length > 0) {
|
|
637
|
+
field.fields = inferred;
|
|
638
|
+
} else {
|
|
639
|
+
field.type = "text";
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
fields.push(field);
|
|
643
|
+
for (const code of group.locales) usedLocales.add(code);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
const collection: CollectionDef = {
|
|
647
|
+
slug,
|
|
648
|
+
label: humanize(slug),
|
|
649
|
+
fields,
|
|
650
|
+
};
|
|
651
|
+
if (usedLocales.size > 0) {
|
|
652
|
+
collection.locales = fallback.locales
|
|
653
|
+
.map((locale) => locale.code)
|
|
654
|
+
.filter((code) => usedLocales.has(code));
|
|
655
|
+
}
|
|
656
|
+
collections.push(collection);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
return {
|
|
660
|
+
title: fallback.title,
|
|
661
|
+
defaultLocale: fallback.defaultLocale,
|
|
662
|
+
locales: fallback.locales,
|
|
663
|
+
collections,
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function schemaDirectory(): string {
|
|
668
|
+
return resolve(process.cwd(), getCmsConfig().schemas.path);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** Make the restored descriptors active immediately, not only after reboot. */
|
|
672
|
+
function applySchemas(schemas: BackupSchemas): void {
|
|
673
|
+
const current = getCmsConfig();
|
|
674
|
+
configureCms({
|
|
675
|
+
...current,
|
|
676
|
+
title: schemas.title,
|
|
677
|
+
collections: schemas.collections,
|
|
678
|
+
locales: schemas.locales,
|
|
679
|
+
defaultLocale: schemas.defaultLocale,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
|
|
283
683
|
/**
|
|
284
684
|
* Restore a backup archive.
|
|
285
685
|
*
|
|
286
686
|
* Instead of replacing the SQLite file on disk (which conflicts with the live
|
|
287
687
|
* connection and any duplicated module instances), the uploaded database is
|
|
288
688
|
* attached and its tables are copied into the running database inside a single
|
|
289
|
-
* transaction.
|
|
689
|
+
* transaction. The schema modules are rewritten to `schemas.path` and bundled
|
|
690
|
+
* assets to `public/`.
|
|
290
691
|
*/
|
|
291
692
|
export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
292
693
|
const payload = parsePayload(buffer);
|
|
@@ -305,6 +706,8 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
305
706
|
}
|
|
306
707
|
|
|
307
708
|
const db = getDb();
|
|
709
|
+
const fallback = currentSchemas();
|
|
710
|
+
let schemas = normalizeSchemas(payload.schemas, fallback);
|
|
308
711
|
const tmp = join(
|
|
309
712
|
tmpdir(),
|
|
310
713
|
`serenojs-restore-${Date.now()}-${Math.random().toString(16).slice(2)}.db`,
|
|
@@ -321,16 +724,10 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
321
724
|
}
|
|
322
725
|
|
|
323
726
|
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
|
-
);
|
|
727
|
+
const restoredTables = attachedTables(db, "restore");
|
|
728
|
+
const restored = new Set(restoredTables.map((table) => table.name));
|
|
333
729
|
const existing = new Set(mainTables(db));
|
|
730
|
+
schemas ??= inferSchemas(db, "restore", fallback);
|
|
334
731
|
|
|
335
732
|
db.exec("BEGIN");
|
|
336
733
|
try {
|
|
@@ -340,12 +737,18 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
340
737
|
db.exec(`DELETE FROM main.${quoteIdent(table)}`);
|
|
341
738
|
}
|
|
342
739
|
}
|
|
343
|
-
//
|
|
740
|
+
// Recreate missing tables so the backup schema itself is restored.
|
|
741
|
+
for (const table of restoredTables) {
|
|
742
|
+
if (existing.has(table.name)) continue;
|
|
743
|
+
createMissingTable(db, table);
|
|
744
|
+
existing.add(table.name);
|
|
745
|
+
}
|
|
746
|
+
// Copy every shared table, column by column.
|
|
344
747
|
for (const table of restored) {
|
|
345
|
-
|
|
346
|
-
|
|
748
|
+
const target = new Set(tableColumns(db, "main", table));
|
|
749
|
+
addMissingColumns(db, table, target);
|
|
347
750
|
const source = new Set(tableColumns(db, "restore", table));
|
|
348
|
-
const columns = target.filter((column) => source.has(column));
|
|
751
|
+
const columns = [...target].filter((column) => source.has(column));
|
|
349
752
|
if (columns.length === 0) continue;
|
|
350
753
|
const list = columns.map(quoteIdent).join(", ");
|
|
351
754
|
db.exec(`DELETE FROM main.${quoteIdent(table)}`);
|
|
@@ -353,6 +756,8 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
353
756
|
`INSERT INTO main.${quoteIdent(table)} (${list}) SELECT ${list} FROM restore.${quoteIdent(table)}`,
|
|
354
757
|
);
|
|
355
758
|
}
|
|
759
|
+
// Restore indexes/triggers declared by the backup.
|
|
760
|
+
createMissingSchemaObjects(db);
|
|
356
761
|
db.exec("COMMIT");
|
|
357
762
|
} catch (error) {
|
|
358
763
|
db.exec("ROLLBACK");
|
|
@@ -370,12 +775,25 @@ export function restoreBackup(buffer: Buffer): BackupManifest {
|
|
|
370
775
|
writeAsset(asset.path, Buffer.from(asset.data, "base64"));
|
|
371
776
|
}
|
|
372
777
|
|
|
778
|
+
const restoredSchemas = schemas ?? fallback;
|
|
779
|
+
let written: SchemaWriteResult;
|
|
780
|
+
try {
|
|
781
|
+
written = writeSchemaFiles(schemaDirectory(), restoredSchemas);
|
|
782
|
+
} catch (error) {
|
|
783
|
+
throw new BackupError(
|
|
784
|
+
`Banco e arquivos restaurados, mas não foi possível gravar os schemas: ${(error as Error).message}`,
|
|
785
|
+
500,
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
applySchemas(restoredSchemas);
|
|
789
|
+
|
|
373
790
|
return {
|
|
374
791
|
format: payload.format,
|
|
375
792
|
version: payload.version,
|
|
376
793
|
createdAt: payload.createdAt,
|
|
377
794
|
databaseBytes: database.length,
|
|
378
795
|
assets: payload.assets.length,
|
|
796
|
+
schemas: written.files,
|
|
379
797
|
};
|
|
380
798
|
}
|
|
381
799
|
|
package/src/core/db.server.ts
CHANGED
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
Item,
|
|
25
25
|
ListResult,
|
|
26
26
|
MediaItem,
|
|
27
|
+
ObjectItem,
|
|
27
28
|
} from "./types.js";
|
|
28
29
|
|
|
29
30
|
import { getCmsConfig } from "../runtime.js";
|
|
@@ -269,6 +270,15 @@ function serialize(field: FieldDef, value: FieldValue): string | number | null {
|
|
|
269
270
|
.filter(Boolean);
|
|
270
271
|
return entries.length > 0 ? JSON.stringify(entries) : null;
|
|
271
272
|
}
|
|
273
|
+
case "object-list": {
|
|
274
|
+
const items = Array.isArray(value)
|
|
275
|
+
? value.filter(
|
|
276
|
+
(entry): entry is ObjectItem =>
|
|
277
|
+
Boolean(entry) && typeof entry === "object" && !Array.isArray(entry),
|
|
278
|
+
)
|
|
279
|
+
: [];
|
|
280
|
+
return items.length > 0 ? JSON.stringify(items) : null;
|
|
281
|
+
}
|
|
272
282
|
default:
|
|
273
283
|
return String(value);
|
|
274
284
|
}
|
|
@@ -308,6 +318,20 @@ function parseStringList(raw: unknown): string[] {
|
|
|
308
318
|
}
|
|
309
319
|
}
|
|
310
320
|
|
|
321
|
+
function parseObjectList(raw: unknown): ObjectItem[] {
|
|
322
|
+
if (typeof raw !== "string" || !raw.trim()) return [];
|
|
323
|
+
try {
|
|
324
|
+
const parsed = JSON.parse(raw);
|
|
325
|
+
if (!Array.isArray(parsed)) return [];
|
|
326
|
+
return parsed.filter(
|
|
327
|
+
(entry): entry is ObjectItem =>
|
|
328
|
+
Boolean(entry) && typeof entry === "object" && !Array.isArray(entry),
|
|
329
|
+
);
|
|
330
|
+
} catch {
|
|
331
|
+
return [];
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
311
335
|
/** Decode a single raw column value into a field value. */
|
|
312
336
|
function decodeFieldValue(field: FieldDef, raw: unknown): FieldValue {
|
|
313
337
|
switch (field.type) {
|
|
@@ -325,6 +349,8 @@ function decodeFieldValue(field: FieldDef, raw: unknown): FieldValue {
|
|
|
325
349
|
return parseMediaList(raw);
|
|
326
350
|
case "list":
|
|
327
351
|
return parseStringList(raw);
|
|
352
|
+
case "object-list":
|
|
353
|
+
return parseObjectList(raw);
|
|
328
354
|
default:
|
|
329
355
|
return raw === null || raw === undefined ? "" : String(raw);
|
|
330
356
|
}
|
|
@@ -402,7 +428,14 @@ export function listItems(
|
|
|
402
428
|
const search = q.trim();
|
|
403
429
|
if (search) {
|
|
404
430
|
const searchColumns = storedColumns(collection).filter((entry) =>
|
|
405
|
-
[
|
|
431
|
+
[
|
|
432
|
+
"text",
|
|
433
|
+
"email",
|
|
434
|
+
"textarea",
|
|
435
|
+
"richtext",
|
|
436
|
+
"select",
|
|
437
|
+
"date",
|
|
438
|
+
].includes(entry.field.type),
|
|
406
439
|
);
|
|
407
440
|
if (searchColumns.length > 0) {
|
|
408
441
|
where =
|