@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,526 @@
1
+ /**
2
+ * SQLite persistence layer.
3
+ *
4
+ * Server-only: this module imports `node:sqlite` and must never be pulled into
5
+ * a client bundle. The schema is derived from `src/schemas`; tables are
6
+ * created lazily on first use and new columns are added automatically.
7
+ *
8
+ * Relations:
9
+ * - `one-to-one` → stored as an INTEGER column holding the target id.
10
+ * - `one-to-many` → stored in a join table (the "one" side owns the list).
11
+ * - `many-to-many` → stored in a join table on each side that declares it.
12
+ */
13
+ import { mkdirSync } from "node:fs";
14
+ import { dirname, resolve } from "node:path";
15
+ import { DatabaseSync } from "node:sqlite";
16
+ import { emptyValues, getCollections, tableName } from "./schema.js";
17
+ import { collectionLocales, isLocalizedField } from "./schema.js";
18
+ import { hashPassword } from "../auth/password.server.js";
19
+ import { getCmsConfig } from "../runtime.js";
20
+ /** Resolved lazily: the host middleware configures the CMS at boot. */
21
+ function dbPath() {
22
+ return (process.env.ADMIN_DB_PATH ??
23
+ resolve(process.cwd(), getCmsConfig().db.path));
24
+ }
25
+ const globalScope = globalThis;
26
+ const CACHE_KEY = Symbol.for("serenojs.db");
27
+ const cache = (globalScope[CACHE_KEY] ??= {});
28
+ function quote(name) {
29
+ return `"${name.replace(/"/g, '""')}"`;
30
+ }
31
+ function safeName(name) {
32
+ return name.replace(/[^a-zA-Z0-9_]/g, "_");
33
+ }
34
+ function isManyRelation(field) {
35
+ return field.type === "relation" && field.relation?.type !== "one-to-one";
36
+ }
37
+ /**
38
+ * Every physical column of a collection. Localized fields expand into one
39
+ * column per locale (`name_pt`, `name_en`); the rest keep their field name.
40
+ */
41
+ function storedColumns(collection) {
42
+ const columns = [];
43
+ for (const field of collection.fields) {
44
+ if (isManyRelation(field))
45
+ continue;
46
+ if (isLocalizedField(collection, field)) {
47
+ for (const locale of collectionLocales(collection)) {
48
+ columns.push({ column: `${field.name}_${locale}`, field, locale });
49
+ }
50
+ }
51
+ else {
52
+ columns.push({ column: field.name, field, locale: null });
53
+ }
54
+ }
55
+ return columns;
56
+ }
57
+ /** Join table for a `to-many` relation field. */
58
+ function joinTable(collection, field) {
59
+ return `r_${tableName(collection.slug)}_${safeName(field.name)}`;
60
+ }
61
+ function columnType(field) {
62
+ switch (field.type) {
63
+ case "number":
64
+ return "REAL";
65
+ case "boolean":
66
+ return "INTEGER";
67
+ case "relation":
68
+ return "INTEGER";
69
+ default:
70
+ return "TEXT";
71
+ }
72
+ }
73
+ /** Auth tables: admin users and their rotating session tokens. */
74
+ function migrateAuth(db) {
75
+ db.exec(`CREATE TABLE IF NOT EXISTS auth_users (
76
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
77
+ email TEXT NOT NULL UNIQUE,
78
+ password_hash TEXT NOT NULL,
79
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
80
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
81
+ )`);
82
+ db.exec(`CREATE TABLE IF NOT EXISTS auth_tokens (
83
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
84
+ user_id INTEGER NOT NULL,
85
+ access_token_hash TEXT NOT NULL,
86
+ refresh_token_hash TEXT NOT NULL,
87
+ access_expires_at TEXT NOT NULL,
88
+ refresh_expires_at TEXT NOT NULL,
89
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
90
+ )`);
91
+ db.exec(`CREATE INDEX IF NOT EXISTS auth_tokens_user_idx ON auth_tokens (user_id)`);
92
+ db.exec(`CREATE INDEX IF NOT EXISTS auth_tokens_access_idx ON auth_tokens (access_token_hash)`);
93
+ db.exec(`CREATE INDEX IF NOT EXISTS auth_tokens_refresh_idx ON auth_tokens (refresh_token_hash)`);
94
+ db.exec(`CREATE TABLE IF NOT EXISTS app_meta (
95
+ key TEXT PRIMARY KEY,
96
+ value TEXT NOT NULL
97
+ )`);
98
+ }
99
+ /**
100
+ * Creates the initial admin user the first time the auth tables are used.
101
+ * Override credentials with `ADMIN_EMAIL` / `ADMIN_PASSWORD`.
102
+ */
103
+ function seedAuth(db) {
104
+ const count = db
105
+ .prepare(`SELECT COUNT(*) AS count FROM auth_users`)
106
+ .get();
107
+ if (Number(count.count) > 0)
108
+ return;
109
+ const email = process.env.ADMIN_EMAIL ?? "admin@example.com";
110
+ const password = process.env.ADMIN_PASSWORD ?? "admin123";
111
+ db.prepare(`INSERT INTO auth_users (email, password_hash) VALUES (?, ?)`).run(email, hashPassword(password));
112
+ }
113
+ function migrate(db) {
114
+ migrateAuth(db);
115
+ for (const collection of getCollections()) {
116
+ const table = tableName(collection.slug);
117
+ const columns = storedColumns(collection);
118
+ const definition = columns
119
+ .map((entry) => `${quote(entry.column)} ${columnType(entry.field)}`)
120
+ .join(", ");
121
+ db.exec(`CREATE TABLE IF NOT EXISTS ${table} (
122
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
123
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
124
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
125
+ ${definition ? `, ${definition}` : ""}
126
+ )`);
127
+ const existing = new Set(db.prepare(`PRAGMA table_info(${table})`).all().map((row) => row.name));
128
+ // Legacy single-column data: rename `<field>` to `<field>_<defaultLocale>`
129
+ // so existing values become the default locale. Idempotent.
130
+ const localeCodes = collectionLocales(collection);
131
+ for (const field of collection.fields) {
132
+ if (!isLocalizedField(collection, field))
133
+ continue;
134
+ const target = `${field.name}_${localeCodes[0]}`;
135
+ if (existing.has(field.name) && !existing.has(target)) {
136
+ db.exec(`ALTER TABLE ${table} RENAME COLUMN ${quote(field.name)} TO ${quote(target)}`);
137
+ existing.delete(field.name);
138
+ existing.add(target);
139
+ }
140
+ }
141
+ for (const entry of columns) {
142
+ if (!existing.has(entry.column)) {
143
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${quote(entry.column)} ${columnType(entry.field)}`);
144
+ }
145
+ }
146
+ for (const field of collection.fields) {
147
+ if (!isManyRelation(field))
148
+ continue;
149
+ const join = joinTable(collection, field);
150
+ db.exec(`CREATE TABLE IF NOT EXISTS ${join} (
151
+ source_id INTEGER NOT NULL,
152
+ target_id INTEGER NOT NULL,
153
+ position INTEGER NOT NULL DEFAULT 0,
154
+ PRIMARY KEY (source_id, target_id)
155
+ )`);
156
+ db.exec(`CREATE INDEX IF NOT EXISTS ${join}_target_idx ON ${join} (target_id)`);
157
+ }
158
+ }
159
+ }
160
+ export function getDb() {
161
+ if (cache.db)
162
+ return cache.db;
163
+ const path = dbPath();
164
+ mkdirSync(dirname(path), { recursive: true });
165
+ const db = new DatabaseSync(path);
166
+ db.exec("PRAGMA journal_mode = WAL;");
167
+ migrate(db);
168
+ cache.db = db;
169
+ seedAuth(db);
170
+ return db;
171
+ }
172
+ function serialize(field, value) {
173
+ if (value === null || value === undefined)
174
+ return null;
175
+ switch (field.type) {
176
+ case "boolean":
177
+ return value ? 1 : 0;
178
+ case "number":
179
+ return Number(value);
180
+ case "relation": {
181
+ const id = Number(value);
182
+ return !Array.isArray(value) && Number.isInteger(id) && id > 0 ? id : null;
183
+ }
184
+ case "media-list": {
185
+ const items = Array.isArray(value) ? value : [];
186
+ const media = items
187
+ .map((entry) => {
188
+ if (!entry || typeof entry !== "object")
189
+ return null;
190
+ const record = entry;
191
+ const url = typeof record.url === "string" ? record.url.trim() : "";
192
+ if (!url)
193
+ return null;
194
+ return {
195
+ url,
196
+ alt: typeof record.alt === "string" ? record.alt : "",
197
+ primary: Boolean(record.primary),
198
+ };
199
+ })
200
+ .filter((entry) => entry !== null);
201
+ return media.length > 0 ? JSON.stringify(media) : null;
202
+ }
203
+ case "list": {
204
+ const items = Array.isArray(value) ? value : [];
205
+ const entries = items
206
+ .map((entry) => String(entry).trim())
207
+ .filter(Boolean);
208
+ return entries.length > 0 ? JSON.stringify(entries) : null;
209
+ }
210
+ default:
211
+ return String(value);
212
+ }
213
+ }
214
+ function parseMediaList(raw) {
215
+ if (typeof raw !== "string" || !raw.trim())
216
+ return [];
217
+ try {
218
+ const parsed = JSON.parse(raw);
219
+ if (!Array.isArray(parsed))
220
+ return [];
221
+ return parsed
222
+ .map((entry) => {
223
+ if (!entry || typeof entry !== "object")
224
+ return null;
225
+ const url = String(entry.url ?? "").trim();
226
+ if (!url)
227
+ return null;
228
+ const alt = entry.alt;
229
+ return {
230
+ url,
231
+ alt: typeof alt === "string" ? alt : "",
232
+ primary: Boolean(entry.primary),
233
+ };
234
+ })
235
+ .filter((entry) => entry !== null);
236
+ }
237
+ catch {
238
+ return [];
239
+ }
240
+ }
241
+ function parseStringList(raw) {
242
+ if (typeof raw !== "string" || !raw.trim())
243
+ return [];
244
+ try {
245
+ const parsed = JSON.parse(raw);
246
+ if (!Array.isArray(parsed))
247
+ return [];
248
+ return parsed.map((entry) => String(entry)).filter((entry) => entry !== "");
249
+ }
250
+ catch {
251
+ return [];
252
+ }
253
+ }
254
+ /** Decode a single raw column value into a field value. */
255
+ function decodeFieldValue(field, raw) {
256
+ switch (field.type) {
257
+ case "boolean":
258
+ return raw === 1 || raw === 1n || raw === true;
259
+ case "number":
260
+ return raw === null || raw === undefined ? null : Number(raw);
261
+ case "relation":
262
+ return isManyRelation(field)
263
+ ? []
264
+ : raw === null || raw === undefined
265
+ ? null
266
+ : Number(raw);
267
+ case "media-list":
268
+ return parseMediaList(raw);
269
+ case "list":
270
+ return parseStringList(raw);
271
+ default:
272
+ return raw === null || raw === undefined ? "" : String(raw);
273
+ }
274
+ }
275
+ function rowToItem(collection, row) {
276
+ const item = {
277
+ id: Number(row.id),
278
+ createdAt: String(row.created_at ?? ""),
279
+ updatedAt: String(row.updated_at ?? ""),
280
+ };
281
+ for (const field of collection.fields) {
282
+ if (isManyRelation(field))
283
+ continue;
284
+ if (isLocalizedField(collection, field)) {
285
+ const value = {};
286
+ for (const locale of collectionLocales(collection)) {
287
+ value[locale] = decodeFieldValue(field, row[`${field.name}_${locale}`]);
288
+ }
289
+ item[field.name] = value;
290
+ }
291
+ else {
292
+ item[field.name] = decodeFieldValue(field, row[field.name]);
293
+ }
294
+ }
295
+ return item;
296
+ }
297
+ /** Batch-load `to-many` relation ids for the given items. */
298
+ function hydrateManyRelations(db, collection, items) {
299
+ if (items.length === 0)
300
+ return;
301
+ const byId = new Map(items.map((item) => [item.id, item]));
302
+ const ids = items.map((item) => item.id);
303
+ const placeholders = ids.map(() => "?").join(", ");
304
+ for (const field of collection.fields) {
305
+ if (!isManyRelation(field))
306
+ continue;
307
+ const rows = db
308
+ .prepare(`SELECT source_id, target_id FROM ${joinTable(collection, field)} WHERE source_id IN (${placeholders}) ORDER BY position`)
309
+ .all(...ids);
310
+ for (const row of rows) {
311
+ const item = byId.get(Number(row.source_id));
312
+ const current = (item?.[field.name] ?? []);
313
+ current.push(Number(row.target_id));
314
+ if (item)
315
+ item[field.name] = current;
316
+ }
317
+ }
318
+ }
319
+ export function listItems(collection, { page = 1, limit = 10, q = "", } = {}) {
320
+ const db = getDb();
321
+ const table = tableName(collection.slug);
322
+ const safeLimit = Math.min(Math.max(1, Math.floor(limit)), 100);
323
+ const params = [];
324
+ let where = "";
325
+ const search = q.trim();
326
+ if (search) {
327
+ const searchColumns = storedColumns(collection).filter((entry) => ["text", "email", "textarea", "select", "date"].includes(entry.field.type));
328
+ if (searchColumns.length > 0) {
329
+ where =
330
+ " WHERE " +
331
+ searchColumns.map((entry) => `${quote(entry.column)} LIKE ?`).join(" OR ");
332
+ for (let i = 0; i < searchColumns.length; i += 1) {
333
+ params.push(`%${search}%`);
334
+ }
335
+ }
336
+ }
337
+ const countRow = db
338
+ .prepare(`SELECT COUNT(*) AS count FROM ${table}${where}`)
339
+ .get(...params);
340
+ const total = Number(countRow?.count ?? 0);
341
+ const totalPages = Math.max(1, Math.ceil(total / safeLimit));
342
+ const safePage = Math.min(Math.max(1, Math.floor(page)), totalPages);
343
+ const offset = (safePage - 1) * safeLimit;
344
+ const rows = db
345
+ .prepare(`SELECT * FROM ${table}${where} ORDER BY id DESC LIMIT ? OFFSET ?`)
346
+ .all(...params, safeLimit, offset);
347
+ const items = rows.map((row) => rowToItem(collection, row));
348
+ hydrateManyRelations(db, collection, items);
349
+ return {
350
+ items,
351
+ total,
352
+ page: safePage,
353
+ limit: safeLimit,
354
+ totalPages,
355
+ };
356
+ }
357
+ export function getItem(collection, id) {
358
+ const db = getDb();
359
+ const row = db
360
+ .prepare(`SELECT * FROM ${tableName(collection.slug)} WHERE id = ?`)
361
+ .get(id);
362
+ if (!row)
363
+ return null;
364
+ const item = rowToItem(collection, row);
365
+ hydrateManyRelations(db, collection, [item]);
366
+ return item;
367
+ }
368
+ function saveManyRelations(db, collection, id, values) {
369
+ for (const field of collection.fields) {
370
+ if (!isManyRelation(field))
371
+ continue;
372
+ if (!Object.prototype.hasOwnProperty.call(values, field.name))
373
+ continue;
374
+ const join = joinTable(collection, field);
375
+ db.prepare(`DELETE FROM ${join} WHERE source_id = ?`).run(id);
376
+ const raw = values[field.name];
377
+ const ids = Array.isArray(raw) ? raw : [];
378
+ const insert = db.prepare(`INSERT INTO ${join} (source_id, target_id, position) VALUES (?, ?, ?)`);
379
+ ids.forEach((targetId, position) => {
380
+ insert.run(id, Number(targetId), position);
381
+ });
382
+ }
383
+ }
384
+ /** Throw-free check that every referenced id actually exists. */
385
+ export function checkRelationTargets(collection, values) {
386
+ const db = getDb();
387
+ const errors = {};
388
+ for (const field of collection.fields) {
389
+ if (field.type !== "relation" || !field.relation)
390
+ continue;
391
+ if (!Object.prototype.hasOwnProperty.call(values, field.name))
392
+ continue;
393
+ const target = getCollections().find((entry) => entry.slug === field.relation?.to);
394
+ if (!target) {
395
+ errors[field.name] = "Coleção de destino inexistente.";
396
+ continue;
397
+ }
398
+ const statement = db.prepare(`SELECT 1 AS ok FROM ${tableName(target.slug)} WHERE id = ?`);
399
+ const exists = (id) => Boolean(statement.get(id));
400
+ const raw = values[field.name];
401
+ const ids = Array.isArray(raw) ? raw.map(Number) : [Number(raw)];
402
+ if (raw !== null &&
403
+ raw !== undefined &&
404
+ ids.some((id) => !Number.isInteger(id) || !exists(id))) {
405
+ errors[field.name] = "Item relacionado inexistente.";
406
+ }
407
+ }
408
+ return errors;
409
+ }
410
+ /** Read the value destined for a physical column from a nested values map. */
411
+ function columnValue(column, values) {
412
+ if (column.locale === null)
413
+ return values[column.field.name] ?? null;
414
+ const raw = values[column.field.name];
415
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
416
+ return null;
417
+ return raw[column.locale] ?? null;
418
+ }
419
+ /** Whether a partial update actually carries this column's value. */
420
+ function columnProvided(column, values) {
421
+ if (!Object.prototype.hasOwnProperty.call(values, column.field.name)) {
422
+ return false;
423
+ }
424
+ if (column.locale === null)
425
+ return true;
426
+ const raw = values[column.field.name];
427
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
428
+ return false;
429
+ return Object.prototype.hasOwnProperty.call(raw, column.locale);
430
+ }
431
+ export function createItem(collection, values) {
432
+ const db = getDb();
433
+ const table = tableName(collection.slug);
434
+ const columns = storedColumns(collection);
435
+ const names = columns.map((entry) => quote(entry.column)).join(", ");
436
+ const placeholders = columns.map(() => "?").join(", ");
437
+ const params = columns.map((entry) => serialize(entry.field, columnValue(entry, values)));
438
+ const result = db
439
+ .prepare(`INSERT INTO ${table} (created_at, updated_at${names ? `, ${names}` : ""}) VALUES (datetime('now'), datetime('now')${placeholders ? `, ${placeholders}` : ""})`)
440
+ .run(...params);
441
+ const id = Number(result.lastInsertRowid);
442
+ saveManyRelations(db, collection, id, values);
443
+ const item = getItem(collection, id);
444
+ if (!item)
445
+ throw new Error("Falha ao ler o item recém-criado.");
446
+ return item;
447
+ }
448
+ export function updateItem(collection, id, values) {
449
+ const db = getDb();
450
+ const columns = storedColumns(collection).filter((entry) => columnProvided(entry, values));
451
+ if (columns.length > 0) {
452
+ const assignments = columns
453
+ .map((entry) => `${quote(entry.column)} = ?`)
454
+ .join(", ");
455
+ const params = columns.map((entry) => serialize(entry.field, columnValue(entry, values)));
456
+ db.prepare(`UPDATE ${tableName(collection.slug)} SET ${assignments}, updated_at = datetime('now') WHERE id = ?`).run(...params, id);
457
+ }
458
+ saveManyRelations(db, collection, id, values);
459
+ return getItem(collection, id);
460
+ }
461
+ /** The single row id of a standalone collection, or null when empty. */
462
+ function standaloneRowId(db, collection) {
463
+ const row = db
464
+ .prepare(`SELECT id FROM ${tableName(collection.slug)} ORDER BY id LIMIT 1`)
465
+ .get();
466
+ return row ? Number(row.id) : null;
467
+ }
468
+ /**
469
+ * Read the single record of a standalone collection, creating it with its
470
+ * field defaults on first access.
471
+ */
472
+ export function getStandalone(collection) {
473
+ const db = getDb();
474
+ const existing = standaloneRowId(db, collection);
475
+ if (existing !== null) {
476
+ const item = getItem(collection, existing);
477
+ if (item)
478
+ return item;
479
+ }
480
+ return createItem(collection, emptyValues(collection));
481
+ }
482
+ /**
483
+ * Upsert the single record of a standalone collection. Values are merged over
484
+ * the field defaults so a fresh record is always fully populated.
485
+ */
486
+ export function saveStandalone(collection, values) {
487
+ const db = getDb();
488
+ const existing = standaloneRowId(db, collection);
489
+ if (existing === null) {
490
+ return createItem(collection, { ...emptyValues(collection), ...values });
491
+ }
492
+ const item = updateItem(collection, existing, values);
493
+ if (!item)
494
+ throw new Error("Falha ao atualizar o registro standalone.");
495
+ return item;
496
+ }
497
+ /** Remove any reference to `targetId` of `target` from every collection. */
498
+ function cascadeDeleteReferences(db, target, targetId) {
499
+ for (const collection of getCollections()) {
500
+ for (const field of collection.fields) {
501
+ if (field.type !== "relation")
502
+ continue;
503
+ if (field.relation?.to !== target.slug)
504
+ continue;
505
+ if (isManyRelation(field)) {
506
+ db.prepare(`DELETE FROM ${joinTable(collection, field)} WHERE target_id = ?`).run(targetId);
507
+ }
508
+ else {
509
+ db.prepare(`UPDATE ${tableName(collection.slug)} SET ${quote(field.name)} = NULL WHERE ${quote(field.name)} = ?`).run(targetId);
510
+ }
511
+ }
512
+ }
513
+ }
514
+ export function deleteItem(collection, id) {
515
+ const db = getDb();
516
+ const result = db
517
+ .prepare(`DELETE FROM ${tableName(collection.slug)} WHERE id = ?`)
518
+ .run(id);
519
+ for (const field of collection.fields) {
520
+ if (!isManyRelation(field))
521
+ continue;
522
+ db.prepare(`DELETE FROM ${joinTable(collection, field)} WHERE source_id = ?`).run(id);
523
+ }
524
+ cascadeDeleteReferences(db, collection, id);
525
+ return Number(result.changes) > 0;
526
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Isomorphic media helpers (no filesystem): type allowlisting and URL checks.
3
+ * Server disk I/O lives in `media.server.ts`.
4
+ */
5
+ import type { FieldDef } from "./types.js";
6
+ export declare const UPLOAD_URL_PREFIX = "/files/";
7
+ export declare const DEFAULT_MAX_SIZE: number;
8
+ /** Default accepted types when a media field omits `accept`. */
9
+ export declare const DEFAULT_ACCEPT: string[];
10
+ /** Extensions that are never accepted, even if listed in `accept`. */
11
+ export declare const BLOCKED_EXTENSIONS: Set<string>;
12
+ export declare function extensionOf(filename: string): string;
13
+ /**
14
+ * Accepts a stored media URL: uploaded files (`/files/...`) or committed
15
+ * portfolio assets (`/images/...`). Rejects traversal and external values.
16
+ */
17
+ export declare function isMediaUrl(value: string): boolean;
18
+ export declare function isImageUrl(url: string): boolean;
19
+ export declare function acceptList(field: FieldDef): string[];
20
+ export declare function isAllowedType(field: FieldDef, filename: string, mime: string): boolean;
21
+ /** `accept` attribute string for the file input (best-effort). */
22
+ export declare function acceptAttribute(field: FieldDef): string;
@@ -0,0 +1,76 @@
1
+ export const UPLOAD_URL_PREFIX = "/files/";
2
+ export const DEFAULT_MAX_SIZE = 10 * 1024 * 1024;
3
+ /** Default accepted types when a media field omits `accept`. */
4
+ export const DEFAULT_ACCEPT = ["image/*", "application/pdf"];
5
+ /** Extensions that are never accepted, even if listed in `accept`. */
6
+ export const BLOCKED_EXTENSIONS = new Set([
7
+ "html",
8
+ "htm",
9
+ "xhtml",
10
+ "js",
11
+ "mjs",
12
+ "cjs",
13
+ "php",
14
+ "phtml",
15
+ "exe",
16
+ "sh",
17
+ "bat",
18
+ "cmd",
19
+ "com",
20
+ "jsx",
21
+ "ts",
22
+ "tsx",
23
+ ]);
24
+ const IMAGE_EXTENSIONS = new Set([
25
+ "png",
26
+ "jpg",
27
+ "jpeg",
28
+ "gif",
29
+ "webp",
30
+ "avif",
31
+ "svg",
32
+ "ico",
33
+ ]);
34
+ export function extensionOf(filename) {
35
+ const match = /\.([a-zA-Z0-9]+)$/.exec(filename);
36
+ return match ? match[1].toLowerCase() : "";
37
+ }
38
+ /**
39
+ * Accepts a stored media URL: uploaded files (`/files/...`) or committed
40
+ * portfolio assets (`/images/...`). Rejects traversal and external values.
41
+ */
42
+ export function isMediaUrl(value) {
43
+ if (!value || value.includes(".."))
44
+ return false;
45
+ return value.startsWith(UPLOAD_URL_PREFIX) || value.startsWith("/images/");
46
+ }
47
+ export function isImageUrl(url) {
48
+ return IMAGE_EXTENSIONS.has(extensionOf(url));
49
+ }
50
+ export function acceptList(field) {
51
+ return field.accept && field.accept.length > 0 ? field.accept : DEFAULT_ACCEPT;
52
+ }
53
+ function matches(pattern, ext, mime) {
54
+ const p = pattern.trim().toLowerCase();
55
+ if (!p)
56
+ return false;
57
+ if (p.startsWith("."))
58
+ return ext === p.slice(1);
59
+ if (p.includes("/")) {
60
+ if (p.endsWith("/*"))
61
+ return mime.startsWith(p.slice(0, -1));
62
+ return mime === p;
63
+ }
64
+ return ext === p;
65
+ }
66
+ export function isAllowedType(field, filename, mime) {
67
+ const ext = extensionOf(filename);
68
+ if (!ext || BLOCKED_EXTENSIONS.has(ext))
69
+ return false;
70
+ const type = mime.toLowerCase();
71
+ return acceptList(field).some((pattern) => matches(pattern, ext, type));
72
+ }
73
+ /** `accept` attribute string for the file input (best-effort). */
74
+ export function acceptAttribute(field) {
75
+ return acceptList(field).join(",");
76
+ }
@@ -0,0 +1,18 @@
1
+ import type { FieldDef } from "./types.js";
2
+ export declare const UPLOADS_DIR: string;
3
+ export declare class MediaError extends Error {
4
+ status: number;
5
+ constructor(message: string, status?: number);
6
+ }
7
+ export declare function contentTypeFor(name: string): string;
8
+ export type StoredUpload = {
9
+ url: string;
10
+ name: string;
11
+ size: number;
12
+ type: string;
13
+ };
14
+ export declare function saveUpload(file: File, field: FieldDef): Promise<StoredUpload>;
15
+ /** Resolve a stored name to a safe path inside `UPLOADS_DIR`, or null. */
16
+ export declare function resolveUploadPath(name: string): string | null;
17
+ export declare function readUpload(name: string): Buffer | null;
18
+ export declare function deleteByUrl(url: string): boolean;