@kidecms/core 0.18.1 → 0.19.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.
@@ -325,6 +325,9 @@ export default function AssetsGrid({
325
325
  const [renameOpen, setRenameOpen] = useState(false);
326
326
  const [deleteOpen, setDeleteOpen] = useState(false);
327
327
  const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
328
+ const [bulkUsage, setBulkUsage] = useState<{ tone: "warn" | "muted"; message: string } | null>(null);
329
+ // Guards against a slow lookup from a previous dialog landing on a new selection.
330
+ const bulkUsageRequest = useRef(0);
328
331
  const [createName, setCreateName] = useState("");
329
332
  const [renameName, setRenameName] = useState("");
330
333
  const [activeFolderId, setActiveFolderId] = useState<string | null>(null);
@@ -581,6 +584,69 @@ export default function AssetsGrid({
581
584
  function resetDialogState() {
582
585
  setLoading(false);
583
586
  setError(null);
587
+ setBulkUsage(null);
588
+ bulkUsageRequest.current += 1;
589
+ }
590
+
591
+ /**
592
+ * Reports where the selected assets are used. Always sets a message — silence
593
+ * would make "none are used" indistinguishable from "the check failed", which
594
+ * is how a broken usage lookup goes unnoticed for a long time. The message is
595
+ * the whole dialog body, not an aside: what happens to the content is the point
596
+ * of the decision, so it must not read as a footnote to a generic warning.
597
+ */
598
+ async function loadBulkUsage(ids: string[]) {
599
+ const token = ++bulkUsageRequest.current;
600
+ const one = ids.length === 1;
601
+ const subject = one ? "This asset" : `These ${ids.length} assets`;
602
+ const settle = (tone: "warn" | "muted", message: string) => {
603
+ if (token === bulkUsageRequest.current) setBulkUsage({ tone, message });
604
+ };
605
+
606
+ settle("muted", `Checking where ${one ? "this asset is" : "these assets are"} used…`);
607
+ try {
608
+ const res = await fetch(`/api/cms/asset-usage?ids=${ids.map(encodeURIComponent).join(",")}`);
609
+ if (!res.ok) {
610
+ settle(
611
+ "muted",
612
+ `Couldn't check where ${one ? "this asset is" : "these assets are"} used. Deleting cannot be undone.`,
613
+ );
614
+ return;
615
+ }
616
+ const { counts, incomplete } = (await res.json()) as {
617
+ counts: Record<string, number>;
618
+ incomplete?: string[];
619
+ };
620
+ const used = ids.filter((id) => (counts[id] ?? 0) > 0);
621
+
622
+ if (used.length > 0) {
623
+ const places = used.reduce((sum, id) => sum + (counts[id] ?? 0), 0);
624
+ const where = places === 1 ? "1 place" : `${places} places`;
625
+ const subjectUsed = one
626
+ ? "This asset is"
627
+ : `${used.length} of these ${ids.length} assets ${used.length === 1 ? "is" : "are"}`;
628
+ settle(
629
+ "warn",
630
+ `${subjectUsed} used in ${where} — deleting will leave ${places === 1 ? "that place" : "those places"} without an image. This cannot be undone.`,
631
+ );
632
+ return;
633
+ }
634
+
635
+ if (incomplete?.length) {
636
+ settle(
637
+ "warn",
638
+ `Couldn't search ${incomplete.join(", ")}, so ${one ? "this asset" : "these assets"} may still be in use. Deleting cannot be undone.`,
639
+ );
640
+ return;
641
+ }
642
+
643
+ settle("muted", `${subject} ${one ? "isn't" : "aren't"} used by any document. Deleting cannot be undone.`);
644
+ } catch {
645
+ settle(
646
+ "muted",
647
+ `Couldn't check where ${one ? "this asset is" : "these assets are"} used. Deleting cannot be undone.`,
648
+ );
649
+ }
584
650
  }
585
651
 
586
652
  async function handleCreateFolder() {
@@ -634,7 +700,8 @@ export default function AssetsGrid({
634
700
  setLoading(true);
635
701
  setError(null);
636
702
  const ids = Array.from(selectedIds);
637
- const results = await Promise.all(ids.map((id) => fetch(`/api/cms/assets/${id}`, { method: "DELETE" })));
703
+ // force=1: the dialog already showed the usage warning and the editor accepted it.
704
+ const results = await Promise.all(ids.map((id) => fetch(`/api/cms/assets/${id}?force=1`, { method: "DELETE" })));
638
705
  const failed = results.filter((r) => !r.ok).length;
639
706
  if (failed > 0 && failed === ids.length) {
640
707
  setLoading(false);
@@ -736,7 +803,7 @@ export default function AssetsGrid({
736
803
 
737
804
  {/* ── Main: search, grid, pagination ── */}
738
805
  <div className="min-w-0 space-y-4 lg:border-l lg:pl-8">
739
- <div className="top-0 z-20 flex items-center justify-between gap-3 pt-1 pb-4">
806
+ <div className="bg-background sticky top-0 z-20 -mx-0.5 flex items-center justify-between gap-3 border-b px-0.5 py-3">
740
807
  <div className="relative w-full sm:max-w-xs">
741
808
  <Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2" />
742
809
  <Input
@@ -746,39 +813,62 @@ export default function AssetsGrid({
746
813
  className="pl-9 text-sm"
747
814
  />
748
815
  </div>
749
- <label
750
- className={cn(
751
- buttonVariants(),
752
- "shrink-0",
753
- uploading ? "pointer-events-none opacity-70" : "cursor-pointer",
754
- )}
755
- >
756
- {uploading ? (
757
- <>
758
- <Loader2 className="size-4 animate-spin" />
759
- {uploadProgress < 100
760
- ? `Uploading ${uploadCount > 1 ? `${uploadCount} files` : "file"}… ${uploadProgress}%`
761
- : "Processing…"}
762
- </>
763
- ) : (
764
- <>
765
- <Upload className="size-4" />
766
- Upload
767
- </>
768
- )}
769
- <input
770
- type="file"
771
- name="file"
772
- accept="image/*,video/*,audio/*,.pdf,.doc,.docx"
773
- multiple
774
- disabled={uploading}
775
- className="hidden"
776
- onChange={(e) => {
777
- if (e.target.files?.length) handleFilesSelected(e.target.files);
778
- e.target.value = "";
779
- }}
780
- />
781
- </label>
816
+ {selectedIds.size > 0 ? (
817
+ <div className="flex shrink-0 items-center gap-2">
818
+ <span className="text-sm font-medium">
819
+ {selectedIds.size}
820
+ <span className="hidden sm:inline"> selected</span>
821
+ </span>
822
+ <Button
823
+ variant="destructive"
824
+ onClick={() => {
825
+ resetDialogState();
826
+ setBulkDeleteOpen(true);
827
+ void loadBulkUsage(Array.from(selectedIds));
828
+ }}
829
+ >
830
+ <Trash2 className="size-4" />
831
+ Delete
832
+ </Button>
833
+ <Button variant="outline" onClick={clearSelection}>
834
+ Cancel
835
+ </Button>
836
+ </div>
837
+ ) : (
838
+ <label
839
+ className={cn(
840
+ buttonVariants(),
841
+ "shrink-0",
842
+ uploading ? "pointer-events-none opacity-70" : "cursor-pointer",
843
+ )}
844
+ >
845
+ {uploading ? (
846
+ <>
847
+ <Loader2 className="size-4 animate-spin" />
848
+ {uploadProgress < 100
849
+ ? `Uploading ${uploadCount > 1 ? `${uploadCount} files` : "file"}… ${uploadProgress}%`
850
+ : "Processing…"}
851
+ </>
852
+ ) : (
853
+ <>
854
+ <Upload className="size-4" />
855
+ Upload
856
+ </>
857
+ )}
858
+ <input
859
+ type="file"
860
+ name="file"
861
+ accept="image/*,video/*,audio/*,.pdf,.doc,.docx"
862
+ multiple
863
+ disabled={uploading}
864
+ className="hidden"
865
+ onChange={(e) => {
866
+ if (e.target.files?.length) handleFilesSelected(e.target.files);
867
+ e.target.value = "";
868
+ }}
869
+ />
870
+ </label>
871
+ )}
782
872
  </div>
783
873
  {uploading && (
784
874
  <div
@@ -810,29 +900,6 @@ export default function AssetsGrid({
810
900
  </div>
811
901
  )}
812
902
 
813
- {/* Selection toolbar */}
814
- {selectedIds.size > 0 && (
815
- <div className="bg-background sticky top-4 z-20 flex items-center justify-between gap-3 rounded-lg border px-3 py-2 shadow-sm">
816
- <span className="text-sm font-medium">{selectedIds.size} selected</span>
817
- <div className="flex items-center gap-2">
818
- <Button
819
- variant="destructive"
820
- size="sm"
821
- onClick={() => {
822
- resetDialogState();
823
- setBulkDeleteOpen(true);
824
- }}
825
- >
826
- <Trash2 className="size-3.5" />
827
- Delete
828
- </Button>
829
- <Button variant="outline" size="sm" onClick={clearSelection}>
830
- Cancel
831
- </Button>
832
- </div>
833
- </div>
834
- )}
835
-
836
903
  {/* Grid or empty state. Keep the current grid visible while a new
837
904
  filter/page loads (dimmed) to avoid an empty-then-fill flash. */}
838
905
  {items.length > 0 ? (
@@ -1033,10 +1100,10 @@ export default function AssetsGrid({
1033
1100
  <Dialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
1034
1101
  <DialogContent>
1035
1102
  <DialogHeader>
1036
- <DialogTitle>Delete assets</DialogTitle>
1037
- <DialogDescription>
1038
- Are you sure you want to delete {selectedIds.size} asset{selectedIds.size > 1 ? "s" : ""}? This action
1039
- cannot be undone.
1103
+ <DialogTitle>Delete {selectedIds.size === 1 ? "asset" : `${selectedIds.size} assets`}</DialogTitle>
1104
+ <DialogDescription className={cn(bulkUsage?.tone === "warn" && "text-foreground font-medium")}>
1105
+ {bulkUsage?.message ??
1106
+ `Deleting ${selectedIds.size === 1 ? "this asset" : "these assets"} cannot be undone.`}
1040
1107
  </DialogDescription>
1041
1108
  </DialogHeader>
1042
1109
  {error && <p className="text-destructive text-sm">{error}</p>}
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { useState } from "react";
4
4
  import { CalendarClock, CheckIcon, EllipsisVertical } from "lucide-react";
5
+ import { cn } from "../lib/utils";
5
6
  import {
6
7
  AlertDialog,
7
8
  AlertDialogClose,
@@ -52,6 +53,12 @@ type Props = {
52
53
  versions?: Version[];
53
54
  restoreEndpoint?: string;
54
55
  redirectTo?: string;
56
+ /** Overrides the reference lookup — assets report usage from a different endpoint. */
57
+ referencesEndpoint?: string;
58
+ /** Noun used in the delete dialog ("document", "asset", …). */
59
+ entityLabel?: string;
60
+ /** Adds `_force=1` to the delete submit, telling the API the warning was shown and accepted. */
61
+ forceOnConfirm?: boolean;
55
62
  };
56
63
 
57
64
  export default function DocumentActions({
@@ -69,10 +76,13 @@ export default function DocumentActions({
69
76
  versions = [],
70
77
  restoreEndpoint,
71
78
  redirectTo,
79
+ referencesEndpoint,
80
+ entityLabel = "document",
81
+ forceOnConfirm,
72
82
  }: Props) {
73
83
  const [scheduleOpen, setScheduleOpen] = useState(false);
74
84
  const [deleteOpen, setDeleteOpen] = useState(false);
75
- const [refWarning, setRefWarning] = useState<string | null>(null);
85
+ const [refWarning, setRefWarning] = useState<{ tone: "warn" | "muted"; message: string } | null>(null);
76
86
  const [publishAt, setPublishAt] = useState(currentPublishAt ? toLocalDatetime(currentPublishAt) : "");
77
87
  const [unpublishAt, setUnpublishAt] = useState(currentUnpublishAt ? toLocalDatetime(currentUnpublishAt) : "");
78
88
 
@@ -102,11 +112,21 @@ export default function DocumentActions({
102
112
  }
103
113
  };
104
114
 
105
- const submitAction = (action: string) => {
115
+ const submitAction = (action: string, force?: boolean) => {
106
116
  const form = document.getElementById(formId) as HTMLFormElement | null;
107
117
  if (!form) return;
108
118
  const input = form.querySelector<HTMLInputElement>('input[name="_action"]');
109
119
  if (input) input.value = action;
120
+ if (force) {
121
+ let forceInput = form.querySelector<HTMLInputElement>('input[name="_force"]');
122
+ if (!forceInput) {
123
+ forceInput = document.createElement("input");
124
+ forceInput.type = "hidden";
125
+ forceInput.name = "_force";
126
+ form.appendChild(forceInput);
127
+ }
128
+ forceInput.value = "1";
129
+ }
110
130
  form.submit();
111
131
  };
112
132
 
@@ -228,23 +248,45 @@ export default function DocumentActions({
228
248
  variant="destructive"
229
249
  onClick={async () => {
230
250
  setRefWarning(null);
231
- if (collectionSlug && documentId) {
232
- try {
233
- const res = await fetch(`/api/cms/references/${collectionSlug}/${documentId}`);
234
- if (res.ok) {
235
- const { refs, total } = await res.json();
236
- if (total > 0) {
237
- const parts = refs.map(
238
- (r: { collection: string; count: number }) => `${r.count} ${r.collection.toLowerCase()}`,
239
- );
240
- setRefWarning(
241
- `This document is referenced by ${parts.join(", ")}. Deleting it will leave broken references.`,
242
- );
243
- }
244
- }
245
- } catch {}
246
- }
251
+ const endpoint =
252
+ referencesEndpoint ??
253
+ (collectionSlug && documentId ? `/api/cms/references/${collectionSlug}/${documentId}` : null);
247
254
  setDeleteOpen(true);
255
+ if (!endpoint) return;
256
+
257
+ // Always report the outcome. Staying silent on a failed lookup makes
258
+ // "nothing references this" and "the check never ran" identical, which
259
+ // is exactly how a broken reference check goes unnoticed.
260
+ try {
261
+ const res = await fetch(endpoint);
262
+ if (!res.ok) {
263
+ setRefWarning({ tone: "muted", message: `Couldn't check what references this ${entityLabel}.` });
264
+ return;
265
+ }
266
+ const payload = await res.json();
267
+ const parts = summarizeRefs(payload);
268
+ if (parts.length > 0) {
269
+ setRefWarning({
270
+ tone: "warn",
271
+ message: `This ${entityLabel} is referenced by ${parts.join(", ")} — deleting it will leave those references broken. This cannot be undone.`,
272
+ });
273
+ } else if (Array.isArray(payload.incomplete) && payload.incomplete.length > 0) {
274
+ setRefWarning({
275
+ tone: "warn",
276
+ message: `Couldn't search ${payload.incomplete.join(", ")}, so this ${entityLabel} may still be referenced. Deleting it cannot be undone.`,
277
+ });
278
+ } else {
279
+ setRefWarning({
280
+ tone: "muted",
281
+ message: `Nothing references this ${entityLabel}. Deleting it cannot be undone.`,
282
+ });
283
+ }
284
+ } catch {
285
+ setRefWarning({
286
+ tone: "muted",
287
+ message: `Couldn't check what references this ${entityLabel}. Deleting it cannot be undone.`,
288
+ });
289
+ }
248
290
  }}
249
291
  >
250
292
  Delete
@@ -302,19 +344,16 @@ export default function DocumentActions({
302
344
  <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
303
345
  <AlertDialogContent>
304
346
  <AlertDialogHeader>
305
- <AlertDialogTitle>Delete document</AlertDialogTitle>
306
- <AlertDialogDescription>
307
- {refWarning && (
308
- <span className="mb-2 block font-medium text-amber-600 dark:text-amber-400">{refWarning}</span>
309
- )}
310
- This action cannot be undone. This will permanently delete this document.
347
+ <AlertDialogTitle>Delete {entityLabel}</AlertDialogTitle>
348
+ <AlertDialogDescription className={cn(refWarning?.tone === "warn" && "text-foreground font-medium")}>
349
+ {refWarning?.message ?? `Deleting this ${entityLabel} cannot be undone.`}
311
350
  </AlertDialogDescription>
312
351
  </AlertDialogHeader>
313
352
  <AlertDialogFooter>
314
353
  <AlertDialogClose>
315
354
  <Button variant="outline">Cancel</Button>
316
355
  </AlertDialogClose>
317
- <Button variant="destructive" onClick={() => submitAction("delete")}>
356
+ <Button variant="destructive" onClick={() => submitAction("delete", forceOnConfirm)}>
318
357
  Delete
319
358
  </Button>
320
359
  </AlertDialogFooter>
@@ -331,3 +370,24 @@ function toLocalDatetime(iso: string): string {
331
370
  const local = new Date(date.getTime() - offset * 60000);
332
371
  return local.toISOString().slice(0, 16);
333
372
  }
373
+
374
+ /**
375
+ * Both reference endpoints answer "where is this used" in their own shape:
376
+ * `/api/cms/references/*` returns pre-counted `refs`, the asset endpoint returns
377
+ * the matching documents grouped by collection.
378
+ */
379
+ function summarizeRefs(payload: {
380
+ refs?: Array<{ collection: string; count: number }>;
381
+ usage?: Array<{ collectionLabel: string; docs: unknown[] }>;
382
+ incomplete?: string[];
383
+ }): string[] {
384
+ if (Array.isArray(payload.usage)) {
385
+ return payload.usage
386
+ .filter((entry) => entry.docs.length > 0)
387
+ .map((entry) => `${entry.docs.length} ${entry.collectionLabel.toLowerCase()}`);
388
+ }
389
+ if (Array.isArray(payload.refs)) {
390
+ return payload.refs.filter((ref) => ref.count > 0).map((ref) => `${ref.count} ${ref.collection.toLowerCase()}`);
391
+ }
392
+ return [];
393
+ }
@@ -798,7 +798,13 @@ export default function DocumentsDataTable({
798
798
  {headerGroup.headers
799
799
  .filter((header) => header.column.id !== "search")
800
800
  .map((header) => (
801
- <TableHead key={header.id} className={header.column.id === "select" ? "w-10" : undefined}>
801
+ <TableHead
802
+ key={header.id}
803
+ className={cn(
804
+ header.column.id === "select" && "w-10",
805
+ header.column.id === primaryColumnKey && "max-sm:min-w-48",
806
+ )}
807
+ >
802
808
  {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
803
809
  </TableHead>
804
810
  ))}
@@ -821,6 +827,7 @@ export default function DocumentsDataTable({
821
827
  // including a wrapped multi-line title, for a consistent row.
822
828
  "align-middle break-words whitespace-normal",
823
829
  cell.column.id === "select" && "w-10",
830
+ cell.column.id === primaryColumnKey && "max-sm:min-w-48",
824
831
  )}
825
832
  >
826
833
  {flexRender(cell.column.columnDef.cell, cell.getContext())}
@@ -0,0 +1 @@
1
+ deleting
@@ -2,9 +2,14 @@
2
2
  import AdminCard from "../../components/AdminCard.astro";
3
3
  import type { ReverseRef } from "../../lib/edit-data";
4
4
 
5
- const { reverseRefs, variant = "editorial" } = Astro.props as {
5
+ const {
6
+ reverseRefs,
7
+ variant = "editorial",
8
+ title = "Referenced by",
9
+ } = Astro.props as {
6
10
  reverseRefs: ReverseRef[];
7
11
  variant?: "editorial" | "record";
12
+ title?: string;
8
13
  };
9
14
 
10
15
  const allDocs = reverseRefs.flatMap((ref) =>
@@ -57,10 +62,10 @@ const hidden = allDocs.slice(30);
57
62
  );
58
63
 
59
64
  return variant === "record" ? (
60
- <AdminCard title="Referenced by">{list}</AdminCard>
65
+ <AdminCard title={title}>{list}</AdminCard>
61
66
  ) : (
62
67
  <div class="grid gap-2">
63
- <span class="text-foreground/80 text-sm leading-none font-medium">Referenced by</span>
68
+ <span class="text-foreground/80 text-sm leading-none font-medium">{title}</span>
64
69
  {list}
65
70
  </div>
66
71
  );
package/core/api.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { and, asc, desc, eq, inArray, like, lte, ne, or, sql } from "drizzle-orm";
2
2
  import { nanoid } from "nanoid";
3
3
 
4
+ import { setUsageConfig } from "./asset-usage";
4
5
  import { recordAudit, type AuditActor } from "./audit";
5
6
  import { hashPassword, MIN_PASSWORD_LENGTH } from "./auth";
6
7
  import type { CMSConfig, CollectionConfig, FieldConfig, RichTextDocument } from "./define";
@@ -407,6 +408,10 @@ export const createCms = (config: CMSConfig) => {
407
408
  }
408
409
  const collectionMap = getCollectionMap(config);
409
410
 
411
+ // Lets assets.delete() check whether a file is still referenced without every
412
+ // caller having to thread the config in.
413
+ setUsageConfig(config);
414
+
410
415
  // Webhook `name` routes deliveries — must be unique and non-empty.
411
416
  const webhookNames = (config.admin?.webhooks ?? []).map((webhook) => webhook.name.trim());
412
417
  if (webhookNames.some((name) => name === "")) {
@@ -0,0 +1,283 @@
1
+ import { eq, or, sql, type SQL } from "drizzle-orm";
2
+
3
+ import { getLabelField, type CMSConfig, type CollectionConfig, type FieldConfig } from "./define";
4
+ import { getDb } from "./runtime";
5
+ import { getSchema } from "./schema";
6
+
7
+ /**
8
+ * Where an asset is used. Structurally identical to the admin's `ReverseRef`
9
+ * so the existing "Referenced by" list component renders it unchanged.
10
+ */
11
+ export type AssetUsageRef = {
12
+ collectionSlug: string;
13
+ collectionLabel: string;
14
+ docs: Array<{ _id: string; label: string }>;
15
+ };
16
+
17
+ export type AssetUsageResult = {
18
+ refs: AssetUsageRef[];
19
+ /**
20
+ * Collections whose scan failed (missing table, schema drift). Their documents
21
+ * were not searched, so `refs` may under-report. Never treat a non-empty
22
+ * `incomplete` as "not used" — that is how a referenced asset gets deleted.
23
+ */
24
+ incomplete: string[];
25
+ };
26
+
27
+ /** Matching rows pulled per collection before attribution. Generous — a match is already rare. */
28
+ const SCAN_CAP = 1000;
29
+
30
+ /**
31
+ * The config is registered by `createCms()` so `assets.delete()` can check usage
32
+ * without every caller threading the config through.
33
+ */
34
+ let usageConfig: CMSConfig | null = null;
35
+
36
+ export const setUsageConfig = (config: CMSConfig) => {
37
+ usageConfig = config;
38
+ };
39
+
40
+ export const getUsageConfig = (): CMSConfig | null => usageConfig;
41
+
42
+ /** Field types serialized to JSON in a single text column — matched by substring. */
43
+ const JSON_FIELD_TYPES = new Set(["richText", "content", "array", "json", "blocks"]);
44
+
45
+ /**
46
+ * Can this field hold a storagePath anywhere inside it? Keeps the query narrow —
47
+ * a `blocks` field whose block types declare no image never gets scanned.
48
+ */
49
+ const fieldCanHoldAsset = (field: FieldConfig, depth = 0): boolean => {
50
+ if (depth > 6) return false;
51
+ switch (field.type) {
52
+ case "image":
53
+ return true;
54
+ // Rich text carries inline `{ type: "image", src }` nodes whatever the sub-fields say.
55
+ case "richText":
56
+ case "content":
57
+ return true;
58
+ case "array":
59
+ return fieldCanHoldAsset(field.of, depth + 1);
60
+ case "json":
61
+ // Freeform json has no declared shape — assume it might.
62
+ return field.itemFields ? Object.values(field.itemFields).some((f) => fieldCanHoldAsset(f, depth + 1)) : true;
63
+ case "blocks":
64
+ return Object.values(field.types).some((blockFields) =>
65
+ Object.values(blockFields).some((f) => fieldCanHoldAsset(f, depth + 1)),
66
+ );
67
+ default:
68
+ return false;
69
+ }
70
+ };
71
+
72
+ type UsageTargets = { exact: string[]; contains: string[] };
73
+
74
+ const getUsageTargets = (collection: CollectionConfig): UsageTargets => {
75
+ const exact: string[] = [];
76
+ const contains: string[] = [];
77
+
78
+ for (const [name, field] of Object.entries(collection.fields)) {
79
+ if (field.type === "image") exact.push(name);
80
+ else if (JSON_FIELD_TYPES.has(field.type) && fieldCanHoldAsset(field)) contains.push(name);
81
+ }
82
+
83
+ return { exact, contains };
84
+ };
85
+
86
+ const hasUsageTargets = (targets: UsageTargets) => targets.exact.length > 0 || targets.contains.length > 0;
87
+
88
+ type ScanColumn = { key: string; column: any; exact: boolean };
89
+
90
+ const collectColumns = (table: Record<string, any>, targets: UsageTargets, includePublished: boolean): ScanColumn[] => {
91
+ const columns: ScanColumn[] = [];
92
+
93
+ for (const name of targets.exact) {
94
+ if (table[name]) columns.push({ key: `c${columns.length}`, column: table[name], exact: true });
95
+ }
96
+ for (const name of targets.contains) {
97
+ if (table[name]) columns.push({ key: `c${columns.length}`, column: table[name], exact: false });
98
+ }
99
+ // The published snapshot is what the live site serves while a doc has unpublished
100
+ // changes, so a path living only in there still renders — and still counts as used.
101
+ if (includePublished && table._published) {
102
+ columns.push({ key: `c${columns.length}`, column: table._published, exact: false });
103
+ }
104
+
105
+ return columns;
106
+ };
107
+
108
+ /**
109
+ * `instr` is a literal substring search — no LIKE wildcards to escape, and the
110
+ * storagePath is a random nanoid so a substring hit is never a false positive.
111
+ */
112
+ const matchExpression = (entry: ScanColumn, path: string): SQL =>
113
+ entry.exact ? eq(entry.column, path) : sql`instr(${entry.column}, ${path}) > 0`;
114
+
115
+ /**
116
+ * Document ids per storagePath, per collection. One query per table — the DB does
117
+ * the filtering; JS only attributes each matched row back to the path(s) it matched.
118
+ */
119
+ const scanUsage = async (
120
+ config: CMSConfig,
121
+ paths: string[],
122
+ ): Promise<{ hits: Map<string, Array<{ collection: CollectionConfig; docId: string }>>; incomplete: string[] }> => {
123
+ const hits = new Map<string, Array<{ collection: CollectionConfig; docId: string }>>();
124
+ const incomplete: string[] = [];
125
+ for (const path of paths) hits.set(path, []);
126
+ if (paths.length === 0) return { hits, incomplete };
127
+
128
+ const db = await getDb();
129
+ const { cmsTables } = getSchema();
130
+
131
+ for (const collection of config.collections) {
132
+ const targets = getUsageTargets(collection);
133
+ if (!hasUsageTargets(targets)) continue;
134
+
135
+ const tables = cmsTables[collection.slug];
136
+ if (!tables?.main) continue;
137
+
138
+ const perPath = new Map<string, Set<string>>();
139
+
140
+ const scanTable = async (table: Record<string, any>, idColumn: any, includePublished: boolean) => {
141
+ const columns = collectColumns(table, targets, includePublished);
142
+ if (columns.length === 0) return;
143
+
144
+ const conditions = paths.flatMap((path) => columns.map((entry) => matchExpression(entry, path)));
145
+ const selection: Record<string, any> = { __id: idColumn };
146
+ for (const entry of columns) selection[entry.key] = entry.column;
147
+
148
+ const rows = await db
149
+ .select(selection)
150
+ .from(table)
151
+ .where(or(...conditions))
152
+ .limit(SCAN_CAP);
153
+
154
+ for (const row of rows as Array<Record<string, unknown>>) {
155
+ const docId = String(row.__id ?? "");
156
+ if (!docId) continue;
157
+ for (const path of paths) {
158
+ const matched = columns.some((entry) => {
159
+ const value = row[entry.key];
160
+ return typeof value === "string" && value.includes(path);
161
+ });
162
+ if (!matched) continue;
163
+ if (!perPath.has(path)) perPath.set(path, new Set());
164
+ perPath.get(path)!.add(docId);
165
+ }
166
+ }
167
+ };
168
+
169
+ try {
170
+ await scanTable(tables.main, tables.main._id, !!collection.drafts);
171
+ if (tables.translations) await scanTable(tables.translations, tables.translations._entityId, false);
172
+ } catch (error) {
173
+ // A missing or mid-migration table must not break the whole check — but it must
174
+ // not pass as "no usage" either, so record it and let the caller refuse to
175
+ // conclude anything. Silence here is what deletes a referenced asset.
176
+ incomplete.push(collection.slug);
177
+ console.warn(`[cms] asset usage scan failed for collection "${collection.slug}":`, error);
178
+ continue;
179
+ }
180
+
181
+ for (const [path, docIds] of perPath) {
182
+ const bucket = hits.get(path);
183
+ if (!bucket) continue;
184
+ for (const docId of docIds) bucket.push({ collection, docId });
185
+ }
186
+ }
187
+
188
+ return { hits, incomplete };
189
+ };
190
+
191
+ /** Resolves display labels for matched documents, one query per collection. */
192
+ const resolveLabels = async (
193
+ entries: Array<{ collection: CollectionConfig; docId: string }>,
194
+ ): Promise<AssetUsageRef[]> => {
195
+ if (entries.length === 0) return [];
196
+
197
+ const db = await getDb();
198
+ const { cmsTables } = getSchema();
199
+ const bySlug = new Map<string, { collection: CollectionConfig; docIds: string[] }>();
200
+
201
+ for (const entry of entries) {
202
+ const existing = bySlug.get(entry.collection.slug);
203
+ if (existing) existing.docIds.push(entry.docId);
204
+ else bySlug.set(entry.collection.slug, { collection: entry.collection, docIds: [entry.docId] });
205
+ }
206
+
207
+ const refs: AssetUsageRef[] = [];
208
+
209
+ for (const { collection, docIds } of bySlug.values()) {
210
+ const tables = cmsTables[collection.slug];
211
+ const labelField = getLabelField(collection);
212
+ const labels = new Map<string, string>();
213
+
214
+ if (tables?.main?.[labelField]) {
215
+ try {
216
+ const rows = await db
217
+ .select({ __id: tables.main._id, __label: tables.main[labelField] })
218
+ .from(tables.main)
219
+ .where(or(...docIds.map((id) => eq(tables.main._id, id))));
220
+ for (const row of rows as Array<Record<string, unknown>>) {
221
+ labels.set(String(row.__id), String(row.__label ?? "").trim());
222
+ }
223
+ } catch {
224
+ // fall through to id labels
225
+ }
226
+ }
227
+
228
+ refs.push({
229
+ collectionSlug: collection.slug,
230
+ collectionLabel: collection.singleton ? collection.labels.singular : collection.labels.plural,
231
+ docs: docIds.map((docId) => ({
232
+ _id: docId,
233
+ label: collection.singleton ? collection.labels.singular : labels.get(docId) || docId,
234
+ })),
235
+ });
236
+ }
237
+
238
+ return refs;
239
+ };
240
+
241
+ /** Every document that references this asset's storagePath. */
242
+ export const findAssetUsage = async (config: CMSConfig, storagePath: string): Promise<AssetUsageResult> => {
243
+ if (!storagePath) return { refs: [], incomplete: [] };
244
+ const { hits, incomplete } = await scanUsage(config, [storagePath]);
245
+ return { refs: await resolveLabels(hits.get(storagePath) ?? []), incomplete };
246
+ };
247
+
248
+ /** Usage counts for many assets at once — one pass per collection, not per asset. */
249
+ export const countAssetUsage = async (
250
+ config: CMSConfig,
251
+ storagePaths: string[],
252
+ ): Promise<{ counts: Record<string, number>; incomplete: string[] }> => {
253
+ const unique = [...new Set(storagePaths.filter(Boolean))];
254
+ const counts: Record<string, number> = Object.fromEntries(unique.map((path) => [path, 0]));
255
+ if (unique.length === 0) return { counts, incomplete: [] };
256
+
257
+ const { hits, incomplete } = await scanUsage(config, unique);
258
+ for (const [path, entries] of hits) counts[path] = entries.length;
259
+ return { counts, incomplete };
260
+ };
261
+
262
+ /**
263
+ * Raised by `assets.delete()` when the asset is still referenced — or when usage
264
+ * could not be established — and `force` was not set.
265
+ */
266
+ export class AssetInUseError extends Error {
267
+ readonly usage: AssetUsageRef[];
268
+ readonly incomplete: string[];
269
+ readonly assetId: string;
270
+
271
+ constructor(assetId: string, usage: AssetUsageRef[], incomplete: string[] = []) {
272
+ const total = usage.reduce((sum, ref) => sum + ref.docs.length, 0);
273
+ super(
274
+ total > 0
275
+ ? `Asset is used by ${total} document${total === 1 ? "" : "s"}.`
276
+ : `Could not verify where this asset is used (${incomplete.join(", ")} could not be searched).`,
277
+ );
278
+ this.name = "AssetInUseError";
279
+ this.assetId = assetId;
280
+ this.usage = usage;
281
+ this.incomplete = incomplete;
282
+ }
283
+ }
package/core/assets.ts CHANGED
@@ -2,11 +2,23 @@ import { createHash } from "node:crypto";
2
2
  import { and, desc, eq, isNull, like, or, sql } from "drizzle-orm";
3
3
  import { nanoid } from "nanoid";
4
4
 
5
+ import { AssetInUseError, findAssetUsage, getUsageConfig } from "./asset-usage";
6
+ import type { CMSConfig } from "./define";
5
7
  import { logAudit, type AuditActor } from "./audit";
6
8
  import { getDb, getStorage } from "./runtime";
7
9
  import { getSchema } from "./schema";
8
10
 
9
- export type AssetContext = { actor?: AuditActor };
11
+ export type AssetContext = {
12
+ actor?: AuditActor;
13
+ /** Skip the in-use check. The admin sets this once the editor has confirmed the warning. */
14
+ force?: boolean;
15
+ /**
16
+ * Config used for the in-use check. Pass it explicitly from any caller that
17
+ * deletes — relying on the copy `createCms()` registers makes the guard depend
18
+ * on whether something else in the process imported the generated API first.
19
+ */
20
+ config?: CMSConfig;
21
+ };
10
22
 
11
23
  export type AssetRecord = {
12
24
  _id: string;
@@ -208,6 +220,25 @@ export const assets = {
208
220
  const rows = await db.select().from(schema.cmsAssets).where(eq(schema.cmsAssets._id, id)).limit(1);
209
221
  if (rows.length === 0) return;
210
222
  const asset = rows[0] as any;
223
+
224
+ // Guarded here, not only in the admin — DELETE /api/cms/assets/:id is reachable
225
+ // directly. Never skip the check silently: with no config there is nothing to
226
+ // check against, and proceeding would delete a referenced asset without a word.
227
+ // Callers that genuinely want an unchecked delete pass `force`.
228
+ if (!context?.force) {
229
+ const config = context?.config ?? getUsageConfig();
230
+ if (!config) {
231
+ throw new Error(
232
+ "assets.delete() cannot check whether this asset is in use — pass `config` in the context " +
233
+ "(or `force: true` to delete without checking).",
234
+ );
235
+ }
236
+ const { refs, incomplete } = await findAssetUsage(config, asset.storagePath);
237
+ // A collection we could not search is not evidence of "unused" — refuse
238
+ // rather than delete something that may still be referenced.
239
+ if (refs.length > 0 || incomplete.length > 0) throw new AssetInUseError(id, refs, incomplete);
240
+ }
241
+
211
242
  await storage.deleteFile(asset.storagePath);
212
243
  await db.delete(schema.cmsAssets).where(eq(schema.cmsAssets._id, id));
213
244
 
@@ -334,3 +365,64 @@ export const folders = {
334
365
  await db.delete(schema.cmsAssetFolders).where(eq(schema.cmsAssetFolders._id, id));
335
366
  },
336
367
  };
368
+
369
+ type RichTextLikeNode = { type?: string; src?: unknown; children?: unknown[]; [key: string]: unknown };
370
+
371
+ const collectLocalImageSrcs = (node: unknown, into: Set<string>): void => {
372
+ if (Array.isArray(node)) {
373
+ for (const child of node) collectLocalImageSrcs(child, into);
374
+ return;
375
+ }
376
+ if (!node || typeof node !== "object") return;
377
+
378
+ const candidate = node as RichTextLikeNode;
379
+ if (candidate.type === "image" && typeof candidate.src === "string" && candidate.src.startsWith("/uploads/")) {
380
+ into.add(candidate.src);
381
+ }
382
+ if (Array.isArray(candidate.children)) collectLocalImageSrcs(candidate.children, into);
383
+ };
384
+
385
+ const withoutMissingImages = <T>(node: T, missing: Set<string>): T => {
386
+ if (Array.isArray(node)) {
387
+ return node
388
+ .filter((child) => {
389
+ const candidate = child as RichTextLikeNode | null;
390
+ return !(
391
+ candidate &&
392
+ typeof candidate === "object" &&
393
+ candidate.type === "image" &&
394
+ typeof candidate.src === "string" &&
395
+ missing.has(candidate.src)
396
+ );
397
+ })
398
+ .map((child) => withoutMissingImages(child, missing)) as unknown as T;
399
+ }
400
+ if (!node || typeof node !== "object") return node;
401
+
402
+ const candidate = node as RichTextLikeNode;
403
+ if (!Array.isArray(candidate.children)) return node;
404
+ return { ...candidate, children: withoutMissingImages(candidate.children, missing) } as unknown as T;
405
+ };
406
+
407
+ /**
408
+ * Drops `image` nodes whose upload no longer exists from a rich-text / content
409
+ * document. The renderers are synchronous string builders, so this is the async
410
+ * pass that keeps a deleted asset from emitting a <picture> of 404s.
411
+ *
412
+ * Returns the document unchanged when nothing is missing (the common case).
413
+ */
414
+ export const stripMissingAssetImages = async <T>(document: T): Promise<T> => {
415
+ const srcs = new Set<string>();
416
+ collectLocalImageSrcs(document, srcs);
417
+ if (srcs.size === 0) return document;
418
+
419
+ const missing = new Set<string>();
420
+ await Promise.all(
421
+ [...srcs].map(async (src) => {
422
+ if (!(await assets.findByUrl(src))) missing.add(src);
423
+ }),
424
+ );
425
+ if (missing.size === 0) return document;
426
+
427
+ return withoutMissingImages(document, missing);
428
+ };
package/core/generator.ts CHANGED
@@ -151,7 +151,11 @@ const generateSchemaFile = (config: CMSConfig): string => {
151
151
  storagePath: text("storage_path").notNull(),
152
152
  hash: text("hash"),
153
153
  _createdAt: text("_created_at").notNull(),
154
- });`);
154
+ }, (table) => ({
155
+ storagePathIdx: index("assets_storage_path_idx").on(table.storagePath),
156
+ hashIdx: index("assets_hash_idx").on(table.hash),
157
+ folderIdx: index("assets_folder_idx").on(table.folder),
158
+ }));`);
155
159
  parts.push("");
156
160
  parts.push(`export const cmsAssetFolders = sqliteTable("cms_asset_folders", {
157
161
  _id: text("_id").primaryKey(),
package/core/image.ts CHANGED
@@ -70,7 +70,16 @@ function isCloudflare(): boolean {
70
70
  return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
71
71
  }
72
72
 
73
- export function cmsImage(src: string, width?: number, format: Format = "webp", crop?: CropOptions): string {
73
+ /**
74
+ * Builds a URL for one rendition. This is the low-level primitive — it cannot
75
+ * read the asset record, so it knows nothing about the stored focal point or the
76
+ * intrinsic dimensions, and it does not check that the upload still exists.
77
+ *
78
+ * To render an image, use `<CmsImage>`, which does all three. Reach for this only
79
+ * when you need a string rather than an element: og:image, CSS background-image,
80
+ * JSON-LD, email HTML.
81
+ */
82
+ export function cmsImageUrl(src: string, width?: number, format: Format = "webp", crop?: CropOptions): string {
74
83
  if (!src) return "";
75
84
 
76
85
  const ratio = parseAspect(crop?.aspect);
@@ -110,7 +119,7 @@ export function cmsSrcset(
110
119
  crop?: CropOptions,
111
120
  ): string {
112
121
  if (!src) return "";
113
- return widths.map((width) => `${cmsImage(src, width, format, crop)} ${width}w`).join(", ");
122
+ return widths.map((width) => `${cmsImageUrl(src, width, format, crop)} ${width}w`).join(", ");
114
123
  }
115
124
 
116
125
  export type TransformOptions = {
package/core/index.ts CHANGED
@@ -140,8 +140,10 @@ export {
140
140
  } from "./auth";
141
141
  export type { SessionUser } from "./auth";
142
142
 
143
- export { assets, folders } from "./assets";
143
+ export { assets, folders, stripMissingAssetImages } from "./assets";
144
144
  export type { AssetRecord, FolderRecord } from "./assets";
145
+ export { AssetInUseError, countAssetUsage, findAssetUsage } from "./asset-usage";
146
+ export type { AssetUsageRef, AssetUsageResult } from "./asset-usage";
145
147
 
146
148
  export { parseBlocks, parseList, cacheTags } from "./content";
147
149
  export { renderRichText, createRichTextFromPlainText, richTextToPlainText, htmlToRichText } from "./richtext";
@@ -169,7 +171,7 @@ export {
169
171
  contentToPlainText,
170
172
  } from "./values";
171
173
  export type { ContentSegment } from "./values";
172
- export { cmsImage, cmsSrcset, transformImage, DEFAULT_PRESETS, resolveImagePreset } from "./image";
174
+ export { cmsImageUrl, cmsSrcset, transformImage, DEFAULT_PRESETS, resolveImagePreset } from "./image";
173
175
  export type { CropOptions, TransformOptions } from "./image";
174
176
 
175
177
  export {
package/core/values.ts CHANGED
@@ -6,7 +6,7 @@ import type {
6
6
  RichTextDocument,
7
7
  RichTextNode,
8
8
  } from "./define";
9
- import { cmsImage, cmsSrcset } from "./image";
9
+ import { cmsImageUrl, cmsSrcset } from "./image";
10
10
 
11
11
  export const cloneValue = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
12
12
 
@@ -320,7 +320,7 @@ const renderNode = (node: RichTextNode): string => {
320
320
  const sizes = "(max-width: 768px) 100vw, 768px";
321
321
  const avif = escapeHtml(cmsSrcset(src, undefined, "avif"));
322
322
  const webp = escapeHtml(cmsSrcset(src, undefined, "webp"));
323
- const fallback = escapeHtml(cmsImage(src, 1024));
323
+ const fallback = escapeHtml(cmsImageUrl(src, 1024));
324
324
  return `<picture><source type="image/avif" srcset="${avif}" sizes="${sizes}" /><source type="image/webp" srcset="${webp}" sizes="${sizes}" /><img src="${fallback}" alt="${alt}" loading="lazy" class="h-auto max-w-full rounded-lg" /></picture>`;
325
325
  }
326
326
  const safeSrc = safeUrl(src);
@@ -309,6 +309,10 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
309
309
  pattern: "/api/cms/assets",
310
310
  entrypoint: new URL("../routes/api/assets/index.ts", import.meta.url),
311
311
  });
312
+ injectRoute({
313
+ pattern: "/api/cms/asset-usage",
314
+ entrypoint: new URL("../routes/api/asset-usage.ts", import.meta.url),
315
+ });
312
316
  injectRoute({
313
317
  pattern: "/api/cms/collaboration",
314
318
  entrypoint: new URL("../routes/api/collaboration/index.ts", import.meta.url),
package/internals/push.ts CHANGED
@@ -122,7 +122,16 @@ async function main() {
122
122
  // drizzle-kit's hasDataLoss misses plain DROP COLUMN — classify statement shapes too.
123
123
  // (`__new_` is drizzle's table-recreate pattern: create copy, insert-select, drop old.)
124
124
  const isDestructive = (stmt: string) => /\bDROP\s+TABLE\b|\bDROP\s+COLUMN\b|\bDELETE\s+FROM\b|__new_/i.test(stmt);
125
- const losesData = hasDataLoss || statements.some(isDestructive);
125
+
126
+ // `hasDataLoss` describes the whole diff, including the runtime FTS tables filtered
127
+ // out above — dropping those is not data loss (ensureSearchSchema rebuilds them), so
128
+ // the flag alone would block any additive change made while a search index exists.
129
+ // Judge what we are actually going to run, and only defer to drizzle's flag when
130
+ // something outside the search index could be behind it.
131
+ const droppedSearchIndex = statementsToExecute.some(isSearchIndexStatement);
132
+ const searchIndexIsTheOnlyLoss =
133
+ droppedSearchIndex && statementsToExecute.every((stmt) => isSearchIndexStatement(stmt) || !isDestructive(stmt));
134
+ const losesData = statements.some(isDestructive) || (hasDataLoss && !searchIndexIsTheOnlyLoss);
126
135
 
127
136
  if (statements.length === 0) {
128
137
  console.log("[cms:push] Schema already in sync.");
@@ -48,6 +48,10 @@ declare module "virtual:kide/runtime" {
48
48
  streamTranslation,
49
49
  assets,
50
50
  folders,
51
+ stripMissingAssetImages,
52
+ findAssetUsage,
53
+ countAssetUsage,
54
+ AssetInUseError,
51
55
  createCms,
52
56
  recordAudit,
53
57
  logAudit,
@@ -70,7 +70,7 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
70
70
  const isInvitePage = pathname === "/admin/invite";
71
71
  const isInviteApi = pathname === "/api/cms/auth/invite";
72
72
 
73
- // Public despite the /api/cms prefix: cmsImage() puts these URLs on public pages.
73
+ // Public despite the /api/cms prefix: cmsImageUrl() puts these URLs on public pages.
74
74
  // Only reads files under public/, which are served unauthenticated anyway.
75
75
  const isPublicImageApi = pathname.startsWith("/api/cms/img/");
76
76
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.18.1",
3
+ "version": "0.19.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",
@@ -6,12 +6,13 @@ import DocumentActions from "../../../admin/components/DocumentActions";
6
6
  import AiGenerateButton from "../../../admin/components/AiGenerateButton";
7
7
  import FocalPointSelector from "../../../admin/components/FocalPointSelector";
8
8
  import UnsavedGuard from "../../../admin/components/UnsavedGuard";
9
+ import ReverseReferencesList from "../../../admin/views/edit/ReverseReferencesList.astro";
9
10
  import TreeSelect, { flattenByParent } from "../../../admin/components/TreeSelect";
10
11
  import { buttonVariants } from "../../../admin/components/ui/button";
11
12
  import { Label } from "../../../admin/components/ui/label";
12
13
  import { Textarea } from "../../../admin/components/ui/textarea";
13
14
  import config from "virtual:kide/config";
14
- import { assets, folders, isAiEnabled } from "virtual:kide/runtime";
15
+ import { assets, findAssetUsage, folders, isAiEnabled } from "virtual:kide/runtime";
15
16
  import { formatDate, initDateFormat, DEFAULT_PRESETS } from "../../../core";
16
17
  import AdminLayout from "../../../admin/layouts/AdminLayout.astro";
17
18
 
@@ -43,6 +44,9 @@ for (const [name, preset] of Object.entries(mergedPresets)) {
43
44
  seenAspects.add(preset.aspect);
44
45
  cropPresets.push({ name, aspect: preset.aspect });
45
46
  }
47
+ const { refs: usage, incomplete: usageIncomplete } = await findAssetUsage(config, asset.storagePath);
48
+ const usageCount = usage.reduce((sum, ref) => sum + ref.docs.length, 0);
49
+
46
50
  const currentFolder = asset.folder ? await folders.findById(asset.folder) : null;
47
51
  const allFolders = await folders.findAll();
48
52
 
@@ -84,7 +88,14 @@ const folderItems = flattenByParent(
84
88
  <button type="submit" form="asset-form" value="save" disabled class={buttonVariants({ variant: "outline" })}>
85
89
  Save
86
90
  </button>
87
- <DocumentActions client:load formId="asset-form" showDelete={true} />
91
+ <DocumentActions
92
+ client:load
93
+ formId="asset-form"
94
+ showDelete={true}
95
+ entityLabel="asset"
96
+ referencesEndpoint={`/api/cms/asset-usage?id=${asset._id}`}
97
+ forceOnConfirm={true}
98
+ />
88
99
  </div>
89
100
 
90
101
  <UnsavedGuard client:load formId="asset-form" isNew={false} isDraft={false} />
@@ -109,41 +120,6 @@ const folderItems = flattenByParent(
109
120
  </div>
110
121
 
111
122
  <div class="space-y-6 text-sm [&_input]:text-sm [&_textarea]:text-sm">
112
- <AdminCard title="Info">
113
- <dl class="grid gap-3">
114
- <div>
115
- <dt class="text-muted-foreground text-xs">Filename</dt>
116
- <dd class="mt-0.5">{asset.filename}</dd>
117
- </div>
118
- <div>
119
- <dt class="text-muted-foreground text-xs">Type</dt>
120
- <dd class="mt-0.5">{asset.mimeType}</dd>
121
- </div>
122
- <div>
123
- <dt class="text-muted-foreground text-xs">Size</dt>
124
- <dd class="mt-0.5">{formatSize(asset.size)}</dd>
125
- </div>
126
- {
127
- asset.width && asset.height && (
128
- <div>
129
- <dt class="text-muted-foreground text-xs">Dimensions</dt>
130
- <dd class="mt-0.5">
131
- {asset.width} &times; {asset.height} px
132
- </dd>
133
- </div>
134
- )
135
- }
136
- <div>
137
- <dt class="text-muted-foreground text-xs">Path</dt>
138
- <dd class="mt-0.5 font-mono text-xs break-all">{asset.storagePath}</dd>
139
- </div>
140
- <div>
141
- <dt class="text-muted-foreground text-xs">Created</dt>
142
- <dd class="mt-0.5">{formatDate(asset._createdAt)}</dd>
143
- </div>
144
- </dl>
145
- </AdminCard>
146
-
147
123
  <AdminCard title="Details">
148
124
  <div class="grid gap-5">
149
125
  <div class="grid gap-2">
@@ -182,6 +158,55 @@ const folderItems = flattenByParent(
182
158
  </div>
183
159
  </div>
184
160
  </AdminCard>
161
+
162
+ <AdminCard title="Info">
163
+ <dl class="grid gap-3">
164
+ <div>
165
+ <dt class="text-muted-foreground text-xs">Filename</dt>
166
+ <dd class="mt-0.5">{asset.filename}</dd>
167
+ </div>
168
+ <div>
169
+ <dt class="text-muted-foreground text-xs">Type</dt>
170
+ <dd class="mt-0.5">{asset.mimeType}</dd>
171
+ </div>
172
+ <div>
173
+ <dt class="text-muted-foreground text-xs">Size</dt>
174
+ <dd class="mt-0.5">{formatSize(asset.size)}</dd>
175
+ </div>
176
+ {
177
+ asset.width && asset.height && (
178
+ <div>
179
+ <dt class="text-muted-foreground text-xs">Dimensions</dt>
180
+ <dd class="mt-0.5">
181
+ {asset.width} &times; {asset.height} px
182
+ </dd>
183
+ </div>
184
+ )
185
+ }
186
+ <div>
187
+ <dt class="text-muted-foreground text-xs">Path</dt>
188
+ <dd class="mt-0.5 font-mono text-xs break-all">{asset.storagePath}</dd>
189
+ </div>
190
+ <div>
191
+ <dt class="text-muted-foreground text-xs">Created</dt>
192
+ <dd class="mt-0.5">{formatDate(asset._createdAt)}</dd>
193
+ </div>
194
+ </dl>
195
+ </AdminCard>
196
+
197
+ {
198
+ usageCount > 0 ? (
199
+ <ReverseReferencesList reverseRefs={usage} variant="record" title="Used in" />
200
+ ) : (
201
+ <AdminCard title="Used in">
202
+ <p class="text-muted-foreground text-sm">
203
+ {usageIncomplete.length > 0
204
+ ? `Could not check ${usageIncomplete.join(", ")} — usage is unknown.`
205
+ : "Not used by any document."}
206
+ </p>
207
+ </AdminCard>
208
+ )
209
+ }
185
210
  </div>
186
211
  </div>
187
212
  </form>
@@ -0,0 +1,53 @@
1
+ import type { APIRoute } from "astro";
2
+ import config from "virtual:kide/config";
3
+ import { assets, countAssetUsage, findAssetUsage } from "virtual:kide/runtime";
4
+
5
+ export const prerender = false;
6
+
7
+ /**
8
+ * Where assets are used. Deliberately not under /api/cms/assets/… — a static
9
+ * segment there is shadowed by the [id] route whenever it is not registered,
10
+ * which turns a missing route into a plausible-looking "Not found" for an asset.
11
+ *
12
+ * `?id=<assetId>` → { usage, total, incomplete } — the detail list
13
+ * `?ids=<id>,<id>,…` → { counts, incomplete } — for delete confirmations
14
+ *
15
+ * `incomplete` lists collections that could not be searched; a caller must not
16
+ * read an empty result as "unused" while it is non-empty.
17
+ */
18
+ export const GET: APIRoute = async ({ url }) => {
19
+ const id = url.searchParams.get("id");
20
+ const ids = url.searchParams.get("ids");
21
+
22
+ if (id) {
23
+ const asset = await assets.findById(id);
24
+ if (!asset) return Response.json({ error: "Not found." }, { status: 404 });
25
+
26
+ const { refs, incomplete } = await findAssetUsage(config, asset.storagePath);
27
+ const total = refs.reduce((sum, ref) => sum + ref.docs.length, 0);
28
+ return Response.json({ usage: refs, total, incomplete });
29
+ }
30
+
31
+ if (ids) {
32
+ const requested = ids
33
+ .split(",")
34
+ .map((value) => value.trim())
35
+ .filter(Boolean)
36
+ .slice(0, 200);
37
+
38
+ const records = (await Promise.all(requested.map((assetId) => assets.findById(assetId)))).filter(
39
+ (asset): asset is NonNullable<typeof asset> => !!asset,
40
+ );
41
+
42
+ const { counts: byPath, incomplete } = await countAssetUsage(
43
+ config,
44
+ records.map((asset) => asset.storagePath),
45
+ );
46
+ const counts: Record<string, number> = {};
47
+ for (const asset of records) counts[asset._id] = byPath[asset.storagePath] ?? 0;
48
+
49
+ return Response.json({ counts, incomplete });
50
+ }
51
+
52
+ return Response.json({ error: "Pass ?id= or ?ids=." }, { status: 400 });
53
+ };
@@ -1,5 +1,6 @@
1
1
  import type { APIRoute } from "astro";
2
- import { assets } from "virtual:kide/runtime";
2
+ import config from "virtual:kide/config";
3
+ import { AssetInUseError, assets } from "virtual:kide/runtime";
3
4
 
4
5
  export const prerender = false;
5
6
 
@@ -42,11 +43,21 @@ export const PATCH: APIRoute = async ({ params, request, locals }) => {
42
43
  return Response.json(result);
43
44
  };
44
45
 
45
- export const DELETE: APIRoute = async ({ params, locals }) => {
46
+ export const DELETE: APIRoute = async ({ params, request, locals }) => {
46
47
  const id = params.id;
47
48
  if (!id) return new Response(null, { status: 400 });
48
49
 
49
- await assets.delete(id, { actor: getActor(locals) });
50
+ const force = new URL(request.url).searchParams.get("force") === "1";
51
+
52
+ try {
53
+ await assets.delete(id, { actor: getActor(locals), force, config });
54
+ } catch (error) {
55
+ if (error instanceof AssetInUseError) {
56
+ return Response.json({ error: error.message, usage: error.usage, incomplete: error.incomplete }, { status: 409 });
57
+ }
58
+ throw error;
59
+ }
60
+
50
61
  return new Response(null, { status: 204 });
51
62
  };
52
63
 
@@ -60,7 +71,17 @@ export const POST: APIRoute = async ({ params, request, locals }) => {
60
71
  const actor = getActor(locals);
61
72
 
62
73
  if (method === "DELETE" || action === "delete") {
63
- await assets.delete(id, { actor });
74
+ try {
75
+ await assets.delete(id, { actor, force: formData.get("_force") === "1", config });
76
+ } catch (error) {
77
+ if (error instanceof AssetInUseError) {
78
+ return new Response(null, {
79
+ status: 303,
80
+ headers: { Location: `/admin/assets/${id}?_toast=error&_msg=${encodeURIComponent(error.message)}` },
81
+ });
82
+ }
83
+ throw error;
84
+ }
64
85
  return new Response(null, {
65
86
  status: 303,
66
87
  headers: { Location: "/admin/assets?_toast=success&_msg=Asset+deleted" },
@@ -27,7 +27,7 @@ export const GET: APIRoute = async ({ params, url }) => {
27
27
  // and uploads live in object storage rather than public/ — so transformImage
28
28
  // can't run. Attempt it, but fall back to streaming the untransformed original
29
29
  // from storage so images still load. (In production on Cloudflare this route
30
- // is bypassed entirely: cmsImage() emits /cdn-cgi/image URLs there.)
30
+ // is bypassed entirely: cmsImageUrl() emits /cdn-cgi/image URLs there.)
31
31
  try {
32
32
  const result = await transformImage(src, {
33
33
  width: num("w"),