@drawnagency/primitives 0.1.94 → 0.1.96

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 (82) hide show
  1. package/dist/{chunk-UFOWXOG6.js → chunk-CS2ECR3U.js} +9 -3
  2. package/dist/{chunk-GDLH3LVH.js → chunk-CSVGCAIH.js} +7 -6
  3. package/dist/chunk-EUSWEVOA.js +29 -0
  4. package/dist/{chunk-677NTHAZ.js → chunk-PTOLUMGV.js} +3 -0
  5. package/dist/{chunk-XYFZ57AS.js → chunk-YUUUCDXN.js} +59 -5
  6. package/dist/components/brandguide/Colors.d.ts +2 -2
  7. package/dist/components/brandguide/Colors.d.ts.map +1 -1
  8. package/dist/components/brandguide/ColorsEditable.d.ts +2 -2
  9. package/dist/components/brandguide/ColorsEditable.d.ts.map +1 -1
  10. package/dist/components/editor/SectionWrapper.d.ts.map +1 -1
  11. package/dist/components/editor/SettingsForm.d.ts.map +1 -1
  12. package/dist/components/editor/index.js +4 -3
  13. package/dist/components/primitives/index.js +1 -1
  14. package/dist/components/sections/Container/Container.d.ts +2 -2
  15. package/dist/components/sections/Container/Container.d.ts.map +1 -1
  16. package/dist/components/sections/brand-guide.js +2 -2
  17. package/dist/components/sections/register-schemas.js +4 -4
  18. package/dist/components/sections/register.js +4 -4
  19. package/dist/components/shared/HistoryChangesModal.d.ts +39 -0
  20. package/dist/components/shared/HistoryChangesModal.d.ts.map +1 -0
  21. package/dist/components/shared/HistoryPopover.d.ts +3 -1
  22. package/dist/components/shared/HistoryPopover.d.ts.map +1 -1
  23. package/dist/components/shared/Navigation.d.ts.map +1 -1
  24. package/dist/components/shared/Popover.d.ts +10 -1
  25. package/dist/components/shared/Popover.d.ts.map +1 -1
  26. package/dist/components/shell/EditorModal.d.ts +6 -1
  27. package/dist/components/shell/EditorModal.d.ts.map +1 -1
  28. package/dist/components/shell/EditorModalContext.d.ts +3 -2
  29. package/dist/components/shell/EditorModalContext.d.ts.map +1 -1
  30. package/dist/components/shell/EditorShell.d.ts.map +1 -1
  31. package/dist/hooks/useEditorPublish.d.ts +5 -1
  32. package/dist/hooks/useEditorPublish.d.ts.map +1 -1
  33. package/dist/index.js +45 -37
  34. package/dist/lib/events.d.ts +18 -0
  35. package/dist/lib/events.d.ts.map +1 -1
  36. package/dist/lib/history-buckets.d.ts +30 -0
  37. package/dist/lib/history-buckets.d.ts.map +1 -0
  38. package/dist/lib/index-ops.d.ts +77 -0
  39. package/dist/lib/index-ops.d.ts.map +1 -0
  40. package/dist/lib/index-ops.js +223 -0
  41. package/dist/lib/index.d.ts +1 -1
  42. package/dist/lib/index.d.ts.map +1 -1
  43. package/dist/lib/index.js +6 -4
  44. package/dist/lib/media-folders.d.ts +13 -0
  45. package/dist/lib/media-folders.d.ts.map +1 -1
  46. package/dist/lib/media-folders.js +172 -0
  47. package/dist/lib/registry.d.ts +7 -1
  48. package/dist/lib/registry.d.ts.map +1 -1
  49. package/dist/lib/theme-vars.d.ts +19 -4
  50. package/dist/lib/theme-vars.d.ts.map +1 -1
  51. package/dist/schemas/index.js +1 -1
  52. package/dist/storage/index.d.ts +1 -1
  53. package/dist/storage/index.d.ts.map +1 -1
  54. package/dist/storage/index.js +9 -3
  55. package/dist/storage/types.d.ts +44 -0
  56. package/dist/storage/types.d.ts.map +1 -1
  57. package/package.json +9 -1
  58. package/src/components/brandguide/Colors.tsx +2 -1
  59. package/src/components/brandguide/ColorsEditable.tsx +2 -1
  60. package/src/components/editor/SectionWrapper.tsx +1 -0
  61. package/src/components/editor/SettingsForm.tsx +5 -2
  62. package/src/components/sections/Container/Container.tsx +5 -4
  63. package/src/components/shared/HistoryChangesModal.tsx +256 -0
  64. package/src/components/shared/HistoryPopover.tsx +255 -76
  65. package/src/components/shared/Navigation.tsx +30 -9
  66. package/src/components/shared/Popover.tsx +95 -2
  67. package/src/components/shell/EditorModal.tsx +26 -4
  68. package/src/components/shell/EditorModalContext.tsx +5 -4
  69. package/src/components/shell/EditorShell.tsx +51 -2
  70. package/src/components/shell/SiteSettingsModal.tsx +1 -1
  71. package/src/hooks/useEditorPublish.ts +15 -6
  72. package/src/lib/events.ts +11 -0
  73. package/src/lib/history-buckets.ts +190 -0
  74. package/src/lib/index-ops.ts +309 -0
  75. package/src/lib/index.ts +1 -1
  76. package/src/lib/media-folders.ts +16 -0
  77. package/src/lib/registry.ts +9 -1
  78. package/src/lib/theme-vars.ts +25 -4
  79. package/src/storage/index.ts +1 -1
  80. package/src/storage/types.ts +55 -0
  81. package/dist/chunk-VAOW4WXQ.js +0 -15
  82. package/dist/{chunk-ZKGMLLUQ.js → chunk-IFCQWC3G.js} +3 -3
