@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.
Files changed (51) hide show
  1. package/README.md +30 -11
  2. package/admin-dist/assets/index-CEMJnHOP.js +22 -0
  3. package/admin-dist/assets/index-Di8sAvwO.css +2 -0
  4. package/admin-dist/assets/marked.esm-BBttRptN.js +77 -0
  5. package/admin-dist/assets/purify.es-Bz-uQoIK.js +3 -0
  6. package/admin-dist/index.html +2 -2
  7. package/dist/config.d.ts +9 -2
  8. package/dist/config.js +1 -0
  9. package/dist/core/backup.server.d.ts +5 -2
  10. package/dist/core/backup.server.js +346 -12
  11. package/dist/core/db.server.js +29 -1
  12. package/dist/core/schema-codegen.server.d.ts +17 -0
  13. package/dist/core/schema-codegen.server.js +155 -0
  14. package/dist/core/schema.js +8 -1
  15. package/dist/core/types.d.ts +15 -4
  16. package/dist/core/validation.js +61 -0
  17. package/dist/ui/admin/collection-manager.js +1 -1
  18. package/dist/ui/admin/display.js +7 -0
  19. package/dist/ui/admin/field-control.d.ts +3 -1
  20. package/dist/ui/admin/field-control.js +10 -2
  21. package/dist/ui/admin/i18n.js +30 -4
  22. package/dist/ui/admin/object-list-control.d.ts +15 -0
  23. package/dist/ui/admin/object-list-control.js +42 -0
  24. package/dist/ui/admin/rich-text-control.d.ts +15 -0
  25. package/dist/ui/admin/rich-text-control.js +62 -0
  26. package/dist/ui/admin/rich-text-icons.d.ts +8 -0
  27. package/dist/ui/admin/rich-text-icons.js +18 -0
  28. package/dist/ui/index.d.ts +1 -0
  29. package/dist/ui/index.js +1 -0
  30. package/dist/ui/markdown-preview.d.ts +10 -0
  31. package/dist/ui/markdown-preview.js +34 -0
  32. package/package.json +4 -1
  33. package/src/admin/styles.css +152 -0
  34. package/src/config.ts +6 -1
  35. package/src/core/backup.server.ts +435 -17
  36. package/src/core/db.server.ts +34 -1
  37. package/src/core/schema-codegen.server.ts +187 -0
  38. package/src/core/schema.ts +8 -1
  39. package/src/core/types.ts +18 -3
  40. package/src/core/validation.ts +71 -0
  41. package/src/ui/admin/collection-manager.tsx +1 -0
  42. package/src/ui/admin/display.tsx +13 -1
  43. package/src/ui/admin/field-control.tsx +43 -2
  44. package/src/ui/admin/i18n.tsx +32 -4
  45. package/src/ui/admin/object-list-control.tsx +154 -0
  46. package/src/ui/admin/rich-text-control.tsx +173 -0
  47. package/src/ui/admin/rich-text-icons.tsx +125 -0
  48. package/src/ui/index.ts +1 -0
  49. package/src/ui/markdown-preview.tsx +42 -0
  50. package/admin-dist/assets/index-B3EgqtT6.js +0 -9
  51. package/admin-dist/assets/index-D2m0Eb4k.css +0 -2
@@ -1,8 +1,9 @@
1
1
  /**
2
- * Database + uploaded-assets backup and restore.
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.
@@ -17,9 +18,11 @@ import { tmpdir } from "node:os";
17
18
  import { join, relative, resolve, sep } from "node:path";
18
19
  import { gunzipSync, gzipSync } from "node:zlib";
19
20
  import { getDb } from "./db.server.js";
20
- import { getCmsConfig } from "../runtime.js";
21
+ import { writeSchemaFiles, } from "./schema-codegen.server.js";
22
+ import { configureCms, getCmsConfig } from "../runtime.js";
23
+ import { isMediaUrl } from "./media.js";
21
24
  export const BACKUP_FORMAT = "serenojs-backup";
22
- export const BACKUP_VERSION = 1;
25
+ export const BACKUP_VERSION = 2;
23
26
  export const BACKUP_EXTENSION = ".serenojs";
24
27
  export const BACKUP_DIR = resolve(process.cwd(), ".data/backups");
25
28
  export const PUBLIC_DIR = resolve(process.cwd(), "public");
@@ -86,6 +89,7 @@ function buildPayload() {
86
89
  createdAt: new Date().toISOString(),
87
90
  database: database.toString("base64"),
88
91
  assets,
92
+ schemas: currentSchemas(),
89
93
  };
90
94
  }
91
95
  /** Create an in-memory backup archive (gzip). */
