@kidecms/core 0.29.3 → 0.30.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.
@@ -0,0 +1,52 @@
1
+ // React-free helpers for block values, shared by the block editors (re-exported
2
+ // from block-fields.tsx) and unit-tested directly.
3
+ import type { SubFieldMeta } from "./block-fields";
4
+
5
+ /** Build a blank value object for a freshly inserted block of the given type. */
6
+ export function blankBlockFields(fieldsMeta: Record<string, SubFieldMeta>): Record<string, unknown> {
7
+ const out: Record<string, unknown> = {};
8
+ for (const [fieldName, meta] of Object.entries(fieldsMeta)) {
9
+ if (meta.defaultValue !== undefined) out[fieldName] = meta.defaultValue;
10
+ else if (meta.type === "boolean") out[fieldName] = false;
11
+ else if (meta.type === "array" || meta.type === "blocks") out[fieldName] = [];
12
+ else out[fieldName] = "";
13
+ }
14
+ return out;
15
+ }
16
+
17
+ type PreviewNode = { value?: unknown; children?: PreviewNode[] };
18
+
19
+ const richTextPreview = (value: unknown): string => {
20
+ let doc = value;
21
+ if (typeof doc === "string") {
22
+ try {
23
+ doc = JSON.parse(doc);
24
+ } catch {
25
+ return "";
26
+ }
27
+ }
28
+ const collect = (node: PreviewNode): string =>
29
+ typeof node.value === "string" ? node.value : (node.children ?? []).map(collect).join(" ");
30
+ return doc && typeof doc === "object" ? collect(doc as PreviewNode).replace(/\s+/g, " ").trim() : "";
31
+ };
32
+
33
+ /**
34
+ * Collapsed block/row preview: the first text or rich-text value, else the first
35
+ * image's file name — so a text-less block (an image, a video) still says what it holds.
36
+ */
37
+ export function getPreviewText(values: Record<string, unknown>, fieldsMeta: Record<string, SubFieldMeta>): string {
38
+ const clip = (text: string) => (text.length > 60 ? text.slice(0, 60) + "..." : text);
39
+ for (const [key, meta] of Object.entries(fieldsMeta)) {
40
+ if (meta.type === "text" && values[key]) return clip(String(values[key]));
41
+ if (meta.type === "richText") {
42
+ const text = richTextPreview(values[key]);
43
+ if (text) return clip(text);
44
+ }
45
+ }
46
+ for (const [key, meta] of Object.entries(fieldsMeta)) {
47
+ if (meta.type === "image" && typeof values[key] === "string" && values[key]) {
48
+ return String(values[key]).split("/").pop() ?? "";
49
+ }
50
+ }
51
+ return "";
52
+ }
@@ -246,7 +246,7 @@ for (const c of navCollections) {
246
246
  href: `/admin/${c.slug}`,
247
247
  label: c.labels.plural,
248
248
  singularLabel: c.labels.singular,
249
- Icon: c.admin?.icon ? (navIconMap[c.admin.icon] ?? LayoutGrid) : (pinnedIcons[c.slug] ?? Layers),
249
+ Icon: c.admin?.icon ? (navIconMap[c.admin.icon] ?? Layers) : (pinnedIcons[c.slug] ?? Layers),
250
250
  active: activeCollection === c.slug,
251
251
  // Submissions are created by end users filling out forms, not added manually.
252
252
  newHref: c.slug === "form-submissions" ? undefined : `/admin/${c.slug}/new`,
@@ -282,7 +282,7 @@ for (const item of customNav) {
282
282
  navItems.push({
283
283
  href: item.href,
284
284
  label: item.label,
285
- Icon: navIconMap[item.icon ?? ""] ?? LayoutGrid,
285
+ Icon: navIconMap[item.icon ?? ""] ?? Layers,
286
286
  active: currentPath === item.href || currentPath.startsWith(item.href + "/"),
287
287
  weight: item.weight ?? 50,
288
288
  group: "Custom",
@@ -550,6 +550,46 @@ const navGroups = [...new Set(navItems.map((item) => item.group))]
550
550
 
551
551
  {toastStatus && <Toast status={toastStatus} message={toastMessage} />}
552
552
 
553
+ {/* Shown when an editor island fails to hydrate, so a failed load never looks like empty content. */}
554
+ <div
555
+ id="admin-hydration-error"
556
+ role="alert"
557
+ hidden
558
+ class="border-destructive/40 bg-background text-foreground fixed inset-x-4 bottom-4 z-[100] mx-auto max-w-xl rounded-lg border px-4 py-3 text-sm shadow-lg"
559
+ >
560
+ <p class="font-medium">Some editors failed to load.</p>
561
+ <p class="text-muted-foreground mt-1">
562
+ Fields may look empty, but your content is safe — don't save this page. Reload to try again.
563
+ {
564
+ import.meta.env.DEV && (
565
+ <>
566
+ {" "}
567
+ If it keeps happening, stop the dev server and restart it with <code>pnpm dev:clean</code>, and check its
568
+ log for a <code>[kide-cms]</code> warning about duplicate packages.
569
+ </>
570
+ )
571
+ }
572
+ </p>
573
+ </div>
574
+ <script is:inline>
575
+ (function () {
576
+ // Astro removes `ssr` from an island once it hydrates; a client:load island
577
+ // still carrying it well after the page has loaded failed to import.
578
+ function check() {
579
+ var failed = document.querySelectorAll('astro-island[ssr][client="load"]');
580
+ if (failed.length === 0) return;
581
+ var banner = document.getElementById("admin-hydration-error");
582
+ if (banner) banner.hidden = false;
583
+ console.error("[kide] " + failed.length + " admin editor(s) failed to hydrate.", failed);
584
+ }
585
+ function schedule() {
586
+ setTimeout(check, 5000);
587
+ }
588
+ if (document.readyState === "complete") schedule();
589
+ else window.addEventListener("load", schedule, { once: true });
590
+ })();
591
+ </script>
592
+
553
593
  {/* Persist collapsible sidebar groups locally. Active groups always open. */}
554
594
  <script is:inline>
555
595
  (function () {
@@ -180,7 +180,7 @@ const hasSidebarFields =
180
180
  effectiveSidebarFieldSets.some((set) =>
181
181
  set.fields.some((fieldName) => collection.fields[fieldName] && !isFieldHidden(fieldName)),
182
182
  ) ||
183
- (hasLocales && !translationMode);
183
+ (hasLocales && mode === "new");
184
184
  const hasSidebarMeta = reverseRefs.length > 0 || hasDocMeta;
185
185
 
186
186
  // Whether to render the right-hand sidebar column at all (avoids a stray sticky
@@ -236,7 +236,7 @@ const publishBlocked =
236
236
  >
237
237
  <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
238
238
  <div class="min-w-0 flex-1">
239
- <div class="flex items-center gap-2.5">
239
+ <div class="flex items-center gap-2.5" data-kide-refresh="title">
240
240
  <h1 class="truncate text-lg font-semibold tracking-tight md:text-xl">
241
241
  {mode === "new" && <LiveHeading client:load initial={`New ${collection.labels.singular}`} />}
242
242
  {
@@ -267,7 +267,7 @@ const publishBlocked =
267
267
 
268
268
  {
269
269
  formTab !== "submissions" && (
270
- <div class="flex flex-wrap items-center gap-2 sm:flex-shrink-0 sm:justify-end">
270
+ <div class="flex flex-wrap items-center gap-2 sm:flex-shrink-0 sm:justify-end" data-kide-refresh="actions">
271
271
  {hasPreview && previewUrl && !translationMode && (
272
272
  <>
273
273
  <a href={previewUrl} target="_blank" class={buttonVariants({ variant: "outline" })}>
@@ -279,28 +279,32 @@ const publishBlocked =
279
279
  )}
280
280
  {hasLocales && mode === "edit" && (
281
281
  <>
282
- {locales.map((locale) => (
283
- <a
284
- href={`/admin/${collection.slug}/${documentId}?locale=${locale}`}
285
- title={
286
- locale === baseLocale
287
- ? "Content language"
288
- : availableLocales.has(locale)
289
- ? undefined
290
- : "Not translated yet"
291
- }
292
- class:list={[
293
- buttonVariants({ variant: "outline", size: "sm" }),
294
- selectedLocale === locale
295
- ? "border-primary/50 bg-background ring-ring/30 font-medium ring-2"
296
- : availableLocales.has(locale)
297
- ? "text-muted-foreground"
298
- : "text-muted-foreground/50 border-dashed",
299
- ]}
300
- >
301
- {locale.toUpperCase()}
302
- </a>
303
- ))}
282
+ {/* One segmented control: the language being edited is the raised segment. */}
283
+ <div class="bg-muted inline-flex h-8 items-center gap-0.5 rounded-lg border p-0.5">
284
+ {locales.map((locale) => (
285
+ <a
286
+ href={`/admin/${collection.slug}/${documentId}?locale=${locale}`}
287
+ title={
288
+ locale === baseLocale
289
+ ? "Original language"
290
+ : availableLocales.has(locale)
291
+ ? undefined
292
+ : "Not translated yet"
293
+ }
294
+ aria-current={selectedLocale === locale ? "page" : undefined}
295
+ class:list={[
296
+ "inline-flex h-full min-w-9 items-center justify-center rounded-md px-2.5 text-xs font-medium transition-colors",
297
+ selectedLocale === locale
298
+ ? "bg-background text-foreground shadow-sm"
299
+ : availableLocales.has(locale)
300
+ ? "text-muted-foreground hover:text-foreground"
301
+ : "text-muted-foreground/50 hover:text-muted-foreground",
302
+ ]}
303
+ >
304
+ {locale.toUpperCase()}
305
+ </a>
306
+ ))}
307
+ </div>
304
308
  <div class="bg-border mx-1 h-6 w-px" />
305
309
  </>
306
310
  )}
@@ -387,6 +391,14 @@ const publishBlocked =
387
391
  currentPublishAt={doc?._publishAt ? String(doc._publishAt) : undefined}
388
392
  currentUnpublishAt={doc?._unpublishAt ? String(doc._unpublishAt) : undefined}
389
393
  versions={versions}
394
+ languages={
395
+ // Only while the document exists in one language: a translation would
396
+ // collide with the new original language, so the API refuses the change.
397
+ hasLocales && availableLocales.size === 1
398
+ ? locales.map((locale) => ({ value: locale, label: locale.toUpperCase() }))
399
+ : undefined
400
+ }
401
+ contentLanguage={baseLocale}
390
402
  restoreEndpoint={getFormAction(collection.slug, documentId)}
391
403
  redirectTo={Astro.url.pathname + Astro.url.search}
392
404
  />
@@ -408,7 +420,7 @@ const publishBlocked =
408
420
  }
409
421
  {
410
422
  showCollab && collabData && documentId && (
411
- <div class="-mt-6 mb-8 2xl:-mx-8">
423
+ <div class="-mt-6 mb-8 2xl:-mx-8" data-kide-refresh="collab">
412
424
  <CollaborationReviewBar
413
425
  client:load
414
426
  collection={collection.slug}
@@ -430,16 +442,20 @@ const publishBlocked =
430
442
  {mode === "edit" && documentId && (
431
443
  <DocumentLock client:load collection={collection.slug} documentId={documentId} />
432
444
  )}
433
- <UnsavedGuard
434
- client:load
435
- formId={translationMode ? "translation-form" : "document-form"}
436
- isNew={mode === "new"}
437
- isDraft={Boolean(
438
- !translationMode &&
439
- collection.drafts &&
440
- (doc?._status === "draft" || doc?._status === "scheduled" || (doc && getVisualStatus(doc) === "changed")),
441
- )}
442
- />
445
+ <div class="contents" data-kide-refresh="guard">
446
+ <UnsavedGuard
447
+ client:load
448
+ formId={translationMode ? "translation-form" : "document-form"}
449
+ isNew={mode === "new"}
450
+ isDraft={Boolean(
451
+ !translationMode &&
452
+ collection.drafts &&
453
+ (doc?._status === "draft" ||
454
+ doc?._status === "scheduled" ||
455
+ (doc && getVisualStatus(doc) === "changed")),
456
+ )}
457
+ />
458
+ </div>
443
459
  <div id="document-edit-area" data-preview-channel={!translationMode ? previewKey : undefined}>
444
460
  {collection.slug === "users" && mode === "edit" && Astro.url.searchParams.get("inviteToken") && (
445
461
  <AdminCard title={Astro.url.searchParams.get("emailSent") === "true" ? "Invitation sent" : "Invite link"}>
@@ -615,10 +631,13 @@ const publishBlocked =
615
631
  );
616
632
  return variant === "record" ? <AdminCard title="Settings">{fields}</AdminCard> : fields;
617
633
  })}
618
- {hasLocales && !translationMode && !isSubmissionView && (
634
+ {/* The language is chosen when the document is created; afterwards the
635
+ top switcher is the one language control (changing it later lives
636
+ in the ⋯ menu, offered only while no translation exists). */}
637
+ {hasLocales && mode === "new" && !isSubmissionView && (
619
638
  <div class="grid gap-1.5">
620
639
  <label for="_sourceLocale" class="text-foreground/80 text-sm leading-none font-medium">
621
- Content language
640
+ Language
622
641
  </label>
623
642
  <SelectField
624
643
  client:load
@@ -627,11 +646,14 @@ const publishBlocked =
627
646
  placeholder="Select a language"
628
647
  items={locales.map((locale) => ({ value: locale, label: locale.toUpperCase() }))}
629
648
  />
630
- <p class="text-muted-foreground text-xs">The language this document is written in.</p>
649
+ <p class="text-muted-foreground text-xs">
650
+ The language this document is written in. Translations can be added after saving.
651
+ </p>
631
652
  </div>
632
653
  )}
633
654
  {hasSidebarMeta && (
634
655
  <div
656
+ data-kide-refresh="meta"
635
657
  class:list={[
636
658
  variant === "record" ? "space-y-6" : "grid gap-6",
637
659
  variant !== "record" && hasSidebarFields && "border-t pt-6",
@@ -42,6 +42,35 @@ const locales = config.locales?.supported ?? [];
42
42
  // and this collection actually has translatable fields to show per-locale.
43
43
  const showLocalesColumn = locales.length > 1 && getTranslatableFieldNames(collection).length > 0;
44
44
 
45
+ // Language filter (?lang=en → documents that exist in English, shown in English;
46
+ // ?lang=missing:en → documents not translated to English yet). Only offered when
47
+ // the collection is actually multilingual.
48
+ const langParam = showLocalesColumn ? (Astro.url.searchParams.get("lang") ?? "") : "";
49
+ const missingLocale = langParam.startsWith("missing:") ? langParam.slice("missing:".length) : "";
50
+ const langFilter = locales.includes(langParam)
51
+ ? { locale: langParam, availability: "exact" as const }
52
+ : locales.includes(missingLocale)
53
+ ? { locale: missingLocale, availability: "missing" as const }
54
+ : null;
55
+ const langHref = (value: string) => {
56
+ const url = new URL(Astro.url);
57
+ if (value) url.searchParams.set("lang", value);
58
+ else url.searchParams.delete("lang");
59
+ url.searchParams.delete("page");
60
+ return url.pathname + url.search;
61
+ };
62
+ // "fi" → "Finnish" (the admin UI is English); unknown codes fall back to the code.
63
+ const languageNames = new Intl.DisplayNames(["en"], { type: "language", fallback: "code" });
64
+ const languageName = (locale: string) => languageNames.of(locale) ?? locale.toUpperCase();
65
+ const langOptions = [
66
+ { value: "", label: "All languages" },
67
+ ...locales.map((locale) => ({ value: locale, label: `In ${languageName(locale)}` })),
68
+ ...locales
69
+ .filter((locale) => locale !== defaultLocale)
70
+ .map((locale) => ({ value: `missing:${locale}`, label: `Missing ${languageName(locale)}` })),
71
+ ].map((option) => ({ ...option, href: langHref(option.value) }));
72
+ const activeLang = langFilter ? langParam : "";
73
+
45
74
  const viewConfig = collection.views ?? {};
46
75
  const defaultSort = viewConfig.list?.defaultSort ?? { field: "_updatedAt", direction: "desc" };
47
76
  const sortParam = Astro.url.searchParams.get("sort");
@@ -58,7 +87,8 @@ const [docs, totalDocs] = await Promise.all([
58
87
  collectionApi.find(
59
88
  {
60
89
  status: "any",
61
- locale: defaultLocale,
90
+ locale: langFilter?.locale ?? defaultLocale,
91
+ availability: langFilter?.availability,
62
92
  sort: currentSort,
63
93
  limit: PAGE_SIZE,
64
94
  offset,
@@ -66,7 +96,15 @@ const [docs, totalDocs] = await Promise.all([
66
96
  },
67
97
  runtimeContext,
68
98
  ),
69
- collectionApi.count({ status: "any", locale: defaultLocale, search: searchParam || undefined }, runtimeContext),
99
+ collectionApi.count(
100
+ {
101
+ status: "any",
102
+ locale: langFilter?.locale ?? defaultLocale,
103
+ availability: langFilter?.availability,
104
+ search: searchParam || undefined,
105
+ },
106
+ runtimeContext,
107
+ ),
70
108
  ]);
71
109
  const totalPages = Math.max(1, Math.ceil(totalDocs / PAGE_SIZE));
72
110
 
@@ -169,7 +207,8 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
169
207
  const pagePath = getPagePath(entry);
170
208
  return {
171
209
  id: String(entry._id),
172
- editHref: `/admin/${collection.slug}/${entry._id}`,
210
+ // Filtered by a language: open that language's tab (for "Missing …", the translation form).
211
+ editHref: `/admin/${collection.slug}/${entry._id}${langFilter ? `?locale=${langFilter.locale}` : ""}`,
173
212
  status: getVisualStatus(entry),
174
213
  locales: Array.isArray(entry._availableLocales) ? entry._availableLocales.map((l) => String(l)) : [defaultLocale],
175
214
  searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
@@ -212,6 +251,7 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
212
251
  }))}
213
252
  data={tableRows}
214
253
  searchPlaceholder={`Filter ${collection.labels.plural.toLowerCase()}...`}
254
+ languageFilter={showLocalesColumn ? { active: activeLang, options: langOptions } : undefined}
215
255
  serverPagination={{
216
256
  totalDocs,
217
257
  totalPages,
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  // Client-side glue for the edit form: conditional field visibility, autofocus on new,
3
- // AJAX form submit (so validation errors surface as toasts without losing form state),
3
+ // AJAX form submit (validation errors surface as toasts, and a successful save updates
4
+ // the page in place instead of reloading it),
4
5
  // and collapsible field-group state persistence.
5
6
  ---
6
7
 
@@ -167,6 +168,68 @@
167
168
  return false;
168
169
  }
169
170
 
171
+ // Values a field shows after saving, as the server rendered them. JSON-backed fields
172
+ // (blocks, rich text, relations) are skipped — their serialization isn't stable
173
+ // across renders, and the server doesn't rewrite them.
174
+ function plainValues(form) {
175
+ var out = {};
176
+ new FormData(form).forEach(function (value, name) {
177
+ if (name.charAt(0) === "_" || name === "redirectTo" || typeof value !== "string") return;
178
+ var trimmed = value.trim();
179
+ if (trimmed.charAt(0) === "{" || trimmed.charAt(0) === "[") return;
180
+ out[name] = (out[name] ? out[name] + "\u0000" : "") + value;
181
+ });
182
+ return out;
183
+ }
184
+
185
+ // Replaces the [data-kide-refresh] regions (title + status, header actions, review
186
+ // bar, unsaved-changes guard, sidebar info) with the freshly rendered ones and shows
187
+ // the response's toast. Returns false — so the caller reloads instead — when the
188
+ // server changed a field value (e.g. a hook rewrote the slug) or the page structure.
189
+ function swapInPlace(form, html) {
190
+ var next = new DOMParser().parseFromString(html, "text/html");
191
+ var nextForm = next.getElementById("document-form");
192
+ if (!nextForm) return false;
193
+
194
+ var mine = plainValues(form);
195
+ var theirs = plainValues(nextForm);
196
+ for (var name in theirs) {
197
+ if (name in mine && mine[name] !== theirs[name]) return false;
198
+ }
199
+
200
+ var regions = document.querySelectorAll("[data-kide-refresh]");
201
+ var nextRegions = next.querySelectorAll("[data-kide-refresh]");
202
+ if (regions.length !== nextRegions.length) return false;
203
+ var byName = {};
204
+ nextRegions.forEach(function (el) {
205
+ byName[el.getAttribute("data-kide-refresh")] = el;
206
+ });
207
+ for (var i = 0; i < regions.length; i++) {
208
+ if (!byName[regions[i].getAttribute("data-kide-refresh")]) return false;
209
+ }
210
+
211
+ regions.forEach(function (el) {
212
+ // Unmount the React islands first so their listeners (e.g. the unsaved-changes
213
+ // guard) go away; the imported islands hydrate themselves when connected.
214
+ el.querySelectorAll("astro-island").forEach(function (island) {
215
+ island.dispatchEvent(new CustomEvent("astro:unmount"));
216
+ });
217
+ el.replaceWith(document.importNode(byName[el.getAttribute("data-kide-refresh")], true));
218
+ });
219
+
220
+ var toast = next.getElementById("admin-toast");
221
+ if (toast && toast.parentElement) {
222
+ var current = document.getElementById("admin-toast");
223
+ if (current && current.parentElement) current.parentElement.remove();
224
+ var wrapper = document.importNode(toast.parentElement, true);
225
+ document.body.appendChild(wrapper);
226
+ setTimeout(function () {
227
+ wrapper.remove();
228
+ }, 3200);
229
+ }
230
+ return true;
231
+ }
232
+
170
233
  (function () {
171
234
  var form = document.getElementById("document-form");
172
235
  if (!form) return;
@@ -212,7 +275,30 @@
212
275
  return;
213
276
  }
214
277
  }
215
- window.location.assign(res.url);
278
+ // Saving an existing document keeps the page: only the parts a save can change are
279
+ // swapped in from the response, so open blocks, scroll, focus and undo survive.
280
+ var intent = sub && sub.name === "_intent" ? sub.value : "";
281
+ var inPlace =
282
+ u.searchParams.get("_toast") === "success" &&
283
+ u.pathname === location.pathname &&
284
+ f.querySelector('input[name="_action"]').value === "update" &&
285
+ (intent === "save" || intent === "publish");
286
+ if (!inPlace) {
287
+ window.location.assign(res.url);
288
+ return;
289
+ }
290
+ return res.text().then(function (html) {
291
+ var swapped = false;
292
+ try {
293
+ // The swapped-in unsaved-changes guard measures "dirty" against what was saved.
294
+ window.__kideSubmittedForm = fd;
295
+ swapped = swapInPlace(f, html);
296
+ } catch (err) {
297
+ // Never let a swap bug reach .catch below — that re-submits (saves twice).
298
+ console.error("[kide] in-place save update failed; reloading", err);
299
+ }
300
+ if (!swapped) window.location.assign(res.url);
301
+ });
216
302
  })
217
303
  .catch(function () {
218
304
  f.submit();
package/core/api.ts CHANGED
@@ -29,9 +29,11 @@ export type FindOptions = {
29
29
  * With `locale`: `"fallback"` (default) returns every document, overlaying the
30
30
  * translation when one exists; `"exact"` returns only documents that exist in
31
31
  * that locale — their source locale, or a translation row. Use `"exact"` for
32
- * listings and `"fallback"` for single-document routes.
32
+ * listings and `"fallback"` for single-document routes. `"missing"` is the
33
+ * complement of `"exact"`: documents that don't exist in that locale yet
34
+ * (e.g. a translation to-do list).
33
35
  */
34
- availability?: "fallback" | "exact";
36
+ availability?: "fallback" | "exact" | "missing";
35
37
  search?: string;
36
38
  };
37
39
 
@@ -473,11 +475,17 @@ export const createCms = (config: CMSConfig) => {
473
475
  if (!supportedLocales.includes(locale)) throw new Error(`Locale "${locale}" is not in locales.supported.`);
474
476
  return locale;
475
477
  };
476
- /** `availability: "exact"` — the document must exist in the requested locale. */
478
+ /**
479
+ * `availability: "exact"` — the document must exist in the requested locale;
480
+ * `"missing"` — it must not (neither its source locale nor a translation).
481
+ */
477
482
  const availabilityCondition = (tables: any, options: { locale?: string; availability?: string }) => {
478
- if (!options.locale || options.availability !== "exact" || !tables.translations || !config.locales) return null;
483
+ const { availability } = options;
484
+ if (!options.locale || (availability !== "exact" && availability !== "missing")) return null;
485
+ if (!tables.translations || !config.locales) return null;
479
486
  const tr = tables.translations;
480
- return sql`(${tables.main._sourceLocale} = ${options.locale} OR EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale}))`;
487
+ const exists = sql`(${tables.main._sourceLocale} = ${options.locale} OR EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale}))`;
488
+ return availability === "exact" ? exists : sql`NOT ${exists}`;
481
489
  };
482
490
 
483
491
  const overlayLocale = (
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, watch,
4
4
  import { createRequire } from "node:module";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { analyzeSharedDeps, formatConflicts } from "./shared-deps";
7
8
 
8
9
  // All runtime files resolve relative to this module, never the project root, so
9
10
  // the integration works identically embedded (workspace package in the project
@@ -113,9 +114,17 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
113
114
  return {
114
115
  name: "kide-cms",
115
116
  hooks: {
116
- "astro:config:setup": ({ command, updateConfig, injectRoute, injectScript, addMiddleware }) => {
117
+ "astro:config:setup": ({ command, updateConfig, injectRoute, injectScript, addMiddleware, logger }) => {
117
118
  const root = process.cwd();
118
119
 
120
+ // One copy per library the admin shares with the project — see shared-deps.ts.
121
+ const sharedDeps = analyzeSharedDeps({
122
+ projectRoot: root,
123
+ packageFile: packagePath("package.json"),
124
+ dependencies: JSON.parse(readFileSync(packagePath("package.json"), "utf8")).dependencies ?? {},
125
+ });
126
+ if (sharedDeps.conflicts.length > 0) logger.warn(formatConflicts(sharedDeps.conflicts));
127
+
119
128
  // Generate a wrapper CSS: Tailwind sources + the core admin chrome +
120
129
  // the project's theme file. Chrome (layers, focus, editor styles,
121
130
  // variants) is core-owned and updates with the package; the project
@@ -180,8 +189,9 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
180
189
  "virtual:kide/admin-css": wrapperCss,
181
190
  "virtual:kide/custom-fields": customFieldsBarrel,
182
191
  },
183
- // Two React copies (project + package) break hooks/context identity.
184
- dedupe: ["react", "react-dom"],
192
+ // Two React copies (project + package) break hooks/context identity, and two
193
+ // copies of any admin UI library break Vite's pre-bundling (shared-deps.ts).
194
+ dedupe: ["react", "react-dom", ...sharedDeps.dedupe],
185
195
  },
186
196
  // The package ships TypeScript/Astro source — Vite must compile it
187
197
  // rather than treat it as an external Node dependency in SSR.
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. With locale, availability 'exact' lists only documents that exist in that locale (their _sourceLocale or a translation); the default 'fallback' lists every document.",
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), 'missing' only those that don't; the default 'fallback' lists every document.",
203
203
  inputSchema: {
204
204
  collection: z.string().min(1),
205
205
  where: jsonObjectSchema.optional(),
@@ -209,7 +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
+ availability: z.enum(["fallback", "exact", "missing"]).optional(),
213
213
  },
214
214
  },
215
215
  async (args) => toResult(await workerCall("listDocuments", args)),
@@ -226,7 +226,7 @@ server.registerTool(
226
226
  search: z.string().optional(),
227
227
  status: statusSchema.optional(),
228
228
  locale: z.string().min(1).optional(),
229
- availability: z.enum(["fallback", "exact"]).optional(),
229
+ availability: z.enum(["fallback", "exact", "missing"]).optional(),
230
230
  },
231
231
  },
232
232
  async (args) => toResult(await workerCall("countDocuments", args)),