@@ -0,0 +1,190 @@
1
+ export interface HistoryCommit {
2
+ sha: string;
3
+ date: string;
4
+ /** First parent's sha; null for the repo's root commit. */
5
+ parent: string | null;
6
+ }
7
+
8
+ export type NodeKind = "commit" | "day" | "week" | "month" | "year";
9
+
10
+ export interface HistoryNode {
11
+ /** Stable React key, unique within the tree. */
12
+ id: string;
13
+ kind: NodeKind;
14
+ label: string;
15
+ sublabel: string | null;
16
+ count: number;
17
+ /** Newest commit in this node — what "browse" opens. */
18
+ newestSha: string | null;
19
+ /** Compare base: parent of this node's oldest commit. Null at repo root. */
20
+ baseSha: string | null;
21
+ children: HistoryNode[];
22
+ }
23
+
24
+ export type GroupId =
25
+ | "today" | "this-week" | "previous-weeks" | "earlier-months" | "previous-years";
26
+
27
+ export interface HistoryGroup {
28
+ id: GroupId;
29
+ label: string;
30
+ nodes: HistoryNode[];
31
+ }
32
+
33
+ const GROUPS: { id: GroupId; label: string }[] = [
34
+ { id: "today", label: "Today" },
35
+ { id: "this-week", label: "Earlier this week" },
36
+ { id: "previous-weeks", label: "Previous weeks" },
37
+ { id: "earlier-months", label: "Earlier months" },
38
+ { id: "previous-years", label: "Previous years" },
39
+ ];
40
+
41
+ // Calendar-day arithmetic (not fixed-ms) so DST transitions don't shift boundaries.
42
+ const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
43
+ const addDays = (d: Date, n: number) =>
44
+ new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
45
+ const startOfYear = (d: Date) => new Date(d.getFullYear(), 0, 1);
46
+
47
+ const WEEKDAY = new Intl.DateTimeFormat(undefined, { weekday: "long" });
48
+ const MONTH = new Intl.DateTimeFormat(undefined, { month: "long" });
49
+ const MON_DAY = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" });
50
+ const TIME = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" });
51
+
52
+ interface Dated extends HistoryCommit {
53
+ at: Date;
54
+ }
55
+
56
+ /** Oldest-first list → node metadata shared by every non-commit node. */
57
+ function rollup(sorted: Dated[]): Pick<HistoryNode, "count" | "newestSha" | "baseSha"> {
58
+ return {
59
+ count: sorted.length,
60
+ newestSha: sorted.length ? sorted[sorted.length - 1].sha : null,
61
+ baseSha: sorted.length ? sorted[0].parent : null,
62
+ };
63
+ }
64
+
65
+ function commitNode(c: Dated): HistoryNode {
66
+ return {
67
+ id: `c:${c.sha}`,
68
+ kind: "commit",
69
+ label: TIME.format(c.at),
70
+ sublabel: null,
71
+ count: 1,
72
+ newestSha: c.sha,
73
+ baseSha: c.parent,
74
+ children: [],
75
+ };
76
+ }
77
+
78
+ /** Bucket by a key derived from each commit's date, newest bucket first. */
79
+ function bucketBy(sorted: Dated[], key: (d: Date) => string): Map<string, Dated[]> {
80
+ const out = new Map<string, Dated[]>();
81
+ for (const c of sorted) {
82
+ const k = key(c.at);
83
+ const list = out.get(k);
84
+ if (list) list.push(c);
85
+ else out.set(k, [c]);
86
+ }
87
+ // sorted is oldest-first, so reverse the insertion order for newest-first display.
88
+ return new Map([...out.entries()].reverse());
89
+ }
90
+
91
+ const dayKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
92
+ const monthKey = (d: Date) => `${d.getFullYear()}-${d.getMonth()}`;
93
+ const yearKey = (d: Date) => `${d.getFullYear()}`;
94
+
95
+ /** Day nodes whose children are commit nodes. `weekday` picks the label style. */
96
+ function dayNodes(sorted: Dated[], weekday: boolean): HistoryNode[] {
97
+ return [...bucketBy(sorted, dayKey).entries()].map(([k, list]) => ({
98
+ id: `d:${k}`,
99
+ kind: "day" as const,
100
+ label: weekday ? WEEKDAY.format(list[0].at) : MON_DAY.format(list[0].at),
101
+ sublabel: weekday ? MON_DAY.format(list[0].at) : null,
102
+ ...rollup(list),
103
+ children: [...list].reverse().map(commitNode),
104
+ }));
105
+ }
106
+
107
+ function monthNodes(sorted: Dated[], withYear: boolean): HistoryNode[] {
108
+ return [...bucketBy(sorted, monthKey).entries()].map(([k, list]) => ({
109
+ id: `m:${k}`,
110
+ kind: "month" as const,
111
+ label: MONTH.format(list[0].at),
112
+ sublabel: withYear ? String(list[0].at.getFullYear()) : null,
113
+ ...rollup(list),
114
+ children: dayNodes(list, false),
115
+ }));
116
+ }
117
+
118
+ function yearNodes(sorted: Dated[]): HistoryNode[] {
119
+ return [...bucketBy(sorted, yearKey).entries()].map(([k, list]) => ({
120
+ id: `y:${k}`,
121
+ kind: "year" as const,
122
+ label: k,
123
+ sublabel: null,
124
+ ...rollup(list),
125
+ children: monthNodes(list, false),
126
+ }));
127
+ }
128
+
129
+ /**
130
+ * Up to three 7-day windows, newest first. Windows with no commits are dropped
131
+ * rather than rendered empty — an editor scanning history wants the edits, not
132
+ * a fixed-width calendar.
133
+ */
134
+ function weekNodes(sorted: Dated[], windowStart: Date): HistoryNode[] {
135
+ const out: HistoryNode[] = [];
136
+ for (let i = 1; i <= 3; i++) {
137
+ const start = addDays(windowStart, -7 * i);
138
+ const end = addDays(windowStart, -7 * (i - 1));
139
+ const list = sorted.filter((c) => c.at >= start && c.at < end);
140
+ if (list.length === 0) continue;
141
+ out.push({
142
+ id: `w:${dayKey(start)}`,
143
+ kind: "week",
144
+ label: `${MON_DAY.format(start)} – ${MON_DAY.format(addDays(end, -1))}`,
145
+ sublabel: null,
146
+ ...rollup(list),
147
+ children: dayNodes(list, false),
148
+ });
149
+ }
150
+ return out;
151
+ }
152
+
153
+ export function buildHistoryTree(commits: HistoryCommit[], now: Date): HistoryGroup[] {
154
+ // Oldest-first throughout; each builder reverses for display.
155
+ const sorted: Dated[] = commits
156
+ .map((c) => ({ ...c, at: new Date(c.date) }))
157
+ .filter((c) => !Number.isNaN(c.at.getTime()))
158
+ .sort((a, b) => a.at.getTime() - b.at.getTime());
159
+
160
+ const t0 = startOfDay(now); // today begins
161
+ const t1 = addDays(t0, -6); // "earlier this week" window begins
162
+ const t2 = addDays(t1, -21); // "previous weeks" window begins
163
+ const y0 = startOfYear(now); // current year begins
164
+ const monthsEnd = t2; // earlier-months covers [y0, t2)
165
+ const yearsEnd = t2 < y0 ? t2 : y0; // previous-years covers [-inf, yearsEnd)
166
+
167
+ const inRange = (lo: Date | null, hi: Date) =>
168
+ sorted.filter((c) => (lo === null || c.at >= lo) && c.at < hi);
169
+
170
+ const byId: Record<GroupId, HistoryNode[]> = {
171
+ "today": [...sorted.filter((c) => c.at >= t0)].reverse().map(commitNode),
172
+ "this-week": dayNodes(inRange(t1, t0), true),
173
+ "previous-weeks": weekNodes(sorted, t1),
174
+ "earlier-months": monthsEnd > y0 ? monthNodes(inRange(y0, monthsEnd), true) : [],
175
+ "previous-years": yearNodes(inRange(null, yearsEnd)),
176
+ };
177
+
178
+ return GROUPS.map((g) => ({ ...g, nodes: byId[g.id] }));
179
+ }
180
+
181
+ /** Largest node count anywhere in the tree; never 0, so callers can divide by it. */
182
+ export function maxNodeCount(groups: HistoryGroup[]): number {
183
+ let max = 1;
184
+ const walk = (n: HistoryNode) => {
185
+ if (n.count > max) max = n.count;
186
+ n.children.forEach(walk);
187
+ };
188
+ groups.forEach((g) => g.nodes.forEach(walk));
189
+ return max;
190
+ }
@@ -0,0 +1,309 @@
1
+ import { z } from "zod";
2
+ import { IndexSchema, RESERVED_SLUGS, type SiteIndex, type SectionMeta } from "../schemas/site-config";
3
+
4
+ /**
5
+ * Server-applied index deltas for the MCP connector's save path. An agent
6
+ * cannot reliably hand-transcribe a real site's 40–51 KB index into a tool
7
+ * parameter (two consecutive attempts each introduced an id-level slip), so
8
+ * structural edits are expressed as ops and applied here against the index the
9
+ * write is concurrency-checked against.
10
+ *
11
+ * Pure by contract: no I/O, no storage, no octokit. The caller owns reading the
12
+ * base index at the right commit and committing the result.
13
+ */
14
+
15
+ // The three canonical statuses. Deliberately a plain enum rather than the
16
+ // schemas' StatusSchema (a ZodPipe with a "published" -> "live" transform):
17
+ // this shape is converted to JSON Schema for MCP clients, so it stays a flat
18
+ // enum, and reads never surface "published" anyway (they return normalized
19
+ // values).
20
+ const OpStatusSchema = z.enum(["draft", "live", "archived"]);
21
+
22
+ // Must match content-ops' SAFE_SECTION_ID: the id becomes a FILENAME
23
+ // (src/content/sections/<id>.json). Enforced here so a bad id is a named op
24
+ // error rather than a bare "[input] Invalid section ID" from deep in the write
25
+ // path, which names neither the op nor the id.
26
+ const SAFE_SECTION_ID = /^[a-zA-Z0-9_-]{1,64}$/;
27
+
28
+ const SectionInsertSchema = z.object({
29
+ id: z.string().regex(SAFE_SECTION_ID, "Section ids may only contain letters, numbers, dashes and underscores (max 64 chars) — they become filenames.").describe("The new section's id: letters, numbers, dashes, underscores; max 64 chars. Must not already exist in the index."),
30
+ status: OpStatusSchema.optional().describe('Defaults to "draft" — invisible to viewers until promoted to "live".'),
31
+ access: z.array(z.string()).optional().describe("Audience slugs from list_audiences. Defaults to [] (everyone)."),
32
+ });
33
+
34
+ export const IndexOpSchema = z.discriminatedUnion("op", [
35
+ z.object({
36
+ op: z.literal("insertAfter"),
37
+ pageId: z.string().describe("The page whose order receives the sections."),
38
+ afterId: z.string().nullable().describe("Insert directly after this section id, or null for the start of the page."),
39
+ sections: z.array(SectionInsertSchema).min(1).describe("Sections to create, in the order they should appear. Each needs its body in this call's `sections`."),
40
+ }),
41
+ z.object({
42
+ op: z.literal("insertAt"),
43
+ pageId: z.string().describe("The page whose order receives the sections."),
44
+ position: z.number().int().min(0).describe("0-based index in the page's order; equal to the order's length appends."),
45
+ sections: z.array(SectionInsertSchema).min(1).describe("Sections to create, in the order they should appear. Each needs its body in this call's `sections`."),
46
+ }),
47
+ z.object({
48
+ op: z.literal("move"),
49
+ pageId: z.string().describe("Destination page id (may be the section's current page)."),
50
+ id: z.string().describe("The existing section to move."),
51
+ afterId: z.string().nullable().describe("Place it directly after this section id in the destination page, or null for the start."),
52
+ }),
53
+ z.object({
54
+ op: z.literal("remove"),
55
+ ids: z.array(z.string()).min(1).describe("Sections to delete: removed from the page order AND from sections{}, and their content files are deleted."),
56
+ }),
57
+ z.object({
58
+ op: z.literal("setMeta"),
59
+ id: z.string().describe("An existing section id."),
60
+ status: OpStatusSchema.optional().describe('New status. "live" is what makes a section visible to viewers.'),
61
+ access: z.array(z.string()).optional().describe("New audience slugs from list_audiences; [] means everyone."),
62
+ }),
63
+ z.object({
64
+ op: z.literal("setPageMeta"),
65
+ pageId: z.string().describe("An existing page id."),
66
+ title: z.string().optional().describe("New page title."),
67
+ slug: z.string().optional().describe("New URL slug (lowercase words joined by dashes). Not settable on the home page, whose slug is always empty."),
68
+ showInNav: z.boolean().optional().describe("Whether the page appears in site navigation."),
69
+ access: z.array(z.string()).optional().describe("New audience slugs from list_audiences; [] means everyone."),
70
+ }),
71
+ ]);
72
+
73
+ export type IndexOp = z.infer<typeof IndexOpSchema>;
74
+
75
+ export type ApplyIndexOpsResult =
76
+ | { ok: true; index: SiteIndex; removedIds: string[]; warnings: string[] }
77
+ | { ok: false; error: string };
78
+
79
+ /** Section-body types keyed by id, for the ids an insert op creates. */
80
+ export function collectPostedTypes(sections: { id: string; content: unknown }[] | undefined): Record<string, string> {
81
+ const types: Record<string, string> = {};
82
+ for (const s of sections ?? []) {
83
+ const type = (s.content as { type?: unknown } | null | undefined)?.type;
84
+ if (typeof type === "string") types[s.id] = type;
85
+ }
86
+ return types;
87
+ }
88
+
89
+ /**
90
+ * Every section id the ops name, derivable from the ops ALONE (no index read).
91
+ * Callers need this before applying anything: the collab broadcast has to tell
92
+ * browser editors which rows moved, and the audit trail has to record that an
93
+ * ops-only save touched anything at all. `setPageMeta` names no section.
94
+ */
95
+ export function opTouchedSectionIds(ops: IndexOp[]): string[] {
96
+ const ids = new Set<string>();
97
+ for (const op of ops) {
98
+ if (op.op === "insertAfter" || op.op === "insertAt") for (const s of op.sections) ids.add(s.id);
99
+ else if (op.op === "move" || op.op === "setMeta") ids.add(op.id);
100
+ else if (op.op === "remove") for (const id of op.ids) ids.add(id);
101
+ }
102
+ return [...ids];
103
+ }
104
+
105
+ const fmt = (ids: string[]) => ids.map((id) => `"${id}"`).join(", ");
106
+
107
+ export function applyIndexOps(
108
+ rawIndex: unknown,
109
+ ops: IndexOp[],
110
+ newSectionTypes: Record<string, string>,
111
+ ): ApplyIndexOpsResult {
112
+ // Apply to the CANONICAL shape, not the raw one: a legacy index
113
+ // (`order`/`sections` with no `pages`) normalizes into a synthetic home page
114
+ // carrying those ids, and ops against the raw shape would find no pages at
115
+ // all and silently miss every id.
116
+ const base = IndexSchema.safeParse(rawIndex);
117
+ if (!base.success) {
118
+ return {
119
+ ok: false,
120
+ error:
121
+ "the site's current index could not be parsed, so indexOps cannot be applied — read it with get_site_index and post a repaired full `index` instead. " +
122
+ base.error.issues.map((i) => i.message).join("; "),
123
+ };
124
+ }
125
+
126
+ // Own copy: the caller's index is also its knownSiteTypes source and may be
127
+ // logged, so nothing here mutates it.
128
+ const index: SiteIndex = {
129
+ ...base.data,
130
+ pages: base.data.pages.map((p) => ({ ...p, order: [...p.order] })),
131
+ sections: Object.fromEntries(Object.entries(base.data.sections).map(([k, v]) => [k, { ...v }])),
132
+ };
133
+
134
+ const removed = new Set<string>();
135
+ const warnings: string[] = [];
136
+ const fail = (error: string): ApplyIndexOpsResult => ({ ok: false, error });
137
+
138
+ for (const [i, op] of ops.entries()) {
139
+ const at = `indexOps[${i}] ${op.op}`;
140
+
141
+ if (op.op === "insertAfter" || op.op === "insertAt") {
142
+ const page = index.pages.find((p) => p.id === op.pageId);
143
+ if (!page) return fail(`${at}: no page with id "${op.pageId}" — page ids come from get_site_index.`);
144
+
145
+ let position: number;
146
+ if (op.op === "insertAfter") {
147
+ if (op.afterId === null) position = 0;
148
+ else {
149
+ const idx = page.order.indexOf(op.afterId);
150
+ if (idx === -1) return fail(`${at}: afterId "${op.afterId}" is not in page "${op.pageId}"'s order.`);
151
+ position = idx + 1;
152
+ }
153
+ } else {
154
+ if (op.position > page.order.length) {
155
+ return fail(`${at}: position ${op.position} is out of range for page "${op.pageId}" (valid: 0..${page.order.length}).`);
156
+ }
157
+ position = op.position;
158
+ }
159
+
160
+ const metas: [string, SectionMeta][] = [];
161
+ // Ids in THIS op are not in `index.sections` yet, so the existence check
162
+ // below cannot see them — without a local seen-set a repeated id splices
163
+ // twice and only fails at the final re-validation, as "appears in more
164
+ // than one page order" with no op index and a misleading description.
165
+ const seen = new Set<string>();
166
+ for (const s of op.sections) {
167
+ if (seen.has(s.id)) return fail(`${at}: section "${s.id}" is listed twice in this op's \`sections\`.`);
168
+ seen.add(s.id);
169
+ if (index.sections[s.id]) {
170
+ return fail(`${at}: section "${s.id}" already exists in the index — use move to relocate it, or setMeta to change its status/access.`);
171
+ }
172
+ if (!SAFE_SECTION_ID.test(s.id)) {
173
+ return fail(`${at}: section id "${s.id}" is not usable — ids become filenames, so they may only contain letters, numbers, dashes and underscores (max 64 chars).`);
174
+ }
175
+ const type = newSectionTypes[s.id];
176
+ if (!type) {
177
+ // Covers both "no body posted" and "body posted but its `type` is
178
+ // missing or not a string" — collectPostedTypes only records usable
179
+ // string types, so this cannot tell them apart, and the old wording
180
+ // ("has no body") sent an agent hunting for a body that was right there.
181
+ return fail(`${at}: section "${s.id}" has no usable body in this call — post its full body ({ "type": "...", "content": {...} }) in \`sections\` in the same save; an inserted section's type comes from the body.`);
182
+ }
183
+ const meta: SectionMeta = { type, status: s.status ?? "draft", access: s.access ?? [] };
184
+ // Same advisory as `move`: an inserted section whose audiences the
185
+ // destination page does not allow is invisible to every audienced
186
+ // viewer, and saying nothing would make that look like a successful save.
187
+ const stranded = page.access.length > 0 ? meta.access.filter((a) => !page.access.includes(a)) : [];
188
+ if (stranded.length > 0) {
189
+ warnings.push(
190
+ `${at}: section "${s.id}" carries audience(s) ${fmt(stranded)} that page "${op.pageId}" does not allow, so no audienced viewer will see it — clear it with setMeta, or widen the page's access.`,
191
+ );
192
+ }
193
+ metas.push([s.id, meta]);
194
+ }
195
+ page.order.splice(position, 0, ...metas.map(([id]) => id));
196
+ for (const [id, meta] of metas) index.sections[id] = meta;
197
+ continue;
198
+ }
199
+
200
+ if (op.op === "move") {
201
+ const meta = index.sections[op.id];
202
+ if (!meta) return fail(`${at}: section "${op.id}" is not in the index.`);
203
+ const dest = index.pages.find((p) => p.id === op.pageId);
204
+ if (!dest) return fail(`${at}: no page with id "${op.pageId}" — page ids come from get_site_index.`);
205
+ if (op.afterId === op.id) return fail(`${at}: cannot move section "${op.id}" after itself.`);
206
+
207
+ for (const p of index.pages) {
208
+ const idx = p.order.indexOf(op.id);
209
+ if (idx !== -1) p.order.splice(idx, 1);
210
+ }
211
+ let position: number;
212
+ if (op.afterId === null) position = 0;
213
+ else {
214
+ const idx = dest.order.indexOf(op.afterId);
215
+ if (idx === -1) return fail(`${at}: afterId "${op.afterId}" is not in destination page "${op.pageId}"'s order.`);
216
+ position = idx + 1;
217
+ }
218
+ dest.order.splice(position, 0, op.id);
219
+
220
+ // Advisory, never a silent rewrite: the editor's moveSection resets an
221
+ // incompatible section access, but an API doing that invisibly would
222
+ // change who can see content without saying so. "no audienced viewer",
223
+ // not "everyone" — audiencePasses returns true for a viewer with no
224
+ // audience at all (lib/pages.ts).
225
+ const stranded = dest.access.length > 0 ? meta.access.filter((a) => !dest.access.includes(a)) : [];
226
+ if (stranded.length > 0) {
227
+ warnings.push(
228
+ `${at}: section "${op.id}" carries audience(s) ${fmt(stranded)} that page "${op.pageId}" does not allow, so no audienced viewer will see it — clear it with setMeta, or widen the page's access.`,
229
+ );
230
+ }
231
+ continue;
232
+ }
233
+
234
+ if (op.op === "remove") {
235
+ for (const id of op.ids) {
236
+ if (!index.sections[id]) return fail(`${at}: section "${id}" is not in the index.`);
237
+ delete index.sections[id];
238
+ for (const p of index.pages) {
239
+ const idx = p.order.indexOf(id);
240
+ if (idx !== -1) p.order.splice(idx, 1);
241
+ }
242
+ removed.add(id);
243
+ }
244
+ continue;
245
+ }
246
+
247
+ if (op.op === "setMeta") {
248
+ if (op.status === undefined && op.access === undefined) {
249
+ return fail(`${at}: nothing to set — provide status and/or access.`);
250
+ }
251
+ const meta = index.sections[op.id];
252
+ if (!meta) return fail(`${at}: section "${op.id}" is not in the index.`);
253
+ if (op.status !== undefined) meta.status = op.status;
254
+ if (op.access !== undefined) meta.access = op.access;
255
+ continue;
256
+ }
257
+
258
+ // setPageMeta
259
+ if (op.title === undefined && op.slug === undefined && op.showInNav === undefined && op.access === undefined) {
260
+ return fail(`${at}: nothing to set — provide title, slug, showInNav and/or access.`);
261
+ }
262
+ const page = index.pages.find((p) => p.id === op.pageId);
263
+ if (!page) return fail(`${at}: no page with id "${op.pageId}" — page ids come from get_site_index.`);
264
+ if (op.slug !== undefined && page.isHome) {
265
+ return fail(`${at}: the home page's slug is always empty and cannot be set. Promote a different page to home in the editor if you need to change which page is the root.`);
266
+ }
267
+ // IndexSchema hard-rejects only the five slugs reserved before client sites
268
+ // existed (PARSE_REJECTED_SLUGS) — the newer ones ("present", "print") are
269
+ // enforced at AUTHORING time on purpose, so a grandfathered index still
270
+ // loads (see schemas/site-config.ts). This is an authoring surface, so it
271
+ // owns that enforcement; without it a page silently disappears behind an
272
+ // injected platform route with no error anywhere.
273
+ if (op.slug !== undefined && (RESERVED_SLUGS as readonly string[]).includes(op.slug)) {
274
+ return fail(`${at}: slug "${op.slug}" is reserved by a platform route and would shadow this page. Pick another slug.`);
275
+ }
276
+ if (op.title !== undefined) page.title = op.title;
277
+ if (op.slug !== undefined) page.slug = op.slug;
278
+ if (op.showInNav !== undefined) page.showInNav = op.showInNav;
279
+ if (op.access !== undefined) {
280
+ const dropped = page.access.filter((a) => !op.access!.includes(a));
281
+ page.access = op.access;
282
+ if (dropped.length > 0 && op.access.length > 0) {
283
+ const stranded = page.order.filter((id) => index.sections[id]?.access.some((a) => dropped.includes(a)));
284
+ if (stranded.length > 0) {
285
+ warnings.push(
286
+ `${at}: section(s) ${fmt(stranded)} still carry audience(s) ${fmt(dropped)} that page "${op.pageId}" no longer allows, so no audienced viewer will see them — clear them with setMeta.`,
287
+ );
288
+ }
289
+ }
290
+ }
291
+ }
292
+
293
+ // A remove followed by a re-insert of the same id is a net no-op for files:
294
+ // reporting it for deletion would delete the file the resulting index
295
+ // references, and content-ops' stillReferenced guard would reject the write.
296
+ const removedIds = [...removed].filter((id) => !index.sections[id]);
297
+
298
+ // Ops cannot break the order/sections partition by construction, but they can
299
+ // break page-level invariants the ops above do not check themselves: a
300
+ // duplicate slug, an invalid slug shape, one of the five parse-rejected legacy
301
+ // slugs. Re-run the canonical validation so the caller gets those named here
302
+ // rather than as an opaque ZodError from the write path. (The NEWER reserved
303
+ // slugs are not in that set — setPageMeta checks them itself, above.)
304
+ const validated = IndexSchema.safeParse(index);
305
+ if (!validated.success) {
306
+ return fail(`applying indexOps produced an invalid index: ${validated.error.issues.map((issue) => issue.message).join("; ")}`);
307
+ }
308
+ return { ok: true, index: validated.data, removedIds, warnings };
309
+ }
package/src/lib/index.ts CHANGED
@@ -12,7 +12,7 @@ export {
12
12
  suggestAccessibleOn,
13
13
  type WcagLevel,
14
14
  } from "./contrast";