@@ -210,13 +214,323 @@ function tableColumns(db, schema, table) {
210
214
  function quoteIdent(name) {
211
215
  return `"${name.replace(/"/g, '""')}"`;
212
216
  }
217
+ /** Tables declared in an attached schema (excluding SQLite internals). */
218
+ function attachedTables(db, schema) {
219
+ return db
220
+ .prepare(`SELECT name, sql FROM ${schema}.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
221
+ .all();
222
+ }
223
+ /** Recreate a table that does not exist in the live database yet. */
224
+ function createMissingTable(db, table) {
225
+ if (!table.sql)
226
+ return;
227
+ db.exec(table.sql);
228
+ }
229
+ /**
230
+ * Add columns that exist in the backup but not in the live table. Without this,
231
+ * data stored in newer columns would be silently dropped on restore.
232
+ */
233
+ function addMissingColumns(db, table, target) {
234
+ const source = db
235
+ .prepare(`PRAGMA restore.table_info(${quoteIdent(table)})`)
236
+ .all();
237
+ for (const column of source) {
238
+ if (target.has(column.name))
239
+ continue;
240
+ let definition = `${quoteIdent(column.name)} ${column.type || "TEXT"}`;
241
+ if (column.dflt_value !== null) {
242
+ definition += ` NOT NULL DEFAULT ${column.dflt_value}`;
243
+ }
244
+ // SQLite cannot add a NOT NULL column without a default; keep it nullable.
245
+ db.exec(`ALTER TABLE main.${quoteIdent(table)} ADD COLUMN ${definition}`);
246
+ target.add(column.name);
247
+ }
248
+ }
249
+ /** Recreate indexes/triggers from the backup whose names are absent live. */
250
+ function createMissingSchemaObjects(db) {
251
+ const existing = new Set(db
252
+ .prepare(`SELECT name FROM main.sqlite_master WHERE type IN ('index', 'trigger')`)
253
+ .all().map((row) => row.name));
254
+ const objects = db
255
+ .prepare(`SELECT name, sql FROM restore.sqlite_master WHERE type IN ('index', 'trigger') AND sql IS NOT NULL`)
256
+ .all();
257
+ for (const object of objects) {
258
+ if (existing.has(object.name))
259
+ continue;
260
+ db.exec(object.sql);
261
+ existing.add(object.name);
262
+ }
263
+ }
264
+ /** Current descriptors, persisted inside every new backup. */
265
+ function currentSchemas() {
266
+ const config = getCmsConfig();
267
+ return {
268
+ title: config.title,
269
+ defaultLocale: config.defaultLocale,
270
+ locales: config.locales,
271
+ collections: config.collections,
272
+ };
273
+ }
274
+ /** Validate the schema section of an uploaded archive. */
275
+ function normalizeSchemas(value, fallback) {
276
+ if (!value || typeof value !== "object")
277
+ return null;
278
+ const record = value;
279
+ if (!Array.isArray(record.collections))
280
+ return null;
281
+ const locales = Array.isArray(record.locales)
282
+ ? record.locales.filter((locale) => Boolean(locale) &&
283
+ typeof locale === "object" &&
284
+ typeof locale.code === "string" &&
285
+ typeof locale.label === "string")
286
+ : fallback.locales;
287
+ const collections = record.collections.filter((collection) => Boolean(collection) &&
288
+ typeof collection === "object" &&
289
+ typeof collection.slug === "string" &&
290
+ typeof collection.label === "string" &&
291
+ Array.isArray(collection.fields));
292
+ // A malformed archive must not overwrite the host schemas with a partial set.
293
+ if (collections.length !== record.collections.length)
294
+ return null;
295
+ return {
296
+ title: typeof record.title === "string" && record.title ? record.title : fallback.title,
297
+ locales: locales.length > 0 ? locales : fallback.locales,
298
+ defaultLocale: typeof record.defaultLocale === "string" && record.defaultLocale
299
+ ? record.defaultLocale
300
+ : fallback.defaultLocale,
301
+ collections,
302
+ };
303
+ }
304
+ function humanize(name) {
305
+ const words = name
306
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
307
+ .replace(/[_-]+/g, " ")
308
+ .trim()
309
+ .split(/\s+/)
310
+ .filter(Boolean);
311
+ if (words.length === 0)
312
+ return name;
313
+ return words
314
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
315
+ .join(" ");
316
+ }
317
+ function inferFieldType(sqlType, samples) {
318
+ const type = (sqlType || "").toUpperCase();
319
+ if (type.includes("INT")) {
320
+ const numbers = samples.map((value) => Number(value));
321
+ if (numbers.length > 0 &&
322
+ numbers.every((value) => value === 0 || value === 1)) {
323
+ return "boolean";
324
+ }
325
+ return "number";
326
+ }
327
+ if (type.includes("REAL") ||
328
+ type.includes("NUM") ||
329
+ type.includes("DEC") ||
330
+ type.includes("FLOA") ||
331
+ type.includes("DOUB")) {
332
+ return "number";
333
+ }
334
+ for (const value of samples) {
335
+ if (typeof value !== "string")
336
+ continue;
337
+ const text = value.trim();
338
+ if (!text)
339
+ continue;
340
+ if ((text.startsWith("/files/") || text.startsWith("/images/")) &&
341
+ /\.(png|jpe?g|gif|webp|avif|svg|pdf)(\?|$)/i.test(text)) {
342
+ return "media";
343
+ }
344
+ if (text.startsWith("[") && text.endsWith("]")) {
345
+ try {
346
+ const parsed = JSON.parse(text);
347
+ if (Array.isArray(parsed) && parsed.length > 0) {
348
+ if (parsed.every((entry) => Boolean(entry) &&
349
+ typeof entry === "object" &&
350
+ !Array.isArray(entry) &&
351
+ typeof entry.url === "string" &&
352
+ isMediaUrl(entry.url) &&
353
+ Object.keys(entry).every((key) => ["url", "alt", "primary"].includes(key)))) {
354
+ return "media-list";
355
+ }
356
+ if (parsed.every((entry) => Boolean(entry) &&
357
+ typeof entry === "object" &&
358
+ !Array.isArray(entry))) {
359
+ return "object-list";
360
+ }
361
+ if (parsed.every((entry) => typeof entry === "string")) {
362
+ return "list";
363
+ }
364
+ }
365
+ }
366
+ catch {
367
+ // Not JSON; keep it as text.
368
+ }
369
+ }
370
+ }
371
+ return "text";
372
+ }
373
+ /** Approximate type of a value found inside an inferred `object-list`. */
374
+ function inferScalarType(samples) {
375
+ if (samples.length > 0 && samples.every((value) => typeof value === "boolean")) {
376
+ return "boolean";
377
+ }
378
+ if (samples.length > 0 && samples.every((value) => typeof value === "number")) {
379
+ return "number";
380
+ }
381
+ if (samples.length > 0 &&
382
+ samples.every((value) => Array.isArray(value) &&
383
+ value.every((entry) => typeof entry === "string"))) {
384
+ return "list";
385
+ }
386
+ return "text";
387
+ }
388
+ /** Reconstruct the subfields of an inferred `object-list` from raw samples. */
389
+ function inferObjectFields(samples) {
390
+ const values = new Map();
391
+ for (const sample of samples) {
392
+ if (typeof sample !== "string")
393
+ continue;
394
+ try {
395
+ const parsed = JSON.parse(sample);
396
+ if (!Array.isArray(parsed))
397
+ continue;
398
+ for (const entry of parsed) {
399
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
400
+ continue;
401
+ for (const [key, value] of Object.entries(entry)) {
402
+ const list = values.get(key) ?? [];
403
+ if (value !== null && value !== undefined)
404
+ list.push(value);
405
+ values.set(key, list);
406
+ }
407
+ }
408
+ }
409
+ catch {
410
+ // Not JSON; ignore this sample.
411
+ }
412
+ }
413
+ return [...values.entries()].map(([name, entries]) => ({
414
+ name,
415
+ label: humanize(name),
416
+ type: inferScalarType(entries),
417
+ localized: false,
418
+ }));
419
+ }
420
+ /**
421
+ * Reconstruct descriptors from the backup database for archives created before
422
+ * schemas were embedded. Types are inferred from SQLite columns and samples.
423
+ */
424
+ function inferSchemas(db, schema, fallback) {
425
+ const localeCodes = [...fallback.locales.map((locale) => locale.code)].sort((a, b) => b.length - a.length);
426
+ const collections = [];
427
+ for (const table of attachedTables(db, schema)) {
428
+ if (!table.name.startsWith("c_"))
429
+ continue;
430
+ const slug = table.name.slice(2);
431
+ const columns = db
432
+ .prepare(`PRAGMA ${schema}.table_info(${quoteIdent(table.name)})`)
433
+ .all();
434
+ const rows = db
435
+ .prepare(`SELECT * FROM ${schema}.${quoteIdent(table.name)} LIMIT 100`)
436
+ .all();
437
+ const groups = new Map();
438
+ for (const column of columns) {
439
+ if (column.name === "id" || column.name === "created_at" || column.name === "updated_at") {
440
+ continue;
441
+ }
442
+ let base = column.name;
443
+ let localized = false;
444
+ let locale = null;
445
+ for (const code of localeCodes) {
446
+ if (column.name.endsWith(`_${code}`)) {
447
+ base = column.name.slice(0, -code.length - 1);
448
+ localized = true;
449
+ locale = code;
450
+ break;
451
+ }
452
+ }
453
+ let group = groups.get(base);
454
+ if (!group) {
455
+ group = { base, localized: false, locales: new Set(), sqlType: column.type, samples: [] };
456
+ groups.set(base, group);
457
+ }
458
+ if (localized && locale) {
459
+ group.localized = true;
460
+ group.locales.add(locale);
461
+ }
462
+ if (!group.sqlType)
463
+ group.sqlType = column.type;
464
+ for (const row of rows) {
465
+ const value = row[column.name];
466
+ if (value !== null && value !== undefined)
467
+ group.samples.push(value);
468
+ }
469
+ }
470
+ const fields = [];
471
+ const usedLocales = new Set();
472
+ for (const group of groups.values()) {
473
+ const type = inferFieldType(group.sqlType, group.samples.slice(0, 50));
474
+ const field = {
475
+ name: group.base,
476
+ label: humanize(group.base),
477
+ type,
478
+ localized: group.localized,
479
+ };
480
+ if (type === "object-list") {
481
+ const inferred = inferObjectFields(group.samples.slice(0, 50));
482
+ if (inferred.length > 0) {
483
+ field.fields = inferred;
484
+ }
485
+ else {
486
+ field.type = "text";
487
+ }
488
+ }
489
+ fields.push(field);
490
+ for (const code of group.locales)
491
+ usedLocales.add(code);
492
+ }
493
+ const collection = {
494
+ slug,
495
+ label: humanize(slug),
496
+ fields,
497
+ };
498
+ if (usedLocales.size > 0) {
499
+ collection.locales = fallback.locales
500
+ .map((locale) => locale.code)
501
+ .filter((code) => usedLocales.has(code));
502
+ }
503
+ collections.push(collection);
504
+ }
505
+ return {
506
+ title: fallback.title,
507
+ defaultLocale: fallback.defaultLocale,
508
+ locales: fallback.locales,
509
+ collections,
510
+ };
511
+ }
512
+ function schemaDirectory() {
513
+ return resolve(process.cwd(), getCmsConfig().schemas.path);
514
+ }
515
+ /** Make the restored descriptors active immediately, not only after reboot. */
516
+ function applySchemas(schemas) {
517
+ const current = getCmsConfig();
518
+ configureCms({
519
+ ...current,
520
+ title: schemas.title,
521
+ collections: schemas.collections,
522
+ locales: schemas.locales,
523
+ defaultLocale: schemas.defaultLocale,
524
+ });
525
+ }
213
526
  /**
214
527
  * Restore a backup archive.
215
528
  *
216
529
  * Instead of replacing the SQLite file on disk (which conflicts with the live
217
530
  * connection and any duplicated module instances), the uploaded database is
218
531
  * attached and its tables are copied into the running database inside a single
219
- * transaction. Bundled assets are rewritten to `public/`.
532
+ * transaction. The schema modules are rewritten to `schemas.path` and bundled
533
+ * assets to `public/`.
220
534
  */
221
535
  export function restoreBackup(buffer) {
222
536
  const payload = parsePayload(buffer);
@@ -232,6 +546,8 @@ export function restoreBackup(buffer) {
232
546
  throw new BackupError("Banco de dados do backup é inválido.");
233
547
  }
234
548
  const db = getDb();
549
+ const fallback = currentSchemas();
550
+ let schemas = normalizeSchemas(payload.schemas, fallback);
235
551
  const tmp = join(tmpdir(), `serenojs-restore-${Date.now()}-${Math.random().toString(16).slice(2)}.db`);
236
552
  writeFileSync(tmp, database);
237
553
  try {
@@ -242,10 +558,10 @@ export function restoreBackup(buffer) {
242
558
  throw new BackupError(`Não foi possível ler o banco do backup: ${error.message}`);
243
559
  }
244
560
  try {
245
- const restored = new Set(db
246
- .prepare(`SELECT name FROM restore.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
247
- .all().map((row) => row.name));
561
+ const restoredTables = attachedTables(db, "restore");
562
+ const restored = new Set(restoredTables.map((table) => table.name));
248
563
  const existing = new Set(mainTables(db));
564
+ schemas ??= inferSchemas(db, "restore", fallback);
249
565
  db.exec("BEGIN");
250
566
  try {
251
567
  // Wipe tables that are not part of the backup.
@@ -254,19 +570,27 @@ export function restoreBackup(buffer) {
254
570
  db.exec(`DELETE FROM main.${quoteIdent(table)}`);
255
571
  }
256
572
  }
257
- // Copy every shared table, column by column (intersection).
258
- for (const table of restored) {
259
- if (!existing.has(table))
573
+ // Recreate missing tables so the backup schema itself is restored.
574
+ for (const table of restoredTables) {
575
+ if (existing.has(table.name))
260
576
  continue;
261
- const target = tableColumns(db, "main", table);
577
+ createMissingTable(db, table);
578
+ existing.add(table.name);
579
+ }
580
+ // Copy every shared table, column by column.
581
+ for (const table of restored) {
582
+ const target = new Set(tableColumns(db, "main", table));
583
+ addMissingColumns(db, table, target);
262
584
  const source = new Set(tableColumns(db, "restore", table));
263
- const columns = target.filter((column) => source.has(column));
585
+ const columns = [...target].filter((column) => source.has(column));
264
586
  if (columns.length === 0)
265
587
  continue;
266
588
  const list = columns.map(quoteIdent).join(", ");
267
589
  db.exec(`DELETE FROM main.${quoteIdent(table)}`);
268
590
  db.exec(`INSERT INTO main.${quoteIdent(table)} (${list}) SELECT ${list} FROM restore.${quoteIdent(table)}`);
269
591
  }
592
+ // Restore indexes/triggers declared by the backup.
593
+ createMissingSchemaObjects(db);
270
594
  db.exec("COMMIT");
271
595
  }
272
596
  catch (error) {
@@ -284,12 +608,22 @@ export function restoreBackup(buffer) {
284
608
  }
285
609
  writeAsset(asset.path, Buffer.from(asset.data, "base64"));
286
610
  }
611
+ const restoredSchemas = schemas ?? fallback;
612
+ let written;
613
+ try {
614
+ written = writeSchemaFiles(schemaDirectory(), restoredSchemas);
615
+ }
616
+ catch (error) {
617
+ throw new BackupError(`Banco e arquivos restaurados, mas não foi possível gravar os schemas: ${error.message}`, 500);
618
+ }
619
+ applySchemas(restoredSchemas);
287
620
  return {
288
621
  format: payload.format,
289
622
  version: payload.version,
290
623
  createdAt: payload.createdAt,
291
624
  databaseBytes: database.length,
292
625
  assets: payload.assets.length,
626
+ schemas: written.files,
293
627
  };
294
628
  }
295
629
  /* -------------------------------------------------------------------------- */
@@ -207,6 +207,12 @@ function serialize(field, value) {
207
207
  .filter(Boolean);
208
208
  return entries.length > 0 ? JSON.stringify(entries) : null;
209
209
  }
210
+ case "object-list": {
211
+ const items = Array.isArray(value)
212
+ ? value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry))
213
+ : [];
214
+ return items.length > 0 ? JSON.stringify(items) : null;
215
+ }
210
216
  default:
