@kidecms/core 0.25.0 → 0.26.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.
package/core/migrate.ts CHANGED
@@ -59,9 +59,14 @@ const validateField = (
59
59
  case "content":
60
60
  validateContent(name, field, value, errors, warnings);
61
61
  break;
62
- case "json":
63
- if (field.itemFields && Array.isArray(value)) validateRows(name, field.itemFields, value, warnings);
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);
64
68
  break;
69
+ }
65
70
  case "blocks":
66
71
  if (!Array.isArray(value)) errors.push({ field: name, message: "blocks expects an array" });
67
72
  else validateBlockList(name, field.types, value, warnings);
@@ -107,6 +112,37 @@ const validateRows = (
107
112
  });
108
113
  };
109
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
+
110
146
  const validateBlockList = (
111
147
  name: string,
112
148
  types: Record<string, Record<string, FieldConfig>>,
@@ -151,12 +187,24 @@ const validateContent = (
151
187
  };
152
188
 
153
189
  /** Validate a document's fields against its collection schema. */
154
- export const validateDocument = (collection: CollectionConfig, data: Record<string, unknown>): ValidationResult => {
190
+ export const validateDocument = (
191
+ collection: CollectionConfig,
192
+ data: Record<string, unknown>,
193
+ config?: CMSConfig,
194
+ ): ValidationResult => {
155
195
  const errors: ValidationIssue[] = [];
156
196
  const warnings: ValidationIssue[] = [];
157
197
  for (const [name, field] of Object.entries(collection.fields)) {
158
198
  validateField(name, field, data[name], errors, warnings);
159
199
  }
200
+ if (data._sourceLocale !== undefined && data._sourceLocale !== null && data._sourceLocale !== "") {
201
+ const locale = String(data._sourceLocale);
202
+ if (!config?.locales) errors.push({ field: "_sourceLocale", message: "no locales configured" });
203
+ else if (!config.locales.supported.includes(locale))
204
+ errors.push({ field: "_sourceLocale", message: `'${locale}' is not in locales.supported` });
205
+ else if (getTranslatableFieldNames(collection).length === 0)
206
+ warnings.push({ field: "_sourceLocale", message: "collection has no translatable fields (ignored)" });
207
+ }
160
208
  for (const key of Object.keys(data)) {
161
209
  if (key.startsWith("_")) continue;
162
210
  if (!(key in collection.fields)) warnings.push({ field: key, message: "not a declared field (will be ignored)" });
@@ -173,6 +221,7 @@ export const validateTranslations = (
173
221
  config: CMSConfig,
174
222
  collection: CollectionConfig,
175
223
  translations: Record<string, Record<string, unknown>> | undefined,
224
+ sourceLocale?: unknown,
176
225
  ): ValidationResult => {
177
226
  const errors: ValidationIssue[] = [];
178
227
  const warnings: ValidationIssue[] = [];
@@ -190,10 +239,11 @@ export const validateTranslations = (
190
239
  return { ok: false, errors, warnings };
191
240
  }
192
241
 
242
+ const base = sourceLocale ? String(sourceLocale) : config.locales.default;
193
243
  for (const locale of locales) {
194
244
  const prefix = `translations.${locale}`;
195
- if (locale === config.locales.default) {
196
- errors.push({ field: prefix, message: `'${locale}' is the default locale — put it in \`data\`` });
245
+ if (locale === base) {
246
+ errors.push({ field: prefix, message: `'${locale}' is the document's content language — put it in \`data\`` });
197
247
  continue;
198
248
  }
199
249
  if (!config.locales.supported.includes(locale)) {
@@ -292,8 +342,8 @@ export const importDocuments = async (
292
342
  report.failed++;
293
343
  continue;
294
344
  }
295
- const doc = validateDocument(collection, item.data);
296
- const i18n = validateTranslations(config, collection, item.translations);
345
+ const doc = validateDocument(collection, item.data, config);
346
+ const i18n = validateTranslations(config, collection, item.translations, item.data._sourceLocale);
297
347
  const warnings = [...doc.warnings, ...i18n.warnings];
298
348
  const errors = [...doc.errors, ...i18n.errors];
299
349
  if (warnings.length) report.warnings.push({ collection: item.collection, id, warnings });
@@ -360,6 +410,11 @@ export const renderModelMarkdown = (config: CMSConfig): string => {
360
410
  out.push("> The **i18n** column is `yes` only for fields declared `translatable: true`. Only those");
361
411
  out.push("> fields accept per-locale values (`translations` in an import item, `upsertTranslation`);");
362
412
  out.push("> everything else is base-locale only. A collection with no `yes` has no translation table.");
413
+ out.push(`> Every document has \`_sourceLocale\` — the language its base row is written in (default`);
414
+ out.push(`> \`${model.locales.default}\`). A document exists in its source locale plus every locale it has a`);
415
+ out.push(
416
+ "> translation for; content that only exists in one language is a base doc in that language with no overlay.",
417
+ );
363
418
  out.push("");
364
419
 
365
420
  out.push("## Field types");
package/core/values.ts CHANGED
@@ -211,7 +211,9 @@ const walkBlocks = (el: HtmlEl, out: RichTextNode[]): void => {
211
211
  const leaves = inlineChildren(child.children);
212
212
  if (meaningful(leaves)) out.push({ type: "paragraph", children: leaves });
213
213
  } else if (/^h[1-6]$/.test(tag)) {
214
- const leaves = inlineChildren(child.children);
214
+ // Headings render bold already; a <strong> inside one (WordPress does this)
215
+ // would only leave the editor's Bold toggle lit for no visible reason.
216
+ const leaves = inlineChildren(child.children).map(({ bold: _bold, ...leaf }) => leaf);
215
217
  if (meaningful(leaves)) out.push({ type: "heading", level: Number(tag[1]), children: leaves });
216
218
  } else if (tag === "ul" || tag === "ol") {
217
219
  const items = child.children
@@ -77,19 +77,19 @@ const ops: Record<string, (args: OpArgs) => unknown> = {
77
77
 
78
78
  describeCollection: ({ collection }) => collectionModel(collection),
79
79
 
80
- listDocuments: async ({ collection, where, search, sort, limit, offset, status, locale }) => {
80
+ listDocuments: async ({ collection, where, search, sort, limit, offset, status, locale, availability }) => {
81
81
  const collectionApi = getCollectionApi(collection);
82
- const options = { where, search, sort, limit, offset, status, locale };
82
+ const options = { where, search, sort, limit, offset, status, locale, availability };
83
83
  const [docs, totalDocs] = await Promise.all([
84
84
  collectionApi.find(options, runtimeContext()),
85
- collectionApi.count({ where, search, status, locale }, runtimeContext()),
85
+ collectionApi.count({ where, search, status, locale, availability }, runtimeContext()),
86
86
  ]);
87
87
  return { docs, totalDocs, limit, offset };
88
88
  },
89
89
 
90
- countDocuments: async ({ collection, where, search, status, locale }) => {
90
+ countDocuments: async ({ collection, where, search, status, locale, availability }) => {
91
91
  const collectionApi = getCollectionApi(collection);
92
- const totalDocs = await collectionApi.count({ where, search, status, locale }, runtimeContext());
92
+ const totalDocs = await collectionApi.count({ where, search, status, locale, availability }, runtimeContext());
93
93
  return { totalDocs };
94
94
  },
95
95
 
package/internals/mcp.ts CHANGED
@@ -199,7 +199,7 @@ server.registerTool(
199
199
  {
200
200
  title: "List documents",
201
201
  description:
202
- "List documents in a collection with optional filters, search, sort, locale, status, limit, and offset.",
202
+ "List documents in a collection with optional filters, search, sort, locale, status, limit, and offset. With locale, availability 'exact' lists only documents that exist in that locale (their _sourceLocale or a translation); the default 'fallback' lists every document.",
203
203
  inputSchema: {
204
204
  collection: z.string().min(1),
205
205
  where: jsonObjectSchema.optional(),
@@ -209,6 +209,7 @@ server.registerTool(
209
209
  offset: z.number().int().min(0).default(0),
210
210
  status: statusSchema.optional(),
211
211
  locale: z.string().min(1).optional(),
212
+ availability: z.enum(["fallback", "exact"]).optional(),
212
213
  },
213
214
  },
214
215
  async (args) => toResult(await workerCall("listDocuments", args)),
@@ -225,6 +226,7 @@ server.registerTool(
225
226
  search: z.string().optional(),
226
227
  status: statusSchema.optional(),
227
228
  locale: z.string().min(1).optional(),
229
+ availability: z.enum(["fallback", "exact"]).optional(),
228
230
  },
229
231
  },
230
232
  async (args) => toResult(await workerCall("countDocuments", args)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
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",
@@ -90,7 +90,7 @@ const extractDataFromForm = async (request: Request) => {
90
90
  data: Object.fromEntries(
91
91
  entries.filter(
92
92
  ([key]) =>
93
- (!key.startsWith("_") || key === "_publishAt" || key === "_unpublishAt") &&
93
+ (!key.startsWith("_") || key === "_publishAt" || key === "_unpublishAt" || key === "_sourceLocale") &&
94
94
  key !== "redirectTo" &&
95
95
  key !== "locale" &&
96
96
  key !== "version",
@@ -74,6 +74,9 @@ export const GET: APIRoute = async ({ url, locals }) => {
74
74
  (c) => requested.includes(c.slug) && !HIDDEN_FROM_SEARCH.has(c.slug),
75
75
  );
76
76
  const results: SearchResult[] = [];
77
+ // Pickers say so when the list is cut off, so 20 rows don't read as "all
78
+ // there is" — one extra row tells us without a count query.
79
+ let hasMore = false;
77
80
 
78
81
  for (const collection of collections) {
79
82
  const api = cmsAny[collection.slug];
@@ -92,15 +95,20 @@ export const GET: APIRoute = async ({ url, locals }) => {
92
95
  // Recently-updated first in both modes — without a sort, LIMIT keeps an
93
96
  // arbitrary subset of the matches.
94
97
  const sort = { field: "_updatedAt", direction: "desc" } as const;
95
- if (q.length >= MIN_QUERY_LENGTH) return api.find({ search: q, status: "any", sort, limit }, context);
96
- return api.find({ status: "any", sort, limit }, context);
98
+ const probe = limit + 1;
99
+ const found =
100
+ q.length >= MIN_QUERY_LENGTH
101
+ ? await api.find({ search: q, status: "any", sort, limit: probe }, context)
102
+ : await api.find({ status: "any", sort, limit: probe }, context);
103
+ if (found.length > limit) hasMore = true;
104
+ return found.slice(0, limit);
97
105
  })().catch(() => null);
98
106
 
99
107
  if (!docs) continue;
100
108
  for (const doc of docs) results.push(toResult(collection, doc));
101
109
  }
102
110
 
103
- return Response.json({ results });
111
+ return Response.json({ results, hasMore });
104
112
  }
105
113
 
106
114
  // Palette mode: everything, a few hits per collection.