@thebes/cadmus 0.2.1 → 0.4.0

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 (49) hide show
  1. package/dist/cms/index.cjs +689 -3
  2. package/dist/cms/index.cjs.map +1 -1
  3. package/dist/cms/index.d.cts +2 -2
  4. package/dist/cms/index.d.ts +2 -2
  5. package/dist/cms/index.js +671 -5
  6. package/dist/cms/index.js.map +1 -1
  7. package/dist/email/index.cjs +1 -1
  8. package/dist/email/index.js +1 -1
  9. package/dist/{errors-CW6Lz0AQ.cjs → errors-BhoibM6Z.cjs} +24 -1
  10. package/dist/{errors-CW6Lz0AQ.cjs.map → errors-BhoibM6Z.cjs.map} +1 -1
  11. package/dist/{errors-mZIqZJO4.js → errors-C8SqkFjl.js} +19 -2
  12. package/dist/{errors-mZIqZJO4.js.map → errors-C8SqkFjl.js.map} +1 -1
  13. package/dist/hono/index.cjs +6 -1
  14. package/dist/hono/index.cjs.map +1 -1
  15. package/dist/hono/index.d.cts +1 -1
  16. package/dist/hono/index.d.cts.map +1 -1
  17. package/dist/hono/index.d.ts +1 -1
  18. package/dist/hono/index.d.ts.map +1 -1
  19. package/dist/hono/index.js +6 -1
  20. package/dist/hono/index.js.map +1 -1
  21. package/dist/index-sB3YOadC.d.cts +1304 -0
  22. package/dist/index-sB3YOadC.d.cts.map +1 -0
  23. package/dist/index-sB3YOadC.d.ts +1304 -0
  24. package/dist/index-sB3YOadC.d.ts.map +1 -0
  25. package/dist/index.cjs +22 -1
  26. package/dist/index.d.cts +3 -89
  27. package/dist/index.d.cts.map +1 -1
  28. package/dist/index.d.ts +3 -89
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +3 -3
  31. package/dist/queues/index.cjs +1 -1
  32. package/dist/queues/index.js +1 -1
  33. package/dist/rate-limit/index.cjs +1 -1
  34. package/dist/rate-limit/index.js +1 -1
  35. package/dist/session/index.cjs +1 -1
  36. package/dist/session/index.js +1 -1
  37. package/dist/storage/index.cjs +1 -1
  38. package/dist/storage/index.cjs.map +1 -1
  39. package/dist/storage/index.d.cts +31 -2
  40. package/dist/storage/index.d.cts.map +1 -1
  41. package/dist/storage/index.d.ts +31 -2
  42. package/dist/storage/index.d.ts.map +1 -1
  43. package/dist/storage/index.js +1 -1
  44. package/dist/storage/index.js.map +1 -1
  45. package/package.json +1 -1
  46. package/dist/index-BUrCSGVb.d.cts +0 -616
  47. package/dist/index-BUrCSGVb.d.cts.map +0 -1
  48. package/dist/index-BUrCSGVb.d.ts +0 -616
  49. package/dist/index-BUrCSGVb.d.ts.map +0 -1
package/dist/cms/index.js CHANGED
@@ -1,7 +1,64 @@
1
- import { a as CadmusCmsError, l as CadmusQueueError, t as CadmusAccessDeniedError } from "../errors-mZIqZJO4.js";
1
+ import { a as CadmusCmsError, l as CadmusQueueError, p as CadmusValidationError, t as CadmusAccessDeniedError } from "../errors-C8SqkFjl.js";
2
2
  import { enqueue } from "../queues/index.js";
3
3
  import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
