@kidecms/core 0.20.0 → 0.21.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.
@@ -6,35 +6,111 @@ import { getLabelField } from "../../../core";
6
6
 
7
7
  export const prerender = false;
8
8
 
9
+ /**
10
+ * Document lookup for the admin. Serves three callers with one shape:
11
+ *
12
+ * ?q=term command palette — every collection, a few hits each
13
+ * ?q=term&collection=a,b&limit=20 relation / internal-link pickers — the target collections only
14
+ * ?collection=a&ids=x,y label resolution for already-selected values
15
+ * ?collection=a no query yet — the most recently updated documents
16
+ *
17
+ * Every read goes through `find()` with the caller's user, so collection and
18
+ * per-document access rules apply exactly as in the admin lists.
19
+ */
9
20
  const HIDDEN_FROM_SEARCH = new Set(["form-submissions"]);
10
- const PER_COLLECTION = 5;
11
- const TOTAL_CAP = 30;
21
+ const MIN_QUERY_LENGTH = 2;
22
+ const PALETTE_PER_COLLECTION = 5;
23
+ const PALETTE_TOTAL_CAP = 30;
24
+ const PICKER_DEFAULT_LIMIT = 20;
25
+ const PICKER_MAX_LIMIT = 50;
26
+ const MAX_IDS = 200;
12
27
 
