@kidecms/core 0.20.0 → 0.22.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/admin/components/BlockEditor.tsx +4 -12
- package/admin/components/CommandPalette.tsx +19 -72
- package/admin/components/ContentEditor.tsx +5 -10
- package/admin/components/DocumentCombobox.tsx +171 -0
- package/admin/components/FieldControl.astro +17 -32
- package/admin/components/InternalLinkPicker.tsx +30 -62
- package/admin/components/LinkField.tsx +26 -12
- package/admin/components/RelationField.tsx +32 -58
- package/admin/components/RepeaterInput.tsx +3 -6
- package/admin/components/SharedSectionBlockField.tsx +3 -6
- package/admin/components/TreeItemsEditor.tsx +4 -4
- package/admin/components/TreeSelect.tsx +33 -19
- package/admin/components/block-fields.tsx +37 -50
- package/admin/components/content-block-spec.ts +5 -6
- package/admin/lib/edit-data.ts +84 -129
- package/admin/lib/use-document-search.ts +107 -0
- package/admin/views/EditView.astro +18 -27
- package/admin/views/ListView.astro +3 -1
- package/admin/views/RecentView.astro +32 -9
- package/core/api.ts +3 -1
- package/core/generator.ts +20 -10
- package/core/index.ts +2 -0
- package/core/migrate.ts +17 -1
- package/core/values.ts +32 -0
- package/internals/context.ts +4 -2
- package/internals/push.ts +8 -2
- package/package.json +1 -1
- package/routes/api/admin/search.ts +102 -45
package/core/index.ts
CHANGED
|
@@ -165,11 +165,13 @@ export {
|
|
|
165
165
|
slugify,
|
|
166
166
|
escapeHtml,
|
|
167
167
|
safeUrl,
|
|
168
|
+
resolveLinkUrl,
|
|
168
169
|
serializeFieldValue,
|
|
169
170
|
contentSegments,
|
|
170
171
|
contentBlocks,
|
|
171
172
|
contentToPlainText,
|
|
172
173
|
} from "./values";
|
|
174
|
+
export type { StoredLink } from "./values";
|
|
173
175
|
export type { ContentSegment } from "./values";
|
|
174
176
|
export { cmsImageUrl, cmsSrcset, transformImage, DEFAULT_PRESETS, resolveImagePreset } from "./image";
|
|
175
177
|
export type { CropOptions, TransformOptions } from "./image";
|
package/core/migrate.ts
CHANGED
|
@@ -123,18 +123,33 @@ export type ImportReport = {
|
|
|
123
123
|
errors: Array<{ collection: string; id: unknown; message: string }>;
|
|
124
124
|
};
|
|
125
125
|
|
|
126
|
+
/** Thrown by a real (non-dry) import run that had failures. Carries the full report. */
|
|
127
|
+
export class ImportFailedError extends Error {
|
|
128
|
+
report: ImportReport;
|
|
129
|
+
constructor(report: ImportReport) {
|
|
130
|
+
const first = report.errors[0]?.message ?? report.invalid[0]?.errors[0]?.message ?? "see report";
|
|
131
|
+
super(`Import failed for ${report.failed} of ${report.total} documents (first: ${first})`);
|
|
132
|
+
this.name = "ImportFailedError";
|
|
133
|
+
this.report = report;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
126
137
|
type AnyCms = Record<string, any>;
|
|
127
138
|
|
|
128
139
|
/**
|
|
129
140
|
* Validate then (unless dryRun) create every item via the typed API. Use
|
|
130
141
|
* `{ _system: true, _skipSearch: true }` context for bulk imports and call
|
|
131
142
|
* `reindex()` once afterwards.
|
|
143
|
+
*
|
|
144
|
+
* A real run throws ImportFailedError when any document fails, so a half-applied
|
|
145
|
+
* import can't look like success; pass `throwOnFailed: false` to get the report
|
|
146
|
+
* back instead. Dry runs always return the report.
|
|
132
147
|
*/
|
|
133
148
|
export const importDocuments = async (
|
|
134
149
|
cms: AnyCms,
|
|
135
150
|
config: CMSConfig,
|
|
136
151
|
items: ImportItem[],
|
|
137
|
-
options: { dryRun?: boolean; context?: Record<string, unknown> } = {},
|
|
152
|
+
options: { dryRun?: boolean; throwOnFailed?: boolean; context?: Record<string, unknown> } = {},
|
|
138
153
|
): Promise<ImportReport> => {
|
|
139
154
|
const dryRun = options.dryRun ?? false;
|
|
140
155
|
const context = options.context ?? { _system: true, _skipSearch: true };
|
|
@@ -178,6 +193,7 @@ export const importDocuments = async (
|
|
|
178
193
|
report.failed++;
|
|
179
194
|
}
|
|
180
195
|
}
|
|
196
|
+
if (!dryRun && report.failed > 0 && (options.throwOnFailed ?? true)) throw new ImportFailedError(report);
|
|
181
197
|
return report;
|
|
182
198
|
};
|
|
183
199
|
|
package/core/values.ts
CHANGED
|
@@ -273,6 +273,38 @@ export const safeUrl = (value: string): string | null => {
|
|
|
273
273
|
}
|
|
274
274
|
};
|
|
275
275
|
|
|
276
|
+
/** Value shape stored by the admin's link field. */
|
|
277
|
+
export type StoredLink = {
|
|
278
|
+
type?: string;
|
|
279
|
+
url?: string;
|
|
280
|
+
label?: string;
|
|
281
|
+
title?: string;
|
|
282
|
+
newTab?: boolean;
|
|
283
|
+
docId?: string;
|
|
284
|
+
collection?: string;
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Current href for a stored link value. A link picked with the internal
|
|
289
|
+
* document picker carries a document reference (docId + collection) — resolve
|
|
290
|
+
* the document's route fresh so the link survives slug edits. The stored `url`
|
|
291
|
+
* is the fallback: external links, hand-typed paths, links saved before the
|
|
292
|
+
* reference existed, and references to unpublished or deleted documents.
|
|
293
|
+
*/
|
|
294
|
+
export const resolveLinkUrl = async (
|
|
295
|
+
cms: Record<string, any>,
|
|
296
|
+
link: StoredLink | null | undefined,
|
|
297
|
+
): Promise<string | null> => {
|
|
298
|
+
if (!link) return null;
|
|
299
|
+
const fallback = link.url ? safeUrl(String(link.url)) : null;
|
|
300
|
+
if (!link.docId || !link.collection) return fallback;
|
|
301
|
+
const api = cms[link.collection];
|
|
302
|
+
if (!api?.findById) return fallback;
|
|
303
|
+
const doc = await api.findById(link.docId).catch(() => null);
|
|
304
|
+
if (!doc) return fallback;
|
|
305
|
+
return cms.meta?.getRouteForDocument?.(link.collection, doc) ?? fallback;
|
|
306
|
+
};
|
|
307
|
+
|
|
276
308
|
const renderNode = (node: RichTextNode): string => {
|
|
277
309
|
if (node.type === "text") {
|
|
278
310
|
let content = escapeHtml(String(node.value ?? ""));
|
package/internals/context.ts
CHANGED
|
@@ -48,8 +48,10 @@ export const createCmsContext = async () => {
|
|
|
48
48
|
/** The resolved CMS config. */
|
|
49
49
|
config,
|
|
50
50
|
/** Validate + create a batch of documents. Pass `{ dryRun: true }` for a report only. */
|
|
51
|
-
load: (
|
|
52
|
-
|
|
51
|
+
load: (
|
|
52
|
+
items: ImportItem[],
|
|
53
|
+
options?: { dryRun?: boolean; throwOnFailed?: boolean; context?: Record<string, unknown> },
|
|
54
|
+
) => importDocuments(cms as Record<string, any>, config, items, options),
|
|
53
55
|
/** The machine-readable content model (same as `.kide/model.json`). */
|
|
54
56
|
model: () => describeModel(config),
|
|
55
57
|
/** Rebuild the search index for all searchable collections (uses this config's locales). */
|
package/internals/push.ts
CHANGED
|
@@ -44,11 +44,17 @@ const parseRecreate = (): string[] => {
|
|
|
44
44
|
const arg = process.argv.find((a) => a.startsWith("--recreate="))?.slice("--recreate=".length);
|
|
45
45
|
const raw = process.env.RECREATE ?? arg ?? "";
|
|
46
46
|
const tables = new Set<string>();
|
|
47
|
+
// Same slug → table-name mapping as the generator, so e.g. front-page finds cms_front_page.
|
|
48
|
+
const snakeCase = (value: string) =>
|
|
49
|
+
value
|
|
50
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
51
|
+
.replace(/[^a-zA-Z0-9]+/g, "_")
|
|
52
|
+
.toLowerCase();
|
|
47
53
|
for (const name of raw
|
|
48
54
|
.split(",")
|
|
49
55
|
.map((s) => s.trim())
|
|
50
56
|
.filter(Boolean)) {
|
|
51
|
-
const base = name.startsWith("cms_") ? name : `cms_${name}`;
|
|
57
|
+
const base = name.startsWith("cms_") ? name : `cms_${snakeCase(name)}`;
|
|
52
58
|
tables.add(base);
|
|
53
59
|
tables.add(`${base}_translations`);
|
|
54
60
|
tables.add(`${base}_versions`);
|
|
@@ -73,7 +79,7 @@ async function main() {
|
|
|
73
79
|
sqlite.close();
|
|
74
80
|
process.exit(1);
|
|
75
81
|
}
|
|
76
|
-
for (const t of recreate) sqlite.exec(`DROP TABLE IF EXISTS ${t}`);
|
|
82
|
+
for (const t of recreate) sqlite.exec(`DROP TABLE IF EXISTS "${t}"`);
|
|
77
83
|
console.log(`[cms:push] dropped for recreate: ${recreate.join(", ")}`);
|
|
78
84
|
}
|
|
79
85
|
|
package/package.json
CHANGED
|
@@ -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
|
|
11
|
-
const
|
|
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
|
-
|
|
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
|
|
31
|
-
|
|
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
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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
|
-
|
|
75
|
-
results.
|
|
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 >=
|
|
142
|
+
if (results.length >= PALETTE_TOTAL_CAP) break;
|
|
86
143
|
}
|
|
87
144
|
|
|
88
145
|
return Response.json({ results });
|