4
- import { count, desc, eq, inArray, sql } from "drizzle-orm";
4
+ import { and, count, desc, eq, inArray, ne, sql } from "drizzle-orm";
5
+ //#region src/cms/blocks.ts
6
+ /**
7
+ * Create a block renderer registry. Seed it with an initial `type → renderer`
8
+ * map and/or an `options.fallback` for unknown types.
9
+ *
10
+ * ```ts
11
+ * const registry = createBlockRegistry<StringBlockRenderer>({
12
+ * divider: () => "<hr>",
13
+ * });
14
+ * registry.register("hero", (b) => `<h1>${b.heading}</h1>`);
15
+ * renderBlocksToString(blocks, registry);
16
+ * ```
17
+ */
18
+ function createBlockRegistry(initial = {}, options = {}) {
19
+ const renderers = new Map(Object.entries(initial));
20
+ let fallback = options.fallback;
21
+ const registry = {
22
+ register(type, renderer) {
23
+ renderers.set(type, renderer);
24
+ return registry;
25
+ },
26
+ registerMany(map) {
27
+ for (const [type, renderer] of Object.entries(map)) renderers.set(type, renderer);
28
+ return registry;
29
+ },
30
+ get(type) {
31
+ return renderers.get(type);
32
+ },
33
+ has(type) {
34
+ return renderers.has(type);
35
+ },
36
+ types() {
37
+ return [...renderers.keys()];
38
+ },
39
+ setFallback(renderer) {
40
+ fallback = renderer;
41
+ return registry;
42
+ },
43
+ resolve(type) {
44
+ return renderers.get(type) ?? fallback;
45
+ }
46
+ };
47
+ return registry;
48
+ }
49
+ /**
50
+ * Render an array of blocks to a single HTML string via a registry of
51
+ * {@link StringBlockRenderer}s. Blocks whose type resolves to no renderer
52
+ * (and no fallback) contribute the empty string — the same forgiving
53
+ * behavior the old hand-rolled `switch` had for unknown types.
54
+ */
55
+ function renderBlocksToString(blocks, registry) {
56
+ return blocks.map((block) => {
57
+ const renderer = registry.resolve(block.type);
58
+ return renderer ? renderer(block) : "";
59
+ }).join("");
60
+ }
61
+ //#endregion
5
62
  //#region src/cms/types.ts