13
- type SearchResult = {
28
+ export type SearchResult = {
14
29
  collection: string;
15
30
  collectionLabel: string;
16
31
  docId: string;
17
32
  title: string;
18
33
  editUrl: string;
34
+ /** Public route of the document (internal-link pickers store this). */
35
+ href: string | null;
19
36
  status: string | null;
20
37
  };
21
38
 
39
+ type CollectionLike = { slug: string; singleton?: boolean; labels: { singular: string; plural: string } };
40
+
41
+ const csv = (value: string | null) =>
42
+ (value ?? "")
43
+ .split(",")
44
+ .map((s) => s.trim())
45
+ .filter(Boolean);
46
+
22
47
  export const GET: APIRoute = async ({ url, locals }) => {
23
48
  if (!locals.user) {
24
49
  return Response.json({ error: "Unauthorized" }, { status: 401 });
25
50
  }
26
51
 
52
+ const cmsAny = cms as Record<string, any>;
53
+ const context = { user: locals.user };
27
54
  const q = (url.searchParams.get("q") ?? "").trim();
28
- if (q.length < 2) return Response.json({ results: [] });
55
+ const requested = csv(url.searchParams.get("collection"));
56
+ const ids = csv(url.searchParams.get("ids")).slice(0, MAX_IDS);
57
+ const limit = Math.min(Math.max(Number(url.searchParams.get("limit")) || PICKER_DEFAULT_LIMIT, 1), PICKER_MAX_LIMIT);
29
58
 
30
- const cmsAny = cms as Record<string, any>;
31
- const results: SearchResult[] = [];
59
+ const toResult = (collection: CollectionLike, doc: Record<string, unknown>): SearchResult => ({
60
+ collection: collection.slug,
61
+ collectionLabel: collection.singleton ? "Single" : collection.labels.singular,
62
+ docId: String(doc._id),
63
+ title: collection.singleton
64
+ ? collection.labels.singular
65
+ : String(doc[getLabelField(collection as any)] ?? doc.slug ?? doc._id),
66
+ editUrl: `/admin/${collection.slug}/${doc._id}`,
67
+ href: cmsAny.meta?.getRouteForDocument?.(collection.slug, doc) ?? null,
68
+ status: typeof doc._status === "string" ? doc._status : null,
69
+ });
70
+
71
+ // Picker mode: explicit target collections.
72
+ if (requested.length > 0) {
73
+ const collections = (config.collections as CollectionLike[]).filter(
74
+ (c) => requested.includes(c.slug) && !HIDDEN_FROM_SEARCH.has(c.slug),
75
+ );
76
+ const results: SearchResult[] = [];
77
+
78
+ for (const collection of collections) {
79
+ const api = cmsAny[collection.slug];
80
+ if (!api?.find) continue;
81
+
82
+ // access denied or runtime error — skip this collection silently, like the palette
83
+ const docs: Array<Record<string, unknown>> | null = await (async () => {
84
+ if (ids.length > 0) {
85
+ const found = await Promise.all(
86
+ ids.map((id) =>
87
+ api.find({ where: { _id: id }, status: "any", limit: 1 }, context).then((d: any[]) => d[0]),
88
+ ),
89
+ );
90
+ return found.filter(Boolean);
91
+ }
92
+ // Recently-updated first in both modes — without a sort, LIMIT keeps an
93
+ // arbitrary subset of the matches.
94
+ 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);
97
+ })().catch(() => null);
98
+
99
+ if (!docs) continue;
100
+ for (const doc of docs) results.push(toResult(collection, doc));
101
+ }
102
+
103
+ return Response.json({ results });
104
+ }
32
105
 
106
+ // Palette mode: everything, a few hits per collection.
107
+ if (q.length < MIN_QUERY_LENGTH) return Response.json({ results: [] });
108
+
109
+ const results: SearchResult[] = [];
33
110
  const qLower = q.toLowerCase();
34
111
 
35
- for (const collection of config.collections) {
112
+ for (const collection of config.collections as CollectionLike[]) {
36
113
  if (HIDDEN_FROM_SEARCH.has(collection.slug)) continue;
37
-
38
114
  const api = cmsAny[collection.slug];
39
115
  if (!api?.find) continue;
40
116
 
@@ -42,47 +118,28 @@ export const GET: APIRoute = async ({ url, locals }) => {
42
118
  // on the collection's singular label (which is what gets shown to admins). Body-search
43
119
  // would fight UX: e.g. searching "front" for the "Front page" singleton must find it
44
120
  // even if the singleton's body text says nothing about "front".
45
- if (collection.singleton) {
46
- if (!collection.labels.singular.toLowerCase().includes(qLower)) continue;
47
- const docs = await api
48
- .find({ status: "any", limit: 1 }, { user: locals.user })
49
- .catch(() => null as Array<Record<string, unknown>> | null);
50
- if (!docs || docs.length === 0) continue;
51
- const doc = docs[0];
52
- results.push({
53
- collection: collection.slug,
54
- // Match the sidebar grouping: every singleton lives under one "Singles" header.
55
- collectionLabel: "Single",
56
- docId: String(doc._id),
57
- title: collection.labels.singular,
58
- editUrl: `/admin/${collection.slug}/${doc._id}`,
59
- status: typeof doc._status === "string" ? doc._status : null,
60
- });
61
- if (results.length >= TOTAL_CAP) break;
62
- continue;
63
- }
121
+ const docs: Array<Record<string, unknown>> | null = collection.singleton
122
+ ? collection.labels.singular.toLowerCase().includes(qLower)
123
+ ? await api.find({ status: "any", limit: 1 }, context).catch(() => null)
124
+ : []
125
+ : await api
126
+ .find(
127
+ {
128
+ search: q,
129
+ status: "any",
130
+ sort: { field: "_updatedAt", direction: "desc" },
131
+ limit: PALETTE_PER_COLLECTION,
132
+ },
133
+ context,
134
+ )
135
+ .catch(() => null);
64
136
 
65
- const docs = await api
66
- .find({ search: q, status: "any", limit: PER_COLLECTION }, { user: locals.user })
67
- .catch(() => null as Array<Record<string, unknown>> | null);
68
-
69
- // access denied or runtime error — skip this collection silently
70
137
  if (!docs) continue;
71
-
72
- const labelField = getLabelField(collection);
73
138
  for (const doc of docs) {
74
- const title = String(doc[labelField] ?? doc.slug ?? doc._id);
75
- results.push({
76
- collection: collection.slug,
77
- collectionLabel: collection.labels.singular,
78
- docId: String(doc._id),
79
- title,
80
- editUrl: `/admin/${collection.slug}/${doc._id}`,
81
- status: typeof doc._status === "string" ? doc._status : null,
82
- });
83
- if (results.length >= TOTAL_CAP) break;
139
+ results.push(toResult(collection, doc));
140
+ if (results.length >= PALETTE_TOTAL_CAP) break;
84
141
  }
85
- if (results.length >= TOTAL_CAP) break;
142
+ if (results.length >= PALETTE_TOTAL_CAP) break;
86
143
  }
87
144
 
88
145
  return Response.json({ results });