@kidecms/core 0.24.0 → 0.25.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.
@@ -41,13 +41,17 @@ export default function ColorField({ name, value: initial, placeholder, colors =
41
41
  onChange?.(v);
42
42
  };
43
43
 
44
- const selected = colors.find((c) => c.value.toLowerCase() === value.trim().toLowerCase());
44
+ // A stored value outside the palette (imported content, a palette edit) must stay
45
+ // visible and re-selectable rather than collapsing into the empty placeholder.
46
+ const known = colors.find((c) => c.value.toLowerCase() === value.trim().toLowerCase());
47
+ const options = value && !known ? [{ label: "Custom", value }, ...colors] : colors;
48
+ const selected = known ?? options.find((c) => c.value === value);
45
49
 
46
50
  return (
47
51
  <div className="relative">
48
52
  {name && <input type="hidden" name={name} value={value} ref={hiddenRef} />}
49
53
 
50
- <Select items={colors} value={value} onValueChange={(v) => set((v as string) ?? "")}>
54
+ <Select items={options} value={value} onValueChange={(v) => set((v as string) ?? "")}>
51
55
  <SelectTrigger className={cn("w-full", value && "pr-14")}>
52
56
  {selected ? (
53
57
  <span className="flex flex-1 items-center gap-2">
@@ -61,7 +65,7 @@ export default function ColorField({ name, value: initial, placeholder, colors =
61
65
  </SelectTrigger>
62
66
  <SelectContent>
63
67
  <SelectGroup>
64
- {colors.map((c) => (
68
+ {options.map((c) => (
65
69
  <SelectItem key={c.value} value={c.value}>
66
70
  <Swatch color={c.value} />
67
71
  <span className="flex-1">{c.label}</span>
@@ -357,7 +357,7 @@ const ToolbarButton = ({
357
357
  title={title}
358
358
  className={cn(
359
359
  "disabled:hover:text-muted-foreground inline-flex size-8 items-center justify-center rounded-md transition-colors outline-none disabled:opacity-50 disabled:hover:bg-transparent",
360
- active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
360
+ active ? "bg-foreground/10 text-foreground" : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
361
361
  )}
362
362
  >
363
363
  {children}
@@ -183,7 +183,7 @@ const ToolbarButton = ({
183
183
  className={cn(
184
184
  "disabled:hover:text-muted-foreground inline-flex size-8 items-center justify-center rounded-md transition-colors outline-none disabled:opacity-50 disabled:hover:bg-transparent",
185
185
  active
186
- ? "bg-muted-strong text-accent-foreground"
186
+ ? "bg-foreground/10 text-foreground"
187
187
  : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
188
188
  )}
189
189
  >
@@ -18,13 +18,26 @@ export function slugify(value: string) {
18
18
  .replace(/^-+|-+$/g, "");
19
19
  }
20
20
 
21
+ /** Imported values often omit `children` (or `id`); fill them in so the editor never
22
+ * reads `.children.length` off undefined. Extra keys are kept. */
23
+ export function normalizeItems(list: unknown): TreeItem[] {
24
+ if (!Array.isArray(list)) return [];
25
+ return list
26
+ .filter((item): item is Record<string, unknown> => !!item && typeof item === "object" && !Array.isArray(item))
27
+ .map((item) => ({
28
+ ...item,
29
+ id: typeof item.id === "string" && item.id ? item.id : generateId(),
30
+ children: normalizeItems(item.children),
31
+ }));
32
+ }
33
+
21
34
  export function parseItems(value?: string): TreeItem[] {
22
35
  if (!value) return [];
23
36
  try {
24
- const parsed = JSON.parse(value);
25
- if (Array.isArray(parsed)) return parsed;
26
- } catch {}
27
- return [];
37
+ return normalizeItems(JSON.parse(value));
38
+ } catch {
39
+ return [];
40
+ }
28
41
  }
29
42
 
30
43
  export function cloneItems(items: TreeItem[]): TreeItem[] {
@@ -35,7 +35,8 @@ export const FIELD_MODEL: Record<string, FieldModelEntry> = {
35
35
  select: { storage: "text", control: "dropdown", valueShape: "string (one of `options`)" },
36
36
  color: {
37
37
  storage: "text",
38
- control: "colour swatch picker (brand palette + custom + hex)",
38
+ control:
39
+ "colour swatch picker — palette from admin.colors (or per-field colors); no free hex entry, off-palette values show as 'Custom'",
39
40
  valueShape: "hex string e.g. '#00BB5F' (empty string = inherit default)",
40
41
  },
41
42
  richText: {
@@ -62,6 +63,18 @@ export const FIELD_MODEL: Record<string, FieldModelEntry> = {
62
63
  control: "link control (internal page picker / external URL + label + new-tab)",
63
64
  valueShape: "{ type:'internal'|'external', url:string, label?:string, newTab?:boolean }",
64
65
  },
66
+ "taxonomy-terms": {
67
+ storage: "json",
68
+ control: "term tree editor (nested, sortable; feeds taxonomy-select fields by slug)",
69
+ valueShape:
70
+ "Array<{ id:string, name:string, slug:string, children:Term[] }> — `children` required on every term (use [])",
71
+ },
72
+ "menu-items": {
73
+ storage: "json",
74
+ control: "menu tree editor (nested to 3 levels, sortable, internal/external links)",
75
+ valueShape:
76
+ "Array<{ id:string, label:string, href:string, target?:'_blank', children:Item[] }> — `children` required on every item (use [])",
77
+ },
65
78
  relation: {
66
79
  storage: "text (json when hasMany)",
67
80
  control: "relation picker (single dropdown, or chips + dropdown when hasMany)",
@@ -119,10 +132,10 @@ const typeSpecific = (field: FieldConfig): Record<string, unknown> => {
119
132
  };
120
133
 
121
134
  export const describeField = (name: string, field: FieldConfig): Record<string, unknown> => {
122
- // `color`/`link` are admin.component helpers over text/json — report them as
123
- // their effective semantic type so the manifest is honest about the control.
135
+ // `color`/`link`/tree editors are admin.component helpers over text/json — report
136
+ // them as their effective semantic type so the manifest is honest about the control.
124
137
  const component = field.admin?.component;
125
- const effectiveType = component === "color" || component === "link" ? component : field.type;
138
+ const effectiveType = component && component in FIELD_MODEL ? component : field.type;
126
139
  const model = FIELD_MODEL[effectiveType] ?? { storage: "json", control: "unknown", valueShape: "unknown" };
127
140
  return {
128
141
  name,
package/core/migrate.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * (internals/describe.ts) and `createCmsContext` (internals/context.ts).
7
7
  */
8
8
  import type { CMSConfig, CollectionConfig, FieldConfig } from "./define";
9
+ import { getTranslatableFieldNames } from "./define";
9
10
  import { describeModel, FIELD_MODEL, CONTENT_AST_SCHEMA } from "./field-model";
10
11
 
11
12
  export type ValidationIssue = { field: string; message: string };
@@ -58,12 +59,106 @@ const validateField = (
58
59
  case "content":
59
60
  validateContent(name, field, value, errors, warnings);
60
61
  break;
62
+ case "json": {
63
+ const component = field.admin?.component;
64
+ if (component === "taxonomy-terms" || component === "menu-items") {
65
+ if (!Array.isArray(value)) errors.push({ field: name, message: `${component} expects an array` });
66
+ else validateTree(name, component, value, warnings);
67
+ } else if (field.itemFields && Array.isArray(value)) validateRows(name, field.itemFields, value, warnings);
68
+ break;
69
+ }
70
+ case "blocks":
71
+ if (!Array.isArray(value)) errors.push({ field: name, message: "blocks expects an array" });
72
+ else validateBlockList(name, field.types, value, warnings);
73
+ break;
61
74
  case "date":
62
75
  if (Number.isNaN(Date.parse(String(value)))) warnings.push({ field: name, message: "date is not parseable" });
63
76
  break;
64
77
  }
65
78
  };
66
79
 
80
+ /**
81
+ * Nested shapes (inline/standalone block fields, repeater rows) are stored as
82
+ * the importer wrote them — the API does not re-validate them on save. Check
83
+ * them anyway so a wrong key surfaces in the report instead of as raw JSON in
84
+ * the editor, but as warnings: the top-level document still counts as valid.
85
+ */
86
+ const validateShape = (
87
+ prefix: string,
88
+ declared: Record<string, FieldConfig>,
89
+ value: Record<string, unknown>,
90
+ warnings: ValidationIssue[],
91
+ ) => {
92
+ const nested: ValidationIssue[] = [];
93
+ for (const [key, sub] of Object.entries(declared)) validateField(`${prefix}.${key}`, sub, value[key], nested, nested);
94
+ for (const key of Object.keys(value)) {
95
+ if (!(key in declared)) nested.push({ field: `${prefix}.${key}`, message: "not a declared field" });
96
+ }
97
+ warnings.push(...nested);
98
+ };
99
+
100
+ const validateRows = (
101
+ name: string,
102
+ itemFields: Record<string, FieldConfig>,
103
+ rows: unknown[],
104
+ warnings: ValidationIssue[],
105
+ ) => {
106
+ rows.forEach((row, i) => {
107
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
108
+ warnings.push({ field: `${name}[${i}]`, message: "repeater row expects an object" });
109
+ return;
110
+ }
111
+ validateShape(`${name}[${i}]`, itemFields, row as Record<string, unknown>, warnings);
112
+ });
113
+ };
114
+
115
+ const TREE_ITEM_KEYS = {
116
+ "taxonomy-terms": ["name", "slug"],
117
+ "menu-items": ["label", "href"],
118
+ } as const;
119
+
120
+ /** Tree editors (menus, taxonomy terms) need `id` + `children` on every node. */
121
+ const validateTree = (
122
+ prefix: string,
123
+ component: keyof typeof TREE_ITEM_KEYS,
124
+ items: unknown[],
125
+ warnings: ValidationIssue[],
126
+ ) => {
127
+ items.forEach((item, i) => {
128
+ const at = `${prefix}[${i}]`;
129
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
130
+ warnings.push({ field: at, message: "tree item expects an object" });
131
+ return;
132
+ }
133
+ const node = item as Record<string, unknown>;
134
+ for (const key of ["id", ...TREE_ITEM_KEYS[component]]) {
135
+ if (typeof node[key] !== "string" || !node[key])
136
+ warnings.push({ field: `${at}.${key}`, message: "expected a string" });
137
+ }
138
+ if (!Array.isArray(node.children)) {
139
+ warnings.push({ field: `${at}.children`, message: "expected an array (use [] for a leaf)" });
140
+ return;
141
+ }
142
+ validateTree(`${at}.children`, component, node.children, warnings);
143
+ });
144
+ };
145
+
146
+ const validateBlockList = (
147
+ name: string,
148
+ types: Record<string, Record<string, FieldConfig>>,
149
+ blocks: unknown[],
150
+ warnings: ValidationIssue[],
151
+ ) => {
152
+ blocks.forEach((block, i) => {
153
+ const { type, ...fields } = (block ?? {}) as { type?: string } & Record<string, unknown>;
154
+ if (!type || !(type in types)) {
155
+ warnings.push({ field: `${name}[${i}]`, message: `block type '${type}' is not declared in this field's types` });
156
+ return;
157
+ }
158
+ validateShape(`${name}[${i}]<${type}>`, types[type], fields, warnings);
159
+ });
160
+ };
161
+
67
162
  const validateContent = (
68
163
  name: string,
69
164
  field: Extract<FieldConfig, { type: "content" }>,
@@ -75,15 +170,20 @@ const validateContent = (
75
170
  errors.push({ field: name, message: "content expects { type:'root', children:[…] }" });
76
171
  return;
77
172
  }
78
- const declared = new Set(Object.keys(field.blocks ?? {}));
79
- for (const node of (value as { children?: Array<{ type?: string; blockType?: string }> }).children ?? []) {
80
- if (node?.type === "block" && node.blockType && !declared.has(node.blockType)) {
173
+ const declared = field.blocks ?? {};
174
+ const children = (value as { children?: Array<{ type?: string; blockType?: string; fields?: unknown }> }).children;
175
+ (children ?? []).forEach((node, i) => {
176
+ if (node?.type !== "block" || !node.blockType) return;
177
+ if (!(node.blockType in declared)) {
81
178
  warnings.push({
82
179
  field: name,
83
180
  message: `inline block '${node.blockType}' is not declared in this field's blocks`,
84
181
  });
182
+ return;
85
183
  }
86
- }
184
+ const fields = node.fields && typeof node.fields === "object" ? (node.fields as Record<string, unknown>) : {};
185
+ validateShape(`${name}[${i}]<${node.blockType}>`, declared[node.blockType], fields, warnings);
186
+ });
87
187
  };
88
188
 
89
189
  /** Validate a document's fields against its collection schema. */
@@ -100,6 +200,61 @@ export const validateDocument = (collection: CollectionConfig, data: Record<stri
100
200
  return { ok: errors.length === 0, errors, warnings };
101
201
  };
102
202
 
203
+ /**
204
+ * Validate an import item's per-locale overlays. Translation tables only exist
205
+ * for fields marked `translatable: true`, and `upsertTranslation` silently drops
206
+ * everything else — so catch both here, before the base document is written.
207
+ */
208
+ export const validateTranslations = (
209
+ config: CMSConfig,
210
+ collection: CollectionConfig,
211
+ translations: Record<string, Record<string, unknown>> | undefined,
212
+ ): ValidationResult => {
213
+ const errors: ValidationIssue[] = [];
214
+ const warnings: ValidationIssue[] = [];
215
+ const locales = Object.keys(translations ?? {});
216
+ if (locales.length === 0) return { ok: true, errors, warnings };
217
+
218
+ const translatable = new Set(getTranslatableFieldNames(collection));
219
+ if (!config.locales || translatable.size === 0) {
220
+ errors.push({
221
+ field: "translations",
222
+ message: !config.locales
223
+ ? "no locales configured (set `locales` in cms.config.ts)"
224
+ : `collection has no translatable fields (mark them \`translatable: true\`, then cms:generate + cms:push)`,
225
+ });
226
+ return { ok: false, errors, warnings };
227
+ }
228
+
229
+ for (const locale of locales) {
230
+ const prefix = `translations.${locale}`;
231
+ if (locale === config.locales.default) {
232
+ errors.push({ field: prefix, message: `'${locale}' is the default locale — put it in \`data\`` });
233
+ continue;
234
+ }
235
+ if (!config.locales.supported.includes(locale)) {
236
+ errors.push({ field: prefix, message: `'${locale}' is not in locales.supported` });
237
+ continue;
238
+ }
239
+ const overlay = translations![locale] ?? {};
240
+ const keys = Object.keys(overlay).filter((k) => !k.startsWith("_"));
241
+ const kept = keys.filter((k) => translatable.has(k));
242
+ for (const key of keys) {
243
+ if (!translatable.has(key))
244
+ warnings.push({ field: `${prefix}.${key}`, message: "not a translatable field (will be dropped)" });
245
+ }
246
+ if (keys.length && kept.length === 0) {
247
+ errors.push({
248
+ field: prefix,
249
+ message: "none of these fields are translatable — the whole translation would be dropped",
250
+ });
251
+ continue;
252
+ }
253
+ for (const key of kept) validateField(`${prefix}.${key}`, collection.fields[key], overlay[key], errors, warnings);
254
+ }
255
+ return { ok: errors.length === 0, errors, warnings };
256
+ };
257
+
103
258
  // ---------------------------------------------------------------------------
104
259
  // Batch loader (import IR → CMS) with dry-run + validation report.
105
260
  // ---------------------------------------------------------------------------
@@ -173,10 +328,13 @@ export const importDocuments = async (
173
328
  report.failed++;
174
329
  continue;
175
330
  }
176
- const result = validateDocument(collection, item.data);
177
- if (result.warnings.length) report.warnings.push({ collection: item.collection, id, warnings: result.warnings });
178
- if (!result.ok) {
179
- report.invalid.push({ collection: item.collection, id, errors: result.errors });
331
+ const doc = validateDocument(collection, item.data);
332
+ const i18n = validateTranslations(config, collection, item.translations);
333
+ const warnings = [...doc.warnings, ...i18n.warnings];
334
+ const errors = [...doc.errors, ...i18n.errors];
335
+ if (warnings.length) report.warnings.push({ collection: item.collection, id, warnings });
336
+ if (errors.length) {
337
+ report.invalid.push({ collection: item.collection, id, errors });
180
338
  report.failed++;
181
339
  continue;
182
340
  }
@@ -235,6 +393,10 @@ export const renderModelMarkdown = (config: CMSConfig): string => {
235
393
  out.push("");
236
394
  out.push(`**Locales:** default \`${model.locales.default}\`, supported \`${model.locales.supported.join(", ")}\``);
237
395
  out.push("");
396
+ out.push("> The **i18n** column is `yes` only for fields declared `translatable: true`. Only those");
397
+ out.push("> fields accept per-locale values (`translations` in an import item, `upsertTranslation`);");
398
+ out.push("> everything else is base-locale only. A collection with no `yes` has no translation table.");
399
+ out.push("");
238
400
 
239
401
  out.push("## Field types");
240
402
  out.push("");
@@ -252,8 +414,9 @@ export const renderModelMarkdown = (config: CMSConfig): string => {
252
414
  out.push(`root: ${CONTENT_AST_SCHEMA.root}`);
253
415
  for (const [k, v] of Object.entries(CONTENT_AST_SCHEMA.nodes)) out.push(` ${k}: ${v}`);
254
416
  out.push("```");
255
- out.push("> A `content` field stores any `{type:'root'}` doc as-is — inline block `fields` are not");
256
- out.push("> validated. Build prose with `htmlToRichText(html)`; declare `blocks` for the editor.");
417
+ out.push("> A `content` field stores any `{type:'root'}` doc as-is — the API does not check inline");
418
+ out.push("> block `fields` on save, but `load({ dryRun: true })` reports mismatches as warnings.");
419
+ out.push("> Build prose with `htmlToRichText(html)`; declare `blocks` for the editor.");
257
420
  out.push("");
258
421
 
259
422
  for (const collection of model.collections) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.24.0",
3
+ "version": "0.25.1",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",