6
63
  /**
7
64
  * Expands every `group` field in `fields` into its flattened equivalents
@@ -249,6 +306,366 @@ function defineCmsConfig(config) {
249
306
  return resolved;
250
307
  }
251
308
  //#endregion
309
+ //#region src/cms/patch.ts
310
+ function deepEqual(a, b) {
311
+ if (a === b) return true;
312
+ if (a === null || b === null) return false;
313
+ if (typeof a !== typeof b) return false;
314
+ if (Array.isArray(a) || Array.isArray(b)) {
315
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
316
+ if (a.length !== b.length) return false;
317
+ return a.every((item, i) => deepEqual(item, b[i]));
318
+ }
319
+ if (typeof a === "object" && typeof b === "object") {
320
+ const ak = Object.keys(a);
321
+ const bk = Object.keys(b);
322
+ if (ak.length !== bk.length) return false;
323
+ return ak.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]));
324
+ }
325
+ return false;
326
+ }
327
+ /**
328
+ * Field-level diff between two document snapshots — the per-field
329
+ * added/removed/changed list a version-history UI renders. Values are
330
+ * compared structurally (deep-equal), so a field only shows as `changed`
331
+ * when its content actually differs.
332
+ */
333
+ function diffDocuments(before, after, options = {}) {
334
+ const ignore = new Set(options.ignore ?? []);
335
+ const keys = options.fields ? options.fields : [...new Set([...Object.keys(before), ...Object.keys(after)])];
336
+ const changes = [];
337
+ for (const path of keys) {
338
+ if (ignore.has(path)) continue;
339
+ const inBefore = Object.hasOwn(before, path);
340
+ const inAfter = Object.hasOwn(after, path);
341
+ if (inBefore && !inAfter) changes.push({
342
+ path,
343
+ kind: "removed",
344
+ before: before[path]
345
+ });
346
+ else if (!inBefore && inAfter) changes.push({
347
+ path,
348
+ kind: "added",
349
+ after: after[path]
350
+ });
351
+ else if (inBefore && inAfter && !deepEqual(before[path], after[path])) changes.push({
352
+ path,
353
+ kind: "changed",
354
+ before: before[path],
355
+ after: after[path]
356
+ });
357
+ }
358
+ return changes;
359
+ }
360
+ /**
361
+ * The {@link Patch} that transforms `before` into `after`: `set` for each
362
+ * added/changed field, `unset` for each removed field. `applyPatch(before,
363
+ * computePatch(before, after))` deep-equals `after`.
364
+ */
365
+ function computePatch(before, after) {
366
+ return diffDocuments(before, after).map((change) => change.kind === "removed" ? {
367
+ op: "unset",
368
+ path: change.path
369
+ } : {
370
+ op: "set",
371
+ path: change.path,
372
+ value: change.after
373
+ });
374
+ }
375
+ /**
376
+ * Apply a {@link Patch} to a document, returning a new document (the input is
377
+ * never mutated). Unknown ops are ignored defensively.
378
+ */
379
+ function applyPatch(doc, patch) {
380
+ const next = { ...doc };
381
+ for (const op of patch) if (op.op === "set") next[op.path] = op.value;
382
+ else if (op.op === "unset") delete next[op.path];
383
+ return next;
384
+ }
385
+ //#endregion
386
+ //#region src/cms/validation.ts
387
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
388
+ const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
389
+ /**
390
+ * Immutable, chainable rule builder — the value a field's `validation`
391
+ * function receives and returns. Build a `Rule` with the module-level
392
+ * {@link rule} factory, or accept the one passed to your `validation`
393
+ * callback.
394
+ */
395
+ var Rule = class Rule {
396
+ checks;
397
+ constructor(checks = []) {
398
+ this.checks = checks;
399
+ }
400
+ add(check) {
401
+ return new Rule([...this.checks, check]);
402
+ }
403
+ /** Override the message of the most recently added check. */
404
+ error(message) {
405
+ return this.withLast({
406
+ message,
407
+ severity: "error"
408
+ });
409
+ }
410
+ /**
411
+ * Demote the most recently added check to a warning (non-blocking),
412
+ * optionally with a message. Sanity's `Rule.warning()` analogue.
413
+ */
414
+ warning(message) {
415
+ return this.withLast({
416
+ severity: "warning",
417
+ ...message ? { message } : {}
418
+ });
419
+ }
420
+ withLast(patch) {
421
+ if (this.checks.length === 0) return this;
422
+ const next = this.checks.slice();
423
+ next[next.length - 1] = {
424
+ ...next[next.length - 1],
425
+ ...patch
426
+ };
427
+ return new Rule(next);
428
+ }
429
+ required() {
430
+ return this.add({ kind: "required" });
431
+ }
432
+ /** Minimum string length / array length / numeric value. */
433
+ min(n) {
434
+ return this.add({
435
+ kind: "min",
436
+ n
437
+ });
438
+ }
439
+ /** Maximum string length / array length / numeric value. */
440
+ max(n) {
441
+ return this.add({
442
+ kind: "max",
443
+ n
444
+ });
445
+ }
446
+ /** Exact string/array length. */
447
+ length(n) {
448
+ return this.add({
449
+ kind: "length",
450
+ n
451
+ });
452
+ }
453
+ regex(re, label = "match the required format") {
454
+ return this.add({
455
+ kind: "regex",
456
+ re,
457
+ label
458
+ });
459
+ }
460
+ email() {
461
+ return this.add({
462
+ kind: "regex",
463
+ re: EMAIL_RE,
464
+ label: "be a valid email"
465
+ });
466
+ }
467
+ /** Lowercase kebab-case slug format. Pair with `.unique()` for slugs. */
468
+ slug() {
469
+ return this.add({
470
+ kind: "regex",
471
+ re: SLUG_RE,
472
+ label: "be a lowercase, hyphen-separated slug"
473
+ });
474
+ }
475
+ integer() {
476
+ return this.add({ kind: "integer" });
477
+ }
478
+ positive() {
479
+ return this.add({ kind: "positive" });
480
+ }
481
+ /**
482
+ * Value must be unique across the collection (DB-backed; skipped in a
483
+ * pure client-side pass). A first-class rule rather than the hand-rolled
484
+ * column `unique` flag, so the failure is a clear field message instead of
485
+ * a raw UNIQUE-constraint write error.
486
+ */
487
+ unique() {
488
+ return this.add({ kind: "unique" });
489
+ }
490
+ /**
491
+ * For a `relationship` field: the referenced id must exist in the related
492
+ * collection (DB-backed; skipped client-side).
493
+ */
494
+ reference() {
495
+ return this.add({ kind: "reference" });
496
+ }
497
+ custom(fn) {
498
+ return this.add({
499
+ kind: "custom",
500
+ fn
501
+ });
502
+ }
503
+ /** Internal: the accumulated checks, read by {@link validateDocument}. */
504
+ toChecks() {
505
+ return this.checks;
506
+ }
507
+ };
508
+ /** Fresh, empty rule — the root of a chain. */
509
+ function rule() {
510
+ return new Rule();
511
+ }
512
+ /**
513
+ * Identity helper mirroring Sanity's `defineField` — returns the field
514
+ * config unchanged but gives editors autocomplete and a single, greppable
515
+ * call site for field definitions. Optional: a plain object literal is still
516
+ * a valid field.
517
+ */
518
+ function defineField(field) {
519
+ return field;
520
+ }
521
+ function resolveChecks(field) {
522
+ if (!field.validation) return [];
523
+ const built = field.validation(new Rule());
524
+ return (Array.isArray(built) ? built : [built]).flatMap((r) => r.toChecks());
525
+ }
526
+ function isEmpty(value) {
527
+ return value === void 0 || value === null || typeof value === "string" && value.length === 0;
528
+ }
529
+ function sizeOf(value) {
530
+ if (typeof value === "string") return {
531
+ size: value.length,
532
+ unit: "character"
533
+ };
534
+ if (Array.isArray(value)) return {
535
+ size: value.length,
536
+ unit: "item"
537
+ };
538
+ if (typeof value === "number") return {
539
+ size: value,
540
+ unit: ""
541
+ };
542
+ return null;
543
+ }
544
+ /**
545
+ * Evaluate every field's validation rules against `doc`, returning all
546
+ * violations (both errors and warnings). `doc` is the nested document; field
547
+ * values are read from its flattened form so group subfields validate too.
548
+ */
549
+ async function validateDocument(config, doc, options) {
550
+ const flatFields = flattenFields(config.fields);
551
+ const flatDoc = flattenDocShallow(config, doc);
552
+ const violations = [];
553
+ for (const [path, field] of Object.entries(flatFields)) {
554
+ if (options.onlyFields && !options.onlyFields.has(path)) continue;
555
+ const checks = resolveChecks(field);
556
+ if (checks.length === 0) continue;
557
+ const value = flatDoc[path];
558
+ const ctx = {
559
+ document: doc,
560
+ path,
561
+ operation: options.operation,
562
+ ...options.id !== void 0 ? { id: options.id } : {}
563
+ };
564
+ for (const check of checks) {
565
+ const violation = await evaluateCheck(check, value, field, ctx, options);
566
+ if (violation) violations.push(violation);
567
+ }
568
+ }
569
+ return violations;
570
+ }
571
+ function flattenDocShallow(config, doc) {
572
+ return Object.values(config.fields).some((f) => f.type === "group") ? flattenDoc(config.fields, doc) : doc;
573
+ }
574
+ async function evaluateCheck(check, value, field, ctx, options) {
575
+ const fail = (defaultMessage) => ({
576
+ path: ctx.path,
577
+ message: check.message ?? `${ctx.path} must ${defaultMessage}`,
578
+ severity: check.severity ?? "error"
579
+ });
580
+ switch (check.kind) {
581
+ case "required": return isEmpty(value) ? fail("not be empty") : null;
582
+ case "min": {
583
+ if (isEmpty(value)) return null;
584
+ const s = sizeOf(value);
585
+ if (s && s.size < check.n) return fail(s.unit ? `have at least ${check.n} ${s.unit}${check.n === 1 ? "" : "s"}` : `be at least ${check.n}`);
586
+ return null;
587
+ }
588
+ case "max": {
589
+ if (isEmpty(value)) return null;
590
+ const s = sizeOf(value);
591
+ if (s && s.size > check.n) return fail(s.unit ? `have at most ${check.n} ${s.unit}${check.n === 1 ? "" : "s"}` : `be at most ${check.n}`);
592
+ return null;
593
+ }
594
+ case "length": {
595
+ if (isEmpty(value)) return null;
596
+ const s = sizeOf(value);
597
+ if (s?.unit && s.size !== check.n) return fail(`be exactly ${check.n} ${s.unit}${check.n === 1 ? "" : "s"}`);
598
+ return null;
599
+ }
600
+ case "regex":
601
+ if (isEmpty(value)) return null;
602
+ if (typeof value !== "string" || !check.re.test(value)) return fail(check.label);
603
+ return null;
604
+ case "integer":
605
+ if (isEmpty(value)) return null;
606
+ return typeof value === "number" && Number.isInteger(value) ? null : fail("be an integer");
607
+ case "positive":
608
+ if (isEmpty(value)) return null;
609
+ return typeof value === "number" && value > 0 ? null : fail("be a positive number");
610
+ case "unique": return evaluateUnique(value, ctx, options, check);
611
+ case "reference": return evaluateReference(value, field, ctx, options, check);
612
+ case "custom": {
613
+ const result = await check.fn(value, ctx);
614
+ if (result === true || result === void 0) return null;
615
+ if (result === false) return fail("be valid");
616
+ if (typeof result === "string") return {
617
+ path: ctx.path,
618
+ message: result,
619
+ severity: check.severity ?? "error"
620
+ };
621
+ return {
622
+ path: ctx.path,
623
+ message: result.message,
624
+ severity: result.severity ?? check.severity ?? "error"
625
+ };
626
+ }
627
+ }
628
+ }
629
+ async function evaluateUnique(value, ctx, options, check) {
630
+ if (isEmpty(value) || !options.db || !options.table) return null;
631
+ const column = options.table[ctx.path];
632
+ if (!column) return null;
633
+ const where = ctx.id !== void 0 ? and(eq(column, value), ne(options.table.id, ctx.id)) : eq(column, value);
634
+ if ((await options.db.select({ id: options.table.id }).from(options.table).where(where).limit(1)).length > 0) return {
635
+ path: ctx.path,
636
+ message: check.message ?? `${ctx.path} "${String(value)}" is already taken`,
637
+ severity: check.severity ?? "error"
638
+ };
639
+ return null;
640
+ }
641
+ async function evaluateReference(value, field, ctx, options, check) {
642
+ if (isEmpty(value) || !options.db || !options.registry) return null;
643
+ if (field.type !== "relationship") return null;
644
+ const target = options.registry.tables[field.relationTo];
645
+ if (!target) return null;
646
+ if ((await options.db.select({ id: target.id }).from(target).where(eq(target.id, value)).limit(1)).length === 0) return {
647
+ path: ctx.path,
648
+ message: check.message ?? `${ctx.path} references a "${field.relationTo}" that does not exist`,
649
+ severity: check.severity ?? "error"
650
+ };
651
+ return null;
652
+ }
653
+ /**
654
+ * Run {@link validateDocument} and throw {@link CadmusValidationError} if any
655
+ * `"error"`-severity violations are found. Warnings are returned (never
656
+ * thrown) so a caller can still surface them. The thrown error's message is
657
+ * a readable, joined summary of every blocking violation.
658
+ */
659
+ async function assertValid(config, doc, options) {
660
+ const violations = await validateDocument(config, doc, options);
661
+ const errors = violations.filter((v) => v.severity === "error");
662
+ if (errors.length > 0) {
663
+ const summary = errors.map((v) => v.message).join("; ");
664
+ throw new CadmusValidationError(`Validation failed for collection "${config.slug}": ${summary}`, violations);
665
+ }
666
+ return violations;
667
+ }
668
+ //#endregion
252
669
  //#region src/cms/localApi.ts