211
217
  return String(value);
212
218
  }
@@ -251,6 +257,19 @@ function parseStringList(raw) {
251
257
  return [];
252
258
  }
253
259
  }
260
+ function parseObjectList(raw) {
261
+ if (typeof raw !== "string" || !raw.trim())
262
+ return [];
263
+ try {
264
+ const parsed = JSON.parse(raw);
265
+ if (!Array.isArray(parsed))
266
+ return [];
267
+ return parsed.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
268
+ }
269
+ catch {
270
+ return [];
271
+ }
272
+ }
254
273
  /** Decode a single raw column value into a field value. */
255
274
  function decodeFieldValue(field, raw) {
256
275
  switch (field.type) {
@@ -268,6 +287,8 @@ function decodeFieldValue(field, raw) {
268
287
  return parseMediaList(raw);
269
288
  case "list":
270
289
  return parseStringList(raw);
290
+ case "object-list":
291
+ return parseObjectList(raw);
271
292
  default:
272
293
  return raw === null || raw === undefined ? "" : String(raw);
273
294
  }
@@ -324,7 +345,14 @@ export function listItems(collection, { page = 1, limit = 10, q = "", } = {}) {
324
345
  let where = "";
325
346
  const search = q.trim();
326
347
  if (search) {
327
- const searchColumns = storedColumns(collection).filter((entry) => ["text", "email", "textarea", "select", "date"].includes(entry.field.type));
348
+ const searchColumns = storedColumns(collection).filter((entry) => [
349
+ "text",
350
+ "email",
351
+ "textarea",
352
+ "richtext",
353
+ "select",
354
+ "date",
355
+ ].includes(entry.field.type));
328
356
  if (searchColumns.length > 0) {
329
357
  where =
330
358
  " WHERE " +
@@ -0,0 +1,17 @@
1
+ import type { LocaleDef } from "../config.js";
2
+ import type { CollectionDef } from "./types.js";
3
+ export type BackupSchemas = {
4
+ title: string;
5
+ defaultLocale: string;
6
+ locales: LocaleDef[];
7
+ collections: CollectionDef[];
8
+ };
9
+ export type SchemaWriteResult = {
10
+ files: number;
11
+ collections: number;
12
+ };
13
+ /**
14
+ * Write the backup schemas into `dir` as the conventional starter layout:
15
+ * `index.ts`, `locales.ts` and one module per collection.
16
+ */
17
+ export declare function writeSchemaFiles(dir: string, schemas: BackupSchemas): SchemaWriteResult;
@@ -0,0 +1,155 @@
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
+ const RESERVED_IDENTIFIERS = new Set([
11
+ "break",
12
+ "case",
13
+ "catch",
14
+ "class",
15
+ "const",
16
+ "continue",
17
+ "debugger",
18
+ "default",
19
+ "delete",
20
+ "do",
21
+ "else",
22
+ "enum",
23
+ "export",
24
+ "extends",
25
+ "false",
26
+ "finally",
27
+ "for",
28
+ "function",
29
+ "if",
30
+ "implements",
31
+ "import",
32
+ "in",
33
+ "instanceof",
34
+ "interface",
35
+ "let",
36
+ "new",
37
+ "null",
38
+ "package",
39
+ "private",
40
+ "protected",
41
+ "public",
42
+ "return",
43
+ "static",
44
+ "super",
45
+ "switch",
46
+ "this",
47
+ "throw",
48
+ "true",
49
+ "try",
50
+ "typeof",
51
+ "var",
52
+ "void",
53
+ "while",
54
+ "with",
55
+ "yield",
56
+ ]);
57
+ function identifier(raw, fallback) {
58
+ let value = raw.replace(/[^a-zA-Z0-9_]/g, "_");
59
+ if (!value)
60
+ value = fallback;
61
+ if (/^[0-9]/.test(value))
62
+ value = `_${value}`;
63
+ if (RESERVED_IDENTIFIERS.has(value))
64
+ value = `${value}_`;
65
+ return value;
66
+ }
67
+ function fileBase(raw) {
68
+ const value = raw.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/^[-_]+/, "");
69
+ return value || "collection";
70
+ }
71
+ function literal(value) {
72
+ return JSON.stringify(value, null, 2) ?? "null";
73
+ }
74
+ function collectionModule(exportName, collection) {
75
+ return [
76
+ `import type { CollectionDef } from "@eutobias/serenojs/config";`,
77
+ "",
78
+ `export const ${exportName}: CollectionDef = ${literal(collection)};`,
79
+ "",
80
+ ].join("\n");
81
+ }
82
+ function localesModule(schemas) {
83
+ return [
84
+ `/** Locale registry restored from a SerenoJS backup. */`,
85
+ "",
86
+ `export type LocaleDef = {`,
87
+ ` code: string;`,
88
+ ` label: string;`,
89
+ `};`,
90
+ "",
91
+ `export const locales: LocaleDef[] = ${literal(schemas.locales)};`,
92
+ "",
93
+ `/** Locale used as fallback and for the seed of legacy single-column data. */`,
94
+ `export const defaultLocale = ${literal(schemas.defaultLocale)};`,
95
+ "",
96
+ `/** Display label for a locale code (falls back to the uppercased code). */`,
97
+ `export function localeLabel(code: string): string {`,
98
+ ` return (`,
99
+ ` locales.find((locale) => locale.code === code)?.label ?? code.toUpperCase()`,
100
+ ` );`,
101
+ `}`,
102
+ "",
103
+ ].join("\n");
104
+ }
105
+ function indexModule(schemas, entries) {
106
+ const imports = entries
107
+ .map(({ base, exportName }) => `import { ${exportName} } from "./${base}";`)
108
+ .join("\n");
109
+ const values = entries.map(({ exportName }) => exportName).join(", ");
110
+ return [
111
+ `import type { CollectionDef } from "@eutobias/serenojs/config";`,
112
+ "",
113
+ imports,
114
+ "",
115
+ `export { defaultLocale, localeLabel, locales } from "./locales";`,
116
+ `export type { LocaleDef } from "./locales";`,
117
+ "",
118
+ `/** Title shown across the admin panel. */`,
119
+ `export const schemaTitle = ${literal(schemas.title)};`,
120
+ "",
121
+ `/** Every collection available in the admin/API. */`,
122
+ `export const collections: CollectionDef[] = [${values}];`,
123
+ "",
124
+ ].join("\n");
125
+ }
126
+ /**
127
+ * Write the backup schemas into `dir` as the conventional starter layout:
128
+ * `index.ts`, `locales.ts` and one module per collection.
129
+ */
130
+ export function writeSchemaFiles(dir, schemas) {
131
+ mkdirSync(dir, { recursive: true });
132
+ const usedFiles = new Set(["index", "locales"]);
133
+ const usedExports = new Set();
134
+ const entries = [];
135
+ for (const collection of schemas.collections) {
136
+ const rawBase = fileBase(collection.slug);
137
+ let base = rawBase;
138
+ let suffix = 2;
139
+ while (usedFiles.has(base))
140
+ base = `${rawBase}_${suffix++}`;
141
+ usedFiles.add(base);
142
+ const rawExport = identifier(collection.slug, "collection");
143
+ let exportName = rawExport;
144
+ suffix = 2;
145
+ while (usedExports.has(exportName)) {
146
+ exportName = `${rawExport}_${suffix++}`;
147
+ }
148
+ usedExports.add(exportName);
149
+ writeFileSync(join(dir, `${base}.ts`), collectionModule(exportName, collection), "utf8");
150
+ entries.push({ base, exportName });
151
+ }
152
+ writeFileSync(join(dir, "locales.ts"), localesModule(schemas), "utf8");
153
+ writeFileSync(join(dir, "index.ts"), indexModule(schemas, entries), "utf8");
154
+ return { files: entries.length + 2, collections: entries.length };
155
+ }
@@ -1,7 +1,13 @@
1
1
  import { getDefaultLocale } from "../locale.js";
2
2
  import { getCmsConfig, getCollection as runtimeGetCollection, getCollections as runtimeGetCollections, localeLabel as runtimeLocaleLabel, } from "../runtime.js";
3
3
  /** Field types that are localized by default. */
4
- const LOCALIZED_TYPES = new Set(["text", "textarea", "email", "list"]);
4
+ const LOCALIZED_TYPES = new Set([
5
+ "text",
6
+ "textarea",
7
+ "richtext",
8
+ "email",
9
+ "list",
10
+ ]);
5
11
  /** Locales stored by a collection (falls back to the global default). */
6
12
  export function collectionLocales(collection) {
7
13
  return collection.locales && collection.locales.length > 0
@@ -67,6 +73,7 @@ export function fieldDefault(field) {
67
73
  case "media-list":
68
74
  return [];
69
75
  case "list":
76
+ case "object-list":
70
77
  return [];
71
78
  case "select":
72
79
  return field.options?.[0]?.value ?? "";