15
- export { primaryVarValue, accentVarValue } from "./theme-vars";
15
+ export { primaryVarValue, accentVarValue, onPrimaryVarValue } from "./theme-vars";
16
16
  export { sanitizeHtml, ensureSanitizer } from "./sanitize";
17
17
  export { gridColsClass } from "./grid";
18
18
  export { getIcon, curatedIcons, type IconEntry } from "./icons";
@@ -178,6 +178,22 @@ export function healMediaManifest(manifest: MediaManifest): MediaManifest {
178
178
  return { ...manifest, images, folders };
179
179
  }
180
180
 
181
+ /**
182
+ * Rebase a local manifest onto a freshly-fetched remote one, so media another
183
+ * writer added is in our copy before the next save assembles from it. Without
184
+ * this a rebased session still writes its pre-conflict manifest, which silently
185
+ * drops their entries and orphans the files they committed.
186
+ *
187
+ * Images union, ours winning, so local alt/folder-move edits survive; a pending
188
+ * local deletion isn't removed from the manifest until save, so the union can't
189
+ * resurrect one. Folders stay ours verbatim — deleting a folder removes it from
190
+ * our map with no wire signal, so unioning would undo the delete. Mirrors the
191
+ * server-side merge in core's content-ops.
192
+ */
193
+ export function rebaseMediaManifest(local: MediaManifest, remote: MediaManifest): MediaManifest {
194
+ return { ...local, images: { ...remote.images, ...local.images } };
195
+ }
196
+
181
197
  /**
182
198
  * Save-time manifest assembly: merge uploaded pending items, apply deletions,
183
199
  * preserve every other manifest key (folders!), then heal.
@@ -77,12 +77,20 @@ export type Thumbnail =
77
77
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
78
  export type CustomSettingsFormProps = Record<string, any>;
79
79
 
80
+ export interface ModalOptions {
81
+ /** Content is a tab set — lock the modal height so tab switches don't resize it. */
82
+ tabbed?: boolean;
83
+ }
84
+
85
+ /** Signature of the editor's modal opener as threaded down to sections. */
86
+ export type OpenModal = (title: string, content: ReactNode, options?: ModalOptions) => void;
87
+
80
88
  export interface SectionProps<T = unknown> {
81
89
  content: T;
82
90
  options?: Record<string, unknown>;
83
91
  onChange?: (content: T) => void;
84
92
  isEditMode: boolean;
85
- openModal?: (title: string, content: ReactNode) => void;
93
+ openModal?: OpenModal;
86
94
  /** Delete this whole section. Used e.g. when a colors section's last swatch
87
95
  * is dragged into another section, leaving it empty. */
88
96
  onDelete?: () => void;
@@ -1,11 +1,13 @@
1
1
  import type { SiteConfig } from "../schemas/site-config";
2
+ import { suggestAccessibleOn } from "./contrast";
2
3
 
3
4
  /**
4
5
  * Computes the CSS value for the brand `--color-primary` / `--color-primary-contrast`
5
- * custom properties. When darkMode is "optional" AND a dark variant is set, the
6
- * value is a CSS `light-dark(<light>, <dark>)` expression — the browser resolves
7
- * it per the element's `color-scheme` (the `.dark` class sets `color-scheme: dark`;
8
- * `:root` sets `color-scheme: light`). Otherwise it's the plain light hex.
6
+ * / `--color-on-primary` custom properties. When darkMode is "optional" AND a dark
7
+ * variant is set, the value is a CSS `light-dark(<light>, <dark>)` expression — the
8
+ * browser resolves it per the element's `color-scheme` (the `.dark` class sets
9
+ * `color-scheme: dark`; `:root` sets `color-scheme: light`). Otherwise it's the
10
+ * plain light hex.
9
11
  *
10
12
  * Single source of truth for every injection site: Layout.astro / LoginLayout.astro
11
13
  * (SSR inline `<html style>`) and EditorShell (live setProperty + localStorage).
@@ -29,3 +31,22 @@ export function primaryVarValue(c?: Partial<ThemeColorConfig> | null): string {
29
31
  export function accentVarValue(c?: Partial<ThemeColorConfig> | null): string {
30
32
  return lightDark(c?.primaryContrast ?? DEFAULT_CONTRAST, c?.primaryContrastDark, c?.darkMode === "optional");
31
33
  }
34
+
35
+ /**
36
+ * Foreground ink for text drawn ON a `--color-primary`-filled surface (branded
37
+ * plates, primary cards). Derived from `primaryColor` with the same
38
+ * black/white WCAG pick the editor's accent "Suggest" button uses, so a
39
+ * primary-filled surface is legible on every brand without configuration.
40
+ *
41
+ * This exists because `--color-primary-contrast` cannot serve the role: it is
42
+ * the *accent* — brands legitimately repoint it at a decorative colour (Siete's
43
+ * gold on aubergine) that reads as a highlight but cannot carry body copy.
44
+ * Sections should consume `var(--color-on-primary)` for text on primary and
45
+ * keep `--color-primary-contrast` for accents, and derive softer inks by mixing
46
+ * the two brand tokens: `color-mix(in srgb, var(--color-on-primary) 70%, var(--color-primary))`.
47
+ */
48
+ export function onPrimaryVarValue(c?: Partial<ThemeColorConfig> | null): string {
49
+ const light = suggestAccessibleOn(c?.primaryColor ?? DEFAULT_PRIMARY);
50
+ const dark = c?.primaryColorDark ? suggestAccessibleOn(c.primaryColorDark) : null;
51
+ return lightDark(light, dark, c?.darkMode === "optional");
52
+ }
@@ -1,2 +1,2 @@
1
1
  export type { StorageProvider, FileWrite, AssetStore } from "./types";
2
- export { StorageConflictError, ASSET_CACHE_CONTROL } from "./types";
2
+ export { StorageConflictError, ASSET_CACHE_CONTROL, IDEMPOTENCY_TRAILER, IDEMPOTENCY_KEY_RE, withIdempotencyTrailer } from "./types";
@@ -31,6 +31,61 @@ export interface StorageProvider {
31
31
  getVersion(): Promise<string>;
32
32
 
33
33
  listDirectory(path: string, options?: { draft?: boolean }): Promise<string[]>;
34
+
35
+ /**
36
+ * Find a recent commit on the draft branch whose message carries the given
37
+ * `Idempotency-Key:` trailer, returning its sha (null if not found).
38
+ *
39
+ * This exists to make a retried write LEGIBLE, not to make it safe — safety is
40
+ * already `writeFiles`' baseVersion check, which a retry cannot get past once
41
+ * the original landed (the head moved, so the retry's baseVersion is stale).
42
+ * What the check cannot do is tell "your write failed" from "your write
43
+ * succeeded and you didn't hear back", and it reports both as a conflict. A
44
+ * caller that tagged its write can ask that question here.
45
+ *
46
+ * OPTIONAL: providers that cannot search history omit it, and callers fall
47
+ * back to surfacing the plain conflict.
48
+ *
49
+ * Best-effort by contract. It searches a BOUNDED window, so an old key reads
50
+ * as absent, and an implementation may answer "not found" when the history
51
+ * read itself fails — failing closed keeps the conflict rather than inventing
52
+ * a replay. So `null` means "could not confirm", NOT "your write did not
53
+ * land": a caller must not tell the user the earlier attempt failed.
54
+ */
55
+ findCommitByIdempotencyKey?(
56
+ key: string,
57
+ options?: { limit?: number },
58
+ ): Promise<string | null>;
59
+ }
60
+
61
+ /**
62
+ * Commit-message trailer carrying a write's idempotency key. The commit itself is
63
+ * the store — no table, and no TTL to tune: keys live exactly as long as the
64
+ * draft branch, and `promoteDraft` deletes it, which is the correct lifetime
65
+ * (after a publish there is no draft, so an old write must not replay).
66
+ */
67
+ export const IDEMPOTENCY_TRAILER = "Idempotency-Key";
68
+
69
+ /**
70
+ * Keys are interpolated into a commit message, so the charset is enforced HERE,
71
+ * at the interpolation point, and not only by the caller that happens to have a
72
+ * schema. A key containing a newline would let a caller append arbitrary further
73
+ * trailer lines to the commit.
74
+ */
75
+ export const IDEMPOTENCY_KEY_RE = /^[A-Za-z0-9._:-]{8,200}$/;
76
+
77
+ /**
78
+ * Build a commit message carrying `key` as a trailer, or return `subject`
79
+ * unchanged when no key is given. Throws on a malformed key: every caller
80
+ * reaches this through a write path that should have validated first, so an
81
+ * invalid key here is a bug, not user input to be tolerated.
82
+ */
83
+ export function withIdempotencyTrailer(subject: string, key?: string): string {
84
+ if (!key) return subject;
85
+ if (!IDEMPOTENCY_KEY_RE.test(key)) {
86
+ throw new Error("Invalid idempotency key: expected 8-200 chars of A-Za-z0-9._:-");
87
+ }
88
+ return `${subject}\n\n${IDEMPOTENCY_TRAILER}: ${key}`;
34
89
  }
35
90
 
36
91
  export type FileWrite = {