253
670
  function validateRequiredFields(config, input) {
254
671
  for (const [key, field] of Object.entries(flattenFields(config.fields))) {
@@ -429,9 +846,16 @@ function createLocalApi(db, table, config, registry) {
429
846
  },
430
847
  async create(context, input) {
431
848
  await checkAccess(config, "create", context);
432
- const flatData = toFlatDoc(await runBeforeChange(config, input));
849
+ const data = await runBeforeChange(config, input);
850
+ const flatData = toFlatDoc(data);
433
851
  validateRequiredFields(config, flatData);
434
852
  rejectUnknownFields(config, flatData);
853
+ await assertValid(config, data, {
854
+ operation: "create",
855
+ db,
856
+ table,
857
+ registry
858
+ });
435
859
  let row;
436
860
  try {
437
861
  const [inserted] = await db.insert(table).values(flatData).returning();
@@ -446,8 +870,17 @@ function createLocalApi(db, table, config, registry) {
446
870
  },
447
871
  async update(context, id, input) {
448
872
  await checkAccess(config, "update", context);
449
- const flatData = toFlatDoc(await runBeforeChange(config, input));
873
+ const data = await runBeforeChange(config, input);
874
+ const flatData = toFlatDoc(data);
450
875
  rejectUnknownFields(config, flatData);
876
+ await assertValid(config, data, {
877
+ operation: "update",
878
+ id,
879
+ onlyFields: new Set(Object.keys(flatData)),
880
+ db,
881
+ table,
882
+ registry
883
+ });
451
884
  let row;
452
885
  try {
453
886
  const [updated] = await db.update(table).set(flatData).where(eq(idColumn, id)).returning();
@@ -510,6 +943,13 @@ function createVersionedLocalApi(db, table, versionsTable, config, registry) {
510
943
  validateRequiredFields(config, data);
511
944
  rejectUnknownFields(config, data);
512
945
  const parentId = versionRecord.parentId;
946
+ await assertValid(config, data, {
947
+ operation: "update",
948
+ id: parentId,
949
+ db,
950
+ table,
951
+ registry
952
+ });
513
953
  let doc;
514
954
  try {
515
955
  const [row] = await db.update(table).set({
@@ -531,6 +971,21 @@ function createVersionedLocalApi(db, table, versionsTable, config, registry) {
531
971
  const [row] = await db.update(table).set({ publishedVersionId: null }).where(eq(idColumn, id)).returning();
532
972
  if (!row) notFound(config, id);
533
973
  return row;
974
+ },
975
+ async diffVersions(context, fromVersionId, toVersionId) {
976
+ await checkAccess(config, "read", context);
977
+ const rows = await db.select().from(versionsTable).where(inArray(versionsIdColumn, [fromVersionId, toVersionId]));
978
+ const byId = new Map(rows.map((r) => [r.id, r.versionData]));
979
+ const before = byId.get(fromVersionId);
980
+ const after = byId.get(toVersionId);
981
+ if (!before) notFoundVersion(config, fromVersionId);
982
+ if (!after) notFoundVersion(config, toVersionId);
983
+ return diffDocuments(before, after, { ignore: [
984
+ "id",
985
+ "createdAt",
986
+ "status",
987
+ "publishedVersionId"
988
+ ] });
534
989
  }
535
990
  };
536
991
  }
@@ -544,6 +999,50 @@ function getCollectionsMeta(config) {
544
999
  }));
545
1000
  }
546
1001
  //#endregion
1002
+ //#region src/cms/migrate.ts
1003
+ /** Identity helper — gives a migration definition its type + a greppable call site. */
1004
+ function defineMigration(migration) {
1005
+ return migration;
1006
+ }
1007
+ function patchToUpdate(patch) {
1008
+ const values = {};
1009
+ for (const op of patch) values[op.path] = op.op === "set" ? op.value : null;
1010
+ return values;
1011
+ }
1012
+ /**
1013
+ * Run a migration over every document in a collection. Reads all documents
1014
+ * through `api.find`, applies `migration.document`, and (unless `dryRun`)
1015
+ * writes the resulting patch through `api.update`. Returns a report of what
1016
+ * changed — run it `dryRun` first, then apply.
1017
+ */
1018
+ async function runMigration(migration, options) {
1019
+ const { api, context, dryRun = false } = options;
1020
+ const rows = await api.find(context);
1021
+ const changes = [];
1022
+ const errors = [];
1023
+ let changed = 0;
1024
+ for (const before of rows) try {
1025
+ const patch = computePatch(before, await migration.document(before) ?? before);
1026
+ if (patch.length === 0) continue;
1027
+ changes.push({
1028
+ id: before.id,
1029
+ patch
1030
+ });
1031
+ changed++;
1032
+ if (!dryRun) await api.update(context, before.id, patchToUpdate(patch));
1033
+ } catch (err) {
1034
+ errors.push(`document ${before.id}: ${String(err)}`);
1035
+ }
1036
+ return {
1037
+ migration: migration.name,
1038
+ dryRun,
1039
+ scanned: rows.length,
1040
+ changed,
1041
+ changes,
1042
+ errors
1043
+ };
1044
+ }
1045
+ //#endregion
547
1046
  //#region src/cms/schema-gen.ts
548
1047
  function toSnakeCase(value) {
549
1048
  return value.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
@@ -659,6 +1158,173 @@ function generateSchemaSource(config) {
659
1158
  ].join("\n");
660
1159
  }
661
1160
  //#endregion
1161
+ //#region src/cms/structure.ts
1162
+ /**
1163
+ * Cadmea's Structure Builder — the framework half of issue #12.
1164
+ *
1165
+ * Adopts Sanity's `sanity/structure` idea (pattern, not code): **decouple
1166
+ * the admin nav from the raw collection list.** Instead of mapping every
1167
+ * `config.collections` entry to an `/admin/<slug>` link — which surfaces
1168
+ * system/log tables as editable links and produces dead links — the sidebar
1169
+ * renders from an explicit, grouped structure derived here from each
1170
+ * collection's `admin` hints (see {@link CollectionAdminConfig}) plus
1171
+ * optional per-slug overrides supplied at the call site.
1172
+ *
1173
+ * Pure data in / pure data out: no SolidJS, no DOM, no server imports — so
1174
+ * it's safe to import from a client studio component (e.g. the site's
1175
+ * `PanelNav`) and trivially testable.
1176
+ */
1177
+ /** Default group heading for collections that don't declare `admin.group`. */
1178
+ const DEFAULT_STUDIO_GROUP = "Content";
1179
+ function capitalize(value) {
1180
+ return value.length === 0 ? value : value[0].toUpperCase() + value.slice(1);
1181
+ }
1182
+ function resolveAdmin(collection, overrides) {
1183
+ return {
1184
+ ...collection.admin,
1185
+ ...overrides?.[collection.slug]
1186
+ };
1187
+ }
1188
+ /**
1189
+ * Build the studio sidebar structure from a resolved CMS config.
1190
+ *
1191
+ * - Hidden collections (`admin.hidden`) are dropped entirely.
1192
+ * - Each remaining collection is placed in its `admin.group` (or
1193
+ * {@link DEFAULT_STUDIO_GROUP}).
1194
+ * - Within a group, items sort by `admin.order` (ascending; unset sorts
1195
+ * after set), then by their original position in `config.collections` —
1196
+ * so config order is the stable tiebreaker.
1197
+ * - Groups render in `options.groupOrder` first, then first-appearance
1198
+ * order for the rest.
1199
+ *
1200
+ * The input is expected to be the *resolved* config (post-plugins), since
1201
+ * that's what carries plugin-injected collections like `products`.
1202
+ */
1203
+ function buildStudioStructure(config, options = {}) {
1204
+ const basePath = options.basePath ?? "/admin";
1205
+ const groupOrder = options.groupOrder ?? [];
1206
+ const ranked = config.collections.map((collection, index) => ({
1207
+ collection,
1208
+ index,
1209
+ admin: resolveAdmin(collection, options.overrides)
1210
+ }));
1211
+ const groups = /* @__PURE__ */ new Map();
1212
+ const appearance = [];
1213
+ for (const { collection, admin } of ranked) {
1214
+ if (admin.hidden) continue;
1215
+ const title = admin.group ?? "Content";
1216
+ if (!groups.has(title)) {
1217
+ groups.set(title, []);
1218
+ appearance.push(title);
1219
+ }
1220
+ groups.get(title).push({
1221
+ slug: collection.slug,
1222
+ label: admin.label ?? capitalize(collection.slug),
1223
+ href: `${basePath}/${collection.slug}`,
1224
+ readOnly: admin.readOnly ?? false,
1225
+ singleton: admin.singleton ?? false,
1226
+ ...admin.icon ? { icon: admin.icon } : {}
1227
+ });
1228
+ }
1229
+ const meta = new Map(ranked.map(({ collection, index, admin }) => [collection.slug, {
1230
+ order: admin.order ?? Number.POSITIVE_INFINITY,
1231
+ index
1232
+ }]));
1233
+ for (const items of groups.values()) items.sort((a, b) => {
1234
+ const ma = meta.get(a.slug);
1235
+ const mb = meta.get(b.slug);
1236
+ return ma.order - mb.order || ma.index - mb.index;
1237
+ });
1238
+ return [...groupOrder.filter((title) => groups.has(title)), ...appearance.filter((title) => !groupOrder.includes(title))].map((title) => ({
1239
+ title,
1240
+ items: groups.get(title)
1241
+ }));
1242
+ }
1243
+ //#endregion
1244
+ //#region src/cms/visual-editing.ts
1245
+ /** The data attribute editable regions are tagged with. */
1246
+ const EDIT_ATTR = "data-cadmus-edit";
1247
+ /** `postMessage` payload type for a click-to-edit selection. */
1248
+ const VISUAL_EDIT_MESSAGE = "cadmus:visual-edit";
1249
+ function encodeEditRef(ref) {
1250
+ return `${ref.collection}:${ref.id}:${ref.field}`;
1251
+ }
1252
+ /** Parse an {@link EditRef} string, or null if malformed. */
1253
+ function decodeEditRef(value) {
1254
+ const parts = value.split(":");
1255
+ if (parts.length !== 3) return null;
1256
+ const [collection, idRaw, field] = parts;
1257
+ const id = Number.parseInt(idRaw, 10);
1258
+ if (!collection || !field || !Number.isFinite(id)) return null;
1259
+ return {
1260
+ collection,
1261
+ id,
1262
+ field
1263
+ };
1264
+ }
1265
+ /**
1266
+ * Attribute object to spread onto a rendered element so the overlay can map
1267
+ * it back to its source field, e.g. `<h1 {...editAttr({collection:'pages',
1268
+ * id, field:'title'})}>`.
1269
+ */
1270
+ function editAttr(ref) {
1271
+ return { [EDIT_ATTR]: encodeEditRef(ref) };
1272
+ }
1273
+ /**
1274
+ * Mount the click-to-edit overlay. Browser-only — call from a preview page's
1275
+ * client script. Highlights `[data-cadmus-edit]` elements on hover and, on
1276
+ * click, calls `onSelect` and posts a {@link VisualEditingMessage} to the
1277
+ * parent window. Returns a cleanup function that removes the listeners.
1278
+ */
1279
+ function mountVisualEditing(options = {}) {
1280
+ const { onSelect, targetOrigin = "*", highlightColor = "#56c6be" } = options;
1281
+ const closest = (target) => {
1282
+ if (!(target instanceof Element)) return null;
1283
+ const el = target.closest(`[${EDIT_ATTR}]`);
1284
+ return el instanceof HTMLElement ? el : null;
1285
+ };
1286
+ let previous = null;
1287
+ const clearHighlight = () => {
1288
+ if (previous) {
1289
+ previous.el.style.outline = previous.outline;
1290
+ previous = null;
1291
+ }
1292
+ };
1293
+ const onOver = (event) => {
1294
+ const el = closest(event.target);
1295
+ if (!el || el === previous?.el) return;
1296
+ clearHighlight();
1297
+ previous = {
1298
+ el,
1299
+ outline: el.style.outline
1300
+ };
1301
+ el.style.outline = `2px solid ${highlightColor}`;
1302
+ el.style.outlineOffset = "2px";
1303
+ el.style.cursor = "pointer";
1304
+ };
1305
+ const onClick = (event) => {
1306
+ const el = closest(event.target);
1307
+ if (!el) return;
1308
+ const ref = decodeEditRef(el.getAttribute("data-cadmus-edit") ?? "");
1309
+ if (!ref) return;
1310
+ event.preventDefault();
1311
+ event.stopPropagation();
1312
+ onSelect?.(ref, el);
1313
+ const message = {
1314
+ type: VISUAL_EDIT_MESSAGE,
1315
+ ref
1316
+ };
1317
+ window.parent?.postMessage(message, targetOrigin);
1318
+ };
1319
+ document.addEventListener("mouseover", onOver, true);
1320
+ document.addEventListener("click", onClick, true);
1321
+ return () => {
1322
+ clearHighlight();
1323
+ document.removeEventListener("mouseover", onOver, true);
1324
+ document.removeEventListener("click", onClick, true);
1325
+ };
1326
+ }
1327
+ //#endregion
662
1328
  //#region src/cms/webhooks.ts
663
1329
  /**
664
1330
  * Builds an `afterChange` hook that enqueues a `WebhookMessage` for every
@@ -738,6 +1404,6 @@ async function deliverWebhookMessage(message) {
738
1404
  if (!response.ok) throw new CadmusQueueError(`Webhook delivery to "${message.url}" returned status ${response.status}`);
739
1405
  }
740
1406
  //#endregion
741
- export { can, cmsConfigToSchema, collectionSearchTableName, collectionSearchTableSQL, collectionToTable, collectionVersionsTable, createLocalApi, createVersionedLocalApi, createWebhookHook, defineCmsConfig, defineCollection, deliverWebhookMessage, extractSearchText, flattenDoc, flattenFields, generateSchemaSource, getCollectionsMeta, getRegisteredApi, nestDoc, relationshipJoinTables };
1407
+ export { DEFAULT_STUDIO_GROUP, EDIT_ATTR, Rule, VISUAL_EDIT_MESSAGE, applyPatch, assertValid, buildStudioStructure, can, cmsConfigToSchema, collectionSearchTableName, collectionSearchTableSQL, collectionToTable, collectionVersionsTable, computePatch, createBlockRegistry, createLocalApi, createVersionedLocalApi, createWebhookHook, decodeEditRef, defineCmsConfig, defineCollection, defineField, defineMigration, deliverWebhookMessage, diffDocuments, editAttr, encodeEditRef, extractSearchText, flattenDoc, flattenFields, generateSchemaSource, getCollectionsMeta, getRegisteredApi, mountVisualEditing, nestDoc, relationshipJoinTables, renderBlocksToString, rule, runMigration, validateDocument };
742
1408
 
743
1409
  //# sourceMappingURL=index.js.map