@kidecms/core 0.31.1 → 0.33.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/DocumentsDataTable.tsx +38 -17
- package/admin/components/FieldControl.astro +12 -8
- package/admin/components/ReadOnlyRepeater.astro +41 -0
- package/admin/components/block-fields.tsx +2 -11
- package/admin/components/block-values.ts +47 -1
- package/admin/lib/access.ts +16 -0
- package/admin/views/EditView.astro +33 -17
- package/admin/views/ListView.astro +3 -2
- package/core/api.ts +239 -48
- package/core/generator.ts +33 -9
- package/core/index.ts +1 -1
- package/internals/context.ts +8 -3
- package/internals/mcp.ts +3 -2
- package/package.json +1 -1
|
@@ -85,6 +85,8 @@ type DocumentsDataTableProps = {
|
|
|
85
85
|
collectionSlug: string;
|
|
86
86
|
draftsEnabled?: boolean;
|
|
87
87
|
duplicateEnabled?: boolean;
|
|
88
|
+
/** Offer Delete on rows and selections; false when the collection's delete rule denies it. */
|
|
89
|
+
deleteEnabled?: boolean;
|
|
88
90
|
/** Show the Locales column. Defaults to true for callers (e.g. Recent) that mix collections. */
|
|
89
91
|
showLocalesColumn?: boolean;
|
|
90
92
|
defaultLocale?: string;
|
|
@@ -156,6 +158,7 @@ export default function DocumentsDataTable({
|
|
|
156
158
|
collectionSlug,
|
|
157
159
|
draftsEnabled = false,
|
|
158
160
|
duplicateEnabled = true,
|
|
161
|
+
deleteEnabled = true,
|
|
159
162
|
showLocalesColumn = true,
|
|
160
163
|
defaultLocale,
|
|
161
164
|
labelField = "title",
|
|
@@ -627,21 +630,35 @@ export default function DocumentsDataTable({
|
|
|
627
630
|
</DropdownMenuItem>
|
|
628
631
|
</>
|
|
629
632
|
)}
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
633
|
+
{deleteEnabled && (
|
|
634
|
+
<>
|
|
635
|
+
<DropdownMenuSeparator />
|
|
636
|
+
<DropdownMenuItem
|
|
637
|
+
variant="destructive"
|
|
638
|
+
disabled={isPending}
|
|
639
|
+
onClick={() => setDeleteConfirm([row.original])}
|
|
640
|
+
>
|
|
641
|
+
Delete
|
|
642
|
+
</DropdownMenuItem>
|
|
643
|
+
</>
|
|
644
|
+
)}
|
|
638
645
|
</DropdownMenuContent>
|
|
639
646
|
</DropdownMenu>
|
|
640
647
|
</div>
|
|
641
648
|
),
|
|
642
649
|
},
|
|
643
650
|
],
|
|
644
|
-
[
|
|
651
|
+
[
|
|
652
|
+
columns,
|
|
653
|
+
draftsEnabled,
|
|
654
|
+
duplicateEnabled,
|
|
655
|
+
deleteEnabled,
|
|
656
|
+
showLocalesColumn,
|
|
657
|
+
isPending,
|
|
658
|
+
primaryColumnKey,
|
|
659
|
+
isServerMode,
|
|
660
|
+
runAction,
|
|
661
|
+
],
|
|
645
662
|
);
|
|
646
663
|
|
|
647
664
|
const table = useReactTable({
|
|
@@ -796,14 +813,18 @@ export default function DocumentsDataTable({
|
|
|
796
813
|
))}
|
|
797
814
|
</>
|
|
798
815
|
)}
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
816
|
+
{deleteEnabled && (
|
|
817
|
+
<>
|
|
818
|
+
<DropdownMenuSeparator />
|
|
819
|
+
<DropdownMenuItem
|
|
820
|
+
variant="destructive"
|
|
821
|
+
disabled={isPending}
|
|
822
|
+
onClick={() => setDeleteConfirm(selectedRows)}
|
|
823
|
+
>
|
|
824
|
+
Delete selected
|
|
825
|
+
</DropdownMenuItem>
|
|
826
|
+
</>
|
|
827
|
+
)}
|
|
807
828
|
</DropdownMenuContent>
|
|
808
829
|
</DropdownMenu>
|
|
809
830
|
)}
|
|
@@ -17,6 +17,7 @@ import SharedSectionBlockField from "./SharedSectionBlockField";
|
|
|
17
17
|
import ColorField from "./ColorField";
|
|
18
18
|
import LinkField from "./LinkField";
|
|
19
19
|
import RepeaterInput from "./RepeaterInput";
|
|
20
|
+
import ReadOnlyRepeater from "./ReadOnlyRepeater.astro";
|
|
20
21
|
import type { SubFieldMeta } from "./block-fields";
|
|
21
22
|
import { Input } from "./ui/input";
|
|
22
23
|
import { Label } from "./ui/label";
|
|
@@ -141,6 +142,12 @@ const toBlockTypesMeta = (source: Record<string, Record<string, FieldConfig>> |
|
|
|
141
142
|
)
|
|
142
143
|
: {};
|
|
143
144
|
|
|
145
|
+
const repeaterItemFields =
|
|
146
|
+
"itemFields" in field && field.itemFields
|
|
147
|
+
? Object.fromEntries(
|
|
148
|
+
Object.entries(field.itemFields).map(([subName, subField]) => [subName, toSubFieldMeta(subField)]),
|
|
149
|
+
)
|
|
150
|
+
: undefined;
|
|
144
151
|
const blockTypesSource = field.type === "blocks" ? field.types : field.type === "content" ? field.blocks : null;
|
|
145
152
|
const blockTypesMeta = toBlockTypesMeta(blockTypesSource);
|
|
146
153
|
const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
|
|
@@ -412,21 +419,18 @@ const sharedBlockTypesMeta = toBlockTypesMeta(sharedBlockTypes);
|
|
|
412
419
|
client:load
|
|
413
420
|
name={name}
|
|
414
421
|
value={serializedValue}
|
|
415
|
-
itemFields={
|
|
416
|
-
"itemFields" in field && field.itemFields
|
|
417
|
-
? Object.fromEntries(
|
|
418
|
-
Object.entries(field.itemFields).map(([subName, subField]) => [subName, toSubFieldMeta(subField)]),
|
|
419
|
-
)
|
|
420
|
-
: undefined
|
|
421
|
-
}
|
|
422
|
+
itemFields={repeaterItemFields}
|
|
422
423
|
linkOptions={linkableCollections}
|
|
423
424
|
/>
|
|
424
425
|
)}
|
|
425
426
|
|
|
427
|
+
{field.type === "json" && field.admin?.component === "repeater" && readOnly && (
|
|
428
|
+
<ReadOnlyRepeater name={name} value={serializedValue} itemFields={repeaterItemFields} />
|
|
429
|
+
)}
|
|
430
|
+
|
|
426
431
|
{field.type === "json" &&
|
|
427
432
|
(field.admin?.component === "menu-items" ||
|
|
428
433
|
field.admin?.component === "taxonomy-terms" ||
|
|
429
|
-
field.admin?.component === "repeater" ||
|
|
430
434
|
field.admin?.component === "shared-section-block") &&
|
|
431
435
|
readOnly && (
|
|
432
436
|
<Textarea
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
---
|
|
2
|
+
import { repeaterTable } from "./block-values";
|
|
3
|
+
import type { SubFieldMeta } from "./block-fields";
|
|
4
|
+
|
|
5
|
+
const { name, value, itemFields } = Astro.props as {
|
|
6
|
+
name: string;
|
|
7
|
+
value?: string;
|
|
8
|
+
itemFields?: Record<string, SubFieldMeta>;
|
|
9
|
+
};
|
|
10
|
+
const { columns, rows } = repeaterTable(value, itemFields);
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
<input type="hidden" name={name} value={value ?? "[]"} />
|
|
14
|
+
{
|
|
15
|
+
rows.length === 0 ? (
|
|
16
|
+
<p class="text-muted-foreground text-sm">No items</p>
|
|
17
|
+
) : (
|
|
18
|
+
<div class="bg-muted/40 overflow-x-auto rounded-md border">
|
|
19
|
+
<table class="w-full text-sm">
|
|
20
|
+
<thead>
|
|
21
|
+
<tr class="border-b">
|
|
22
|
+
{columns.map((column) => (
|
|
23
|
+
<th scope="col" class="text-muted-foreground px-3 py-2 text-left font-medium whitespace-nowrap">
|
|
24
|
+
{column.label}
|
|
25
|
+
</th>
|
|
26
|
+
))}
|
|
27
|
+
</tr>
|
|
28
|
+
</thead>
|
|
29
|
+
<tbody class="divide-y">
|
|
30
|
+
{rows.map((row) => (
|
|
31
|
+
<tr>
|
|
32
|
+
{row.map((cell) => (
|
|
33
|
+
<td class="text-muted-foreground px-3 py-2 align-top">{cell}</td>
|
|
34
|
+
))}
|
|
35
|
+
</tr>
|
|
36
|
+
))}
|
|
37
|
+
</tbody>
|
|
38
|
+
</table>
|
|
39
|
+
</div>
|
|
40
|
+
)
|
|
41
|
+
}
|
|
@@ -71,18 +71,9 @@ export function generateKey() {
|
|
|
71
71
|
return "blk_" + Math.random().toString(36).slice(2, 9);
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
export function humanize(value: string) {
|
|
75
|
-
return value
|
|
76
|
-
.replace(/^_+/, "")
|
|
77
|
-
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
78
|
-
.replace(/[-_]/g, " ")
|
|
79
|
-
.replace(/\s+/g, " ")
|
|
80
|
-
.trim()
|
|
81
|
-
.replace(/^\w/, (char) => char.toUpperCase());
|
|
82
|
-
}
|
|
83
|
-
|
|
84
74
|
// Pure value helpers live in a React-free module so they can be unit-tested.
|
|
85
|
-
export { blankBlockFields, getPreviewText } from "./block-values";
|
|
75
|
+
export { blankBlockFields, getPreviewText, humanize } from "./block-values";
|
|
76
|
+
import { humanize } from "./block-values";
|
|
86
77
|
|
|
87
78
|
// -----------------------------------------------
|
|
88
79
|
// Sub-field label + control wrapper
|
|
@@ -2,6 +2,16 @@
|
|
|
2
2
|
// from block-fields.tsx) and unit-tested directly.
|
|
3
3
|
import type { SubFieldMeta } from "./block-fields";
|
|
4
4
|
|
|
5
|
+
export function humanize(value: string) {
|
|
6
|
+
return value
|
|
7
|
+
.replace(/^_+/, "")
|
|
8
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
9
|
+
.replace(/[-_]/g, " ")
|
|
10
|
+
.replace(/\s+/g, " ")
|
|
11
|
+
.trim()
|
|
12
|
+
.replace(/^\w/, (char) => char.toUpperCase());
|
|
13
|
+
}
|
|
14
|
+
|
|
5
15
|
/** Build a blank value object for a freshly inserted block of the given type. */
|
|
6
16
|
export function blankBlockFields(fieldsMeta: Record<string, SubFieldMeta>): Record<string, unknown> {
|
|
7
17
|
const out: Record<string, unknown> = {};
|
|
@@ -27,7 +37,11 @@ const richTextPreview = (value: unknown): string => {
|
|
|
27
37
|
}
|
|
28
38
|
const collect = (node: PreviewNode): string =>
|
|
29
39
|
typeof node.value === "string" ? node.value : (node.children ?? []).map(collect).join(" ");
|
|
30
|
-
return doc && typeof doc === "object"
|
|
40
|
+
return doc && typeof doc === "object"
|
|
41
|
+
? collect(doc as PreviewNode)
|
|
42
|
+
.replace(/\s+/g, " ")
|
|
43
|
+
.trim()
|
|
44
|
+
: "";
|
|
31
45
|
};
|
|
32
46
|
|
|
33
47
|
/**
|
|
@@ -50,3 +64,35 @@ export function getPreviewText(values: Record<string, unknown>, fieldsMeta: Reco
|
|
|
50
64
|
}
|
|
51
65
|
return "";
|
|
52
66
|
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Rows of a repeater value as display text, for read-only rendering. Columns
|
|
70
|
+
* follow `itemFields` when declared, otherwise every key seen in the rows.
|
|
71
|
+
*/
|
|
72
|
+
export function repeaterTable(
|
|
73
|
+
value: unknown,
|
|
74
|
+
itemFields?: Record<string, SubFieldMeta>,
|
|
75
|
+
): { columns: { key: string; label: string }[]; rows: string[][] } {
|
|
76
|
+
let items: unknown = value;
|
|
77
|
+
if (typeof items === "string") {
|
|
78
|
+
try {
|
|
79
|
+
items = JSON.parse(items || "[]");
|
|
80
|
+
} catch {
|
|
81
|
+
items = [];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const rows = (Array.isArray(items) ? items : []).filter(
|
|
85
|
+
(row): row is Record<string, unknown> => !!row && typeof row === "object" && !Array.isArray(row),
|
|
86
|
+
);
|
|
87
|
+
const keys = itemFields ? Object.keys(itemFields) : [...new Set(rows.flatMap((row) => Object.keys(row)))];
|
|
88
|
+
const text = (cell: unknown) => {
|
|
89
|
+
if (cell === null || cell === undefined || cell === "") return "–";
|
|
90
|
+
if (typeof cell === "boolean") return cell ? "Yes" : "No";
|
|
91
|
+
if (typeof cell === "object") return JSON.stringify(cell);
|
|
92
|
+
return String(cell);
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
columns: keys.map((key) => ({ key, label: itemFields?.[key]?.label ?? humanize(key) })),
|
|
96
|
+
rows: rows.map((row) => keys.map((key) => text(row[key]))),
|
|
97
|
+
};
|
|
98
|
+
}
|
package/admin/lib/access.ts
CHANGED
|
@@ -19,6 +19,22 @@ export function canWrite(config: CMSConfig, user: User, slug: string): boolean {
|
|
|
19
19
|
return rule({ user: user ?? null, doc: null, operation: "create", collection: slug }) as boolean;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/** Whether the collection's update rule lets this user edit the document. */
|
|
23
|
+
export function canUpdate(config: CMSConfig, user: User, slug: string, doc?: Record<string, unknown> | null): boolean {
|
|
24
|
+
const c = config.collections.find((col) => col.slug === slug);
|
|
25
|
+
const rule = c?.access?.update;
|
|
26
|
+
if (!rule) return c?.auth ? user?.role === "admin" || (!!doc && doc._id === user?.id) : true;
|
|
27
|
+
return rule({ user: user ?? null, doc: doc ?? null, operation: "update", collection: slug }) as boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether the collection's delete rule lets this user delete (the document, when given). */
|
|
31
|
+
export function canDelete(config: CMSConfig, user: User, slug: string, doc?: Record<string, unknown> | null): boolean {
|
|
32
|
+
const c = config.collections.find((col) => col.slug === slug);
|
|
33
|
+
const rule = c?.access?.delete;
|
|
34
|
+
if (!rule) return c?.auth ? user?.role === "admin" : true;
|
|
35
|
+
return rule({ user: user ?? null, doc: doc ?? null, operation: "delete", collection: slug }) as boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
22
38
|
export function isFieldHidden(
|
|
23
39
|
collection: { slug: string; fields: Record<string, any> } | null,
|
|
24
40
|
user: User,
|
|
@@ -26,6 +26,9 @@ import {
|
|
|
26
26
|
resolveCollaboration,
|
|
27
27
|
} from "../../core";
|
|
28
28
|
import {
|
|
29
|
+
canDelete,
|
|
30
|
+
canUpdate,
|
|
31
|
+
canWrite,
|
|
29
32
|
getFormAction,
|
|
30
33
|
getVisualStatus,
|
|
31
34
|
isFieldHidden as isFieldHiddenFn,
|
|
@@ -80,7 +83,8 @@ const collectionApi = cmsRuntime[collection.slug];
|
|
|
80
83
|
const isSingleton = collection.singleton === true;
|
|
81
84
|
|
|
82
85
|
const isFieldHidden = (fieldName: string) => isFieldHiddenFn(collection, user, fieldName);
|
|
83
|
-
|
|
86
|
+
// A document the collection rules won't let this user change renders every field read-only
|
|
87
|
+
const isFieldReadOnly = (fieldName: string) => !docEditable || isFieldReadOnlyFn(collection, user, fieldName);
|
|
84
88
|
|
|
85
89
|
// --- Data loading ---
|
|
86
90
|
let doc: Record<string, unknown> | null = null;
|
|
@@ -104,6 +108,16 @@ if (mode === "edit" && documentId) {
|
|
|
104
108
|
}
|
|
105
109
|
}
|
|
106
110
|
|
|
111
|
+
// Hide actions the access rules would refuse anyway: a document nobody may
|
|
112
|
+
// edit (an ERP mirror, say) gets no Save, and Delete/Duplicate follow their rules
|
|
113
|
+
const docEditable =
|
|
114
|
+
mode === "new" ? canWrite(config, user, collection.slug) : canUpdate(config, user, collection.slug, doc);
|
|
115
|
+
const canSave = Object.keys(collection.fields).some(
|
|
116
|
+
(fieldName) => !isFieldHidden(fieldName) && !isFieldReadOnly(fieldName),
|
|
117
|
+
);
|
|
118
|
+
const canDeleteDoc = canDelete(config, user, collection.slug, doc);
|
|
119
|
+
const canDuplicate = canWrite(config, user, collection.slug);
|
|
120
|
+
|
|
107
121
|
const relationMetaByField = loadRelationMeta(collection, config, user);
|
|
108
122
|
// Seed labels for the ids this document already points at, so relation fields
|
|
109
123
|
// render named selections immediately instead of resolving them client-side.
|
|
@@ -330,20 +344,22 @@ const publishBlocked =
|
|
|
330
344
|
</form>
|
|
331
345
|
) : (
|
|
332
346
|
<>
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
+
{canSave && (
|
|
348
|
+
<button
|
|
349
|
+
class={buttonVariants({ variant: "outline" })}
|
|
350
|
+
type="submit"
|
|
351
|
+
form="document-form"
|
|
352
|
+
name="_intent"
|
|
353
|
+
value="save"
|
|
354
|
+
disabled={mode === "edit"}
|
|
355
|
+
>
|
|
356
|
+
{collection.slug === "users" && mode === "new"
|
|
357
|
+
? "Send invite"
|
|
358
|
+
: collection.drafts
|
|
359
|
+
? "Save draft"
|
|
360
|
+
: "Save"}
|
|
361
|
+
</button>
|
|
362
|
+
)}
|
|
347
363
|
{collection.drafts &&
|
|
348
364
|
(publishBlocked ? (
|
|
349
365
|
<button
|
|
@@ -384,8 +400,8 @@ const publishBlocked =
|
|
|
384
400
|
documentId={documentId}
|
|
385
401
|
showUnpublish={collection.drafts && doc?._status === "published"}
|
|
386
402
|
showDiscardDraft={Boolean(collection.drafts && doc?._status === "published" && doc?._published)}
|
|
387
|
-
showDelete={!isSingleton}
|
|
388
|
-
showDuplicate={!isSingleton && !collection.auth}
|
|
403
|
+
showDelete={!isSingleton && canDeleteDoc}
|
|
404
|
+
showDuplicate={!isSingleton && !collection.auth && canDuplicate}
|
|
389
405
|
showSchedule={!!collection.drafts}
|
|
390
406
|
showCancelSchedule={collection.drafts && doc?._status === "scheduled"}
|
|
391
407
|
currentPublishAt={doc?._publishAt ? String(doc._publishAt) : undefined}
|
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
humanize,
|
|
19
19
|
resolveCollaboration,
|
|
20
20
|
} from "../../core";
|
|
21
|
-
import { canWrite, getVisualStatus } from "../lib/access";
|
|
21
|
+
import { canDelete, canWrite, getVisualStatus } from "../lib/access";
|
|
22
22
|
import { loadRelationOptionList, loadSharedSectionUsageCounts } from "../lib/edit-data";
|
|
23
23
|
|
|
24
24
|
type CollectionLike = {
|
|
@@ -238,7 +238,8 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
|
|
|
238
238
|
client:load
|
|
239
239
|
collectionSlug={collection.slug}
|
|
240
240
|
draftsEnabled={collection.drafts}
|
|
241
|
-
duplicateEnabled={!collection.auth}
|
|
241
|
+
duplicateEnabled={!collection.auth && canWrite(config, user, collection.slug)}
|
|
242
|
+
deleteEnabled={canDelete(config, user, collection.slug)}
|
|
242
243
|
showLocalesColumn={showLocalesColumn}
|
|
243
244
|
defaultLocale={locales.length > 1 ? defaultLocale : undefined}
|
|
244
245
|
labelField={getLabelField(collection)}
|
package/core/api.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { and, asc, desc, eq, inArray, like, lte, ne, or, sql } from "drizzle-orm";
|
|
1
|
+
import { and, asc, desc, eq, inArray, like, lte, ne, or, sql, type SQL } from "drizzle-orm";
|
|
2
2
|
import { setCloudflareImageMode } from "./image";
|
|
3
3
|
import { nanoid } from "nanoid";
|
|
4
4
|
|
|
@@ -22,7 +22,24 @@ import { drainTasks, enqueueTask, pruneTasks, tickSchedules, type EnqueueTaskOpt
|
|
|
22
22
|
import { cloneValue, createRichTextFromPlainText, slugify } from "./values";
|
|
23
23
|
import { dispatchWebhooks } from "./webhooks";
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Operators for a `where` key. Scalar fields: `ne`, `gt`, `gte`, `lt`, `lte`, `in`,
|
|
27
|
+
* `notIn` (`ne: null` = "is set"). Array fields (`hasMany` relations, `array`):
|
|
28
|
+
* `contains` (has this item), `in` (has any of), `notIn` (has none of).
|
|
29
|
+
*/
|
|
30
|
+
export type WhereOperators = {
|
|
31
|
+
ne?: unknown;
|
|
32
|
+
gt?: unknown;
|
|
33
|
+
gte?: unknown;
|
|
34
|
+
lt?: unknown;
|
|
35
|
+
lte?: unknown;
|
|
36
|
+
in?: unknown[];
|
|
37
|
+
notIn?: unknown[];
|
|
38
|
+
contains?: unknown;
|
|
39
|
+
};
|
|
40
|
+
|
|
25
41
|
export type FindOptions = {
|
|
42
|
+
/** A plain value means equality; a `WhereOperators` object ANDs its operators. */
|
|
26
43
|
where?: Record<string, unknown>;
|
|
27
44
|
sort?: {
|
|
28
45
|
field: string;
|
|
@@ -78,6 +95,184 @@ const isJsonField = (field: FieldConfig) =>
|
|
|
78
95
|
field.type === "blocks" ||
|
|
79
96
|
(field.type === "relation" && field.hasMany);
|
|
80
97
|
|
|
98
|
+
const isArrayValuedField = (field: FieldConfig | undefined) =>
|
|
99
|
+
!!field && (field.type === "array" || (field.type === "relation" && !!field.hasMany));
|
|
100
|
+
|
|
101
|
+
const WHERE_OPERATORS = new Set(["ne", "gt", "gte", "lt", "lte", "in", "notIn", "contains"]);
|
|
102
|
+
const SCALAR_OPERATORS = new Set(["ne", "gt", "gte", "lt", "lte", "in", "notIn"]);
|
|
103
|
+
const ARRAY_OPERATORS = new Set(["contains", "in", "notIn"]);
|
|
104
|
+
|
|
105
|
+
const isOperatorObject = (value: unknown): value is Record<string, unknown> =>
|
|
106
|
+
typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
|
|
107
|
+
|
|
108
|
+
// Raw SQL skips drizzle's column mapper, so booleans must be bound as 0/1 and dates as ISO text.
|
|
109
|
+
const bindWhereValue = (value: unknown) => {
|
|
110
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
111
|
+
if (value instanceof Date) return value.toISOString();
|
|
112
|
+
if (typeof value === "object" && value !== null) return JSON.stringify(value);
|
|
113
|
+
return value;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A field's value as published reads see it: the `_published` snapshot holds the live
|
|
118
|
+
* values while a published document has pending draft edits in the main row.
|
|
119
|
+
*/
|
|
120
|
+
const publishedValue = (collection: CollectionConfig, tables: any, key: string): unknown => {
|
|
121
|
+
const field = collection.fields[key];
|
|
122
|
+
if (!tables.main._published || !field) return tables.main[key];
|
|
123
|
+
const path = `$.${key}`;
|
|
124
|
+
const value = sql`(CASE WHEN json_type(${tables.main._published}, ${path}) IS NOT NULL THEN json_extract(${tables.main._published}, ${path}) ELSE ${tables.main[key]} END)`;
|
|
125
|
+
// A CASE has no column affinity; the CAST restores it so "3" still matches a number field.
|
|
126
|
+
if (isJsonField(field)) return value;
|
|
127
|
+
return field.type === "number" || field.type === "boolean"
|
|
128
|
+
? sql`CAST(${value} AS NUMERIC)`
|
|
129
|
+
: sql`CAST(${value} AS TEXT)`;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const operatorCondition = (column: unknown, op: string, value: unknown, arrayValued: boolean): SQL => {
|
|
133
|
+
const list = () =>
|
|
134
|
+
sql.join(
|
|
135
|
+
(value as unknown[]).map((item) => sql`${bindWhereValue(item)}`),
|
|
136
|
+
sql`, `,
|
|
137
|
+
);
|
|
138
|
+
if (arrayValued) {
|
|
139
|
+
const members = (match: SQL) => sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value ${match})`;
|
|
140
|
+
if (op === "contains") return members(sql`= ${bindWhereValue(value)}`);
|
|
141
|
+
if (op === "in") return (value as unknown[]).length === 0 ? sql`0` : members(sql`IN (${list()})`);
|
|
142
|
+
return (value as unknown[]).length === 0 ? sql`1` : sql`NOT ${members(sql`IN (${list()})`)}`;
|
|
143
|
+
}
|
|
144
|
+
switch (op) {
|
|
145
|
+
case "ne":
|
|
146
|
+
return value === null
|
|
147
|
+
? sql`${column} IS NOT NULL`
|
|
148
|
+
: sql`(${column} IS NULL OR ${column} <> ${bindWhereValue(value)})`;
|
|
149
|
+
case "gt":
|
|
150
|
+
return sql`${column} > ${bindWhereValue(value)}`;
|
|
151
|
+
case "gte":
|
|
152
|
+
return sql`${column} >= ${bindWhereValue(value)}`;
|
|
153
|
+
case "lt":
|
|
154
|
+
return sql`${column} < ${bindWhereValue(value)}`;
|
|
155
|
+
case "lte":
|
|
156
|
+
return sql`${column} <= ${bindWhereValue(value)}`;
|
|
157
|
+
case "in":
|
|
158
|
+
return (value as unknown[]).length === 0 ? sql`0` : sql`${column} IN (${list()})`;
|
|
159
|
+
default:
|
|
160
|
+
return (value as unknown[]).length === 0 ? sql`1` : sql`(${column} IS NULL OR ${column} NOT IN (${list()}))`;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const SYSTEM_FILTER_COLUMNS = new Set([
|
|
165
|
+
"_id",
|
|
166
|
+
"_status",
|
|
167
|
+
"_createdAt",
|
|
168
|
+
"_updatedAt",
|
|
169
|
+
"_publishedAt",
|
|
170
|
+
"_publishAt",
|
|
171
|
+
"_unpublishAt",
|
|
172
|
+
"_sourceLocale",
|
|
173
|
+
]);
|
|
174
|
+
|
|
175
|
+
/** Columns an untrusted caller must not range-probe: credentials, internals and fields behind a read rule. */
|
|
176
|
+
const isHiddenFromFilters = (collection: CollectionConfig, key: string) => {
|
|
177
|
+
const field = collection.fields[key];
|
|
178
|
+
if (!field) return !SYSTEM_FILTER_COLUMNS.has(key);
|
|
179
|
+
return (!!collection.auth && key === "password") || !!field.access?.read;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Turn a `where` filter into SQL conditions. A plain value is equality (unchanged
|
|
184
|
+
* behavior); an object is a set of operators ANDed together. Keys that aren't
|
|
185
|
+
* columns are ignored. With `locale`, translatable fields match their effective
|
|
186
|
+
* (translation-overlaid) value; with `published`, fields match the published snapshot.
|
|
187
|
+
*/
|
|
188
|
+
const buildWhereConditions = (
|
|
189
|
+
collection: CollectionConfig,
|
|
190
|
+
tables: any,
|
|
191
|
+
where: Record<string, unknown> | undefined,
|
|
192
|
+
options: { locale?: string; system?: boolean; published?: boolean },
|
|
193
|
+
): { conditions: SQL[]; byCandidates: boolean } => {
|
|
194
|
+
const conditions: SQL[] = [];
|
|
195
|
+
let byCandidates = false;
|
|
196
|
+
if (!where) return { conditions, byCandidates };
|
|
197
|
+
const translatableFields = new Set(getTranslatableFieldNames(collection));
|
|
198
|
+
|
|
199
|
+
for (const [key, value] of Object.entries(where)) {
|
|
200
|
+
if (!(key in tables.main)) continue;
|
|
201
|
+
const field = collection.fields[key];
|
|
202
|
+
const arrayValued = isArrayValuedField(field);
|
|
203
|
+
|
|
204
|
+
let match: (column: unknown) => SQL;
|
|
205
|
+
if (isOperatorObject(value)) {
|
|
206
|
+
const ops = Object.entries(value).filter(([, operand]) => operand !== undefined);
|
|
207
|
+
// Skipping it would widen the filter — and deleteMany would clear the collection.
|
|
208
|
+
if (ops.length === 0) throw new Error(`Empty where operator object on ${collection.slug}.${key}.`);
|
|
209
|
+
if (!options.system && isHiddenFromFilters(collection, key)) {
|
|
210
|
+
throw new Error(`Cannot filter ${collection.slug}.${key} with operators.`);
|
|
211
|
+
}
|
|
212
|
+
if (field && !arrayValued && isJsonField(field)) {
|
|
213
|
+
throw new Error(`Field ${collection.slug}.${key} (${field.type}) doesn't support where operators.`);
|
|
214
|
+
}
|
|
215
|
+
const allowed = arrayValued ? ARRAY_OPERATORS : SCALAR_OPERATORS;
|
|
216
|
+
for (const [op] of ops) {
|
|
217
|
+
if (!WHERE_OPERATORS.has(op)) throw new Error(`Unknown where operator "${op}" on ${collection.slug}.${key}.`);
|
|
218
|
+
if (!allowed.has(op)) {
|
|
219
|
+
throw new Error(
|
|
220
|
+
`where operator "${op}" isn't supported on ${arrayValued ? "array" : "scalar"} field ${collection.slug}.${key}.`,
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
const isList = op === "in" || op === "notIn";
|
|
224
|
+
if (isList !== Array.isArray(value[op])) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`where operator "${op}" on ${collection.slug}.${key} expects ${isList ? "an array" : "a single value"}.`,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
if (isList && (value[op] as unknown[]).some((item) => item === null || item === undefined)) {
|
|
230
|
+
throw new Error(`where operator "${op}" on ${collection.slug}.${key} can't list null; use ne: null.`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
match = (column) => {
|
|
234
|
+
const parts = ops.map(([op, operand]) => operatorCondition(column, op, operand, arrayValued));
|
|
235
|
+
return parts.length === 1 ? parts[0] : and(...parts)!;
|
|
236
|
+
};
|
|
237
|
+
} else {
|
|
238
|
+
match = (column) => sql`${column} = ${bindWhereValue(value)}`;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const mainValue = options.published ? publishedValue(collection, tables, key) : tables.main[key];
|
|
242
|
+
|
|
243
|
+
if (options.locale && tables.translations && translatableFields.has(key)) {
|
|
244
|
+
// Translatable fields live in the translations table for non-default locales:
|
|
245
|
+
// match the translation when one exists for this locale, the main-table value
|
|
246
|
+
// otherwise. Without this, e.g. findOne({ slug, locale: "en" }) can never match
|
|
247
|
+
// a translated slug.
|
|
248
|
+
const tr = tables.translations;
|
|
249
|
+
conditions.push(
|
|
250
|
+
sql`(EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${match(tr[key])}) OR (${match(mainValue)} AND NOT EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} IS NOT NULL)))`,
|
|
251
|
+
);
|
|
252
|
+
} else if (mainValue !== tables.main[key]) {
|
|
253
|
+
// Candidates come from the column's own index plus the few documents with
|
|
254
|
+
// pending drafts (pending index; `> ''` keeps it a range seek); the
|
|
255
|
+
// snapshot-aware match then decides.
|
|
256
|
+
const main = tables.main;
|
|
257
|
+
byCandidates = true;
|
|
258
|
+
conditions.push(
|
|
259
|
+
sql`${main._id} IN (SELECT ${main._id} FROM ${main} WHERE ${match(main[key])} UNION ALL SELECT ${main._id} FROM ${main} WHERE ${main._published} > '')`,
|
|
260
|
+
match(mainValue),
|
|
261
|
+
);
|
|
262
|
+
} else if (isOperatorObject(value)) {
|
|
263
|
+
conditions.push(match(tables.main[key]));
|
|
264
|
+
} else {
|
|
265
|
+
conditions.push(eq(tables.main[key], value));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return { conditions, byCandidates };
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// With snapshot candidates in play, the unary + keeps SQLite (no ANALYZE stats) from
|
|
272
|
+
// picking the low-selectivity _status index over the candidate _id lookup.
|
|
273
|
+
const statusCondition = (tables: any, status: string, byCandidates: boolean) =>
|
|
274
|
+
byCandidates ? sql`+${tables.main._status} = ${status}` : eq(tables.main._status, status);
|
|
275
|
+
|
|
81
276
|
const ensureCollection = (config: CMSConfig, slug: string) => {
|
|
82
277
|
const collection = getCollectionMap(config)[slug];
|
|
83
278
|
if (!collection) {
|
|
@@ -365,12 +560,21 @@ const stripUnreadableFields = async (
|
|
|
365
560
|
) => {
|
|
366
561
|
if (context._system) return doc;
|
|
367
562
|
const accessCtx = { user: context.user ?? null, doc, operation: "read", collection: collection.slug };
|
|
368
|
-
|
|
563
|
+
const denied: string[] = [];
|
|
369
564
|
for (const [fieldName, field] of Object.entries(collection.fields)) {
|
|
370
|
-
if (
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
565
|
+
if (field.access?.read && !(await field.access.read(accessCtx))) denied.push(fieldName);
|
|
566
|
+
}
|
|
567
|
+
if (denied.length === 0) return doc;
|
|
568
|
+
const result = { ...doc };
|
|
569
|
+
for (const fieldName of denied) delete result[fieldName];
|
|
570
|
+
// The pending-draft snapshot carries the same fields; strip them there too.
|
|
571
|
+
if (typeof result._published === "string") {
|
|
572
|
+
try {
|
|
573
|
+
const snapshot = JSON.parse(result._published);
|
|
574
|
+
for (const fieldName of denied) delete snapshot[fieldName];
|
|
575
|
+
result._published = JSON.stringify(snapshot);
|
|
576
|
+
} catch {
|
|
577
|
+
delete result._published;
|
|
374
578
|
}
|
|
375
579
|
}
|
|
376
580
|
return result;
|
|
@@ -601,31 +805,17 @@ export const createCms = (config: CMSConfig) => {
|
|
|
601
805
|
const tables = await getTableRefs(slug);
|
|
602
806
|
const status = options.status ?? (collection.drafts ? "published" : "any");
|
|
603
807
|
const filterAfterReadAccess = hasReadRule(collection) && !context._system;
|
|
808
|
+
const published = status === "published" && !!collection.drafts;
|
|
809
|
+
const readValue = (key: string) => (published ? publishedValue(collection, tables, key) : tables.main[key]);
|
|
604
810
|
|
|
605
|
-
const
|
|
811
|
+
const where = buildWhereConditions(collection, tables, options.where, {
|
|
812
|
+
locale: options.locale,
|
|
813
|
+
system: context._system,
|
|
814
|
+
published,
|
|
815
|
+
});
|
|
816
|
+
const conditions: any[] = [...where.conditions];
|
|
606
817
|
if (status !== "any" && collection.drafts) {
|
|
607
|
-
conditions.
|
|
608
|
-
}
|
|
609
|
-
if (options.where) {
|
|
610
|
-
const translatableFields = new Set(getTranslatableFieldNames(collection));
|
|
611
|
-
for (const [key, value] of Object.entries(options.where)) {
|
|
612
|
-
if (!(key in tables.main)) continue;
|
|
613
|
-
if (options.locale && tables.translations && translatableFields.has(key)) {
|
|
614
|
-
// Translatable fields live in the translations table for non-default
|
|
615
|
-
// locales: match the effective (overlaid) value — the translation when
|
|
616
|
-
// one exists for this locale, the main-table value otherwise. Without
|
|
617
|
-
// this, e.g. findOne({ slug, locale: "en" }) can never match a
|
|
618
|
-
// translated slug.
|
|
619
|
-
const tr = tables.translations;
|
|
620
|
-
// Raw SQL skips drizzle's column mapper, so booleans must be bound as 0/1.
|
|
621
|
-
const bound = typeof value === "boolean" ? (value ? 1 : 0) : value;
|
|
622
|
-
conditions.push(
|
|
623
|
-
sql`(EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} = ${bound}) OR (${tables.main[key]} = ${bound} AND NOT EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} IS NOT NULL)))`,
|
|
624
|
-
);
|
|
625
|
-
} else {
|
|
626
|
-
conditions.push(eq(tables.main[key], value));
|
|
627
|
-
}
|
|
628
|
-
}
|
|
818
|
+
conditions.unshift(statusCondition(tables, status, where.byCandidates));
|
|
629
819
|
}
|
|
630
820
|
const availability = availabilityCondition(tables, options);
|
|
631
821
|
if (availability) conditions.push(availability);
|
|
@@ -636,7 +826,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
636
826
|
const searchConditions = Object.entries(collection.fields)
|
|
637
827
|
.filter(([, field]) => searchableTypes.has(field.type))
|
|
638
828
|
.filter(([name]) => name in tables.main)
|
|
639
|
-
.map(([name]) => like(sql`lower(${
|
|
829
|
+
.map(([name]) => like(sql`lower(${readValue(name)})`, searchTerm));
|
|
640
830
|
if (searchConditions.length > 0) {
|
|
641
831
|
conditions.push(or(...searchConditions)!);
|
|
642
832
|
}
|
|
@@ -648,8 +838,8 @@ export const createCms = (config: CMSConfig) => {
|
|
|
648
838
|
}
|
|
649
839
|
|
|
650
840
|
if (options.sort) {
|
|
651
|
-
|
|
652
|
-
|
|
841
|
+
if (tables.main[options.sort.field]) {
|
|
842
|
+
const col = readValue(options.sort.field) as any;
|
|
653
843
|
query = query.orderBy(options.sort.direction === "desc" ? desc(col) : asc(col)) as any;
|
|
654
844
|
}
|
|
655
845
|
}
|
|
@@ -1045,7 +1235,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1045
1235
|
},
|
|
1046
1236
|
|
|
1047
1237
|
/**
|
|
1048
|
-
* Delete every document matching `filter` (
|
|
1238
|
+
* Delete every document matching `filter` (same shape as `find`'s `where`;
|
|
1049
1239
|
* empty filter clears the whole collection), along with their translation,
|
|
1050
1240
|
* version and search-index rows. Returns the number of documents removed.
|
|
1051
1241
|
*
|
|
@@ -1062,10 +1252,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1062
1252
|
const db = await getDb();
|
|
1063
1253
|
const tables = await getTableRefs(slug);
|
|
1064
1254
|
|
|
1065
|
-
const conditions
|
|
1066
|
-
for (const [key, value] of Object.entries(filter)) {
|
|
1067
|
-
if (key in tables.main) conditions.push(eq(tables.main[key], value));
|
|
1068
|
-
}
|
|
1255
|
+
const { conditions } = buildWhereConditions(collection, tables, filter, { system: context._system });
|
|
1069
1256
|
let idQuery = db.select({ _id: tables.main._id }).from(tables.main);
|
|
1070
1257
|
if (conditions.length > 0) {
|
|
1071
1258
|
idQuery = idQuery.where(conditions.length === 1 ? conditions[0] : and(...conditions)) as any;
|
|
@@ -1154,11 +1341,15 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1154
1341
|
}
|
|
1155
1342
|
|
|
1156
1343
|
const timestamp = now();
|
|
1344
|
+
// A pending end date survives publishing, whether the publish comes from
|
|
1345
|
+
// the schedule cron or an editor publishing new edits
|
|
1346
|
+
const unpublishAt =
|
|
1347
|
+
typeof existing._unpublishAt === "string" && existing._unpublishAt > timestamp ? existing._unpublishAt : null;
|
|
1157
1348
|
const updateValues: Record<string, unknown> = {
|
|
1158
1349
|
_status: "published",
|
|
1159
1350
|
_publishedAt: timestamp,
|
|
1160
1351
|
_publishAt: null,
|
|
1161
|
-
_unpublishAt:
|
|
1352
|
+
_unpublishAt: unpublishAt,
|
|
1162
1353
|
_published: null,
|
|
1163
1354
|
};
|
|
1164
1355
|
if (collection.timestamps !== false) updateValues._updatedAt = timestamp;
|
|
@@ -1275,17 +1466,17 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1275
1466
|
const db = await getDb();
|
|
1276
1467
|
const tables = await getTableRefs(slug);
|
|
1277
1468
|
const status = filter.status ?? (collection.drafts ? "published" : "any");
|
|
1469
|
+
const published = status === "published" && !!collection.drafts;
|
|
1470
|
+
const readValue = (key: string) => (published ? publishedValue(collection, tables, key) : tables.main[key]);
|
|
1278
1471
|
|
|
1279
|
-
const
|
|
1472
|
+
const where = buildWhereConditions(collection, tables, filter.where, {
|
|
1473
|
+
locale: filter.locale,
|
|
1474
|
+
system: context._system,
|
|
1475
|
+
published,
|
|
1476
|
+
});
|
|
1477
|
+
const conditions: any[] = [...where.conditions];
|
|
1280
1478
|
if (status !== "any" && collection.drafts) {
|
|
1281
|
-
conditions.
|
|
1282
|
-
}
|
|
1283
|
-
if (filter.where) {
|
|
1284
|
-
for (const [key, value] of Object.entries(filter.where)) {
|
|
1285
|
-
if (key in tables.main) {
|
|
1286
|
-
conditions.push(eq(tables.main[key], value));
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1479
|
+
conditions.unshift(statusCondition(tables, status, where.byCandidates));
|
|
1289
1480
|
}
|
|
1290
1481
|
const availability = availabilityCondition(tables, filter);
|
|
1291
1482
|
if (availability) conditions.push(availability);
|
|
@@ -1295,7 +1486,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1295
1486
|
const searchConditions = Object.entries(collection.fields)
|
|
1296
1487
|
.filter(([, field]) => searchableTypes.has(field.type))
|
|
1297
1488
|
.filter(([name]) => name in tables.main)
|
|
1298
|
-
.map(([name]) => like(sql`lower(${
|
|
1489
|
+
.map(([name]) => like(sql`lower(${readValue(name)})`, searchTerm));
|
|
1299
1490
|
if (searchConditions.length > 0) {
|
|
1300
1491
|
conditions.push(or(...searchConditions)!);
|
|
1301
1492
|
}
|
package/core/generator.ts
CHANGED
|
@@ -146,6 +146,10 @@ const generateMainTable = (
|
|
|
146
146
|
if (collection.drafts) {
|
|
147
147
|
indexes.push(` publishIdx: index("${idxPrefix}_publish_idx").on(table._status, table._publishAt),`);
|
|
148
148
|
indexes.push(` unpublishIdx: index("${idxPrefix}_unpublish_idx").on(table._status, table._unpublishAt),`);
|
|
149
|
+
// Published reads filter on the _published snapshot for documents with pending
|
|
150
|
+
// draft edits; this keeps that lookup to those few rows instead of a full scan.
|
|
151
|
+
// Plain, not partial: drizzle-kit can't round-trip a partial index.
|
|
152
|
+
indexes.push(` pendingIdx: index("${idxPrefix}_pending_idx").on(table._published),`);
|
|
149
153
|
}
|
|
150
154
|
// The admin lists, the Recent view and most editorial listings sort by
|
|
151
155
|
// _updatedAt; without an index each of them is a full scan plus a temp
|
|
@@ -197,12 +201,10 @@ const generateVersionsTable = (collection: CollectionConfig): string | null => {
|
|
|
197
201
|
});`;
|
|
198
202
|
};
|
|
199
203
|
|
|
204
|
+
const SCHEMA_IMPORT_PLACEHOLDER = "/* kide:schema-imports */";
|
|
205
|
+
|
|
200
206
|
const generateSchemaFile = (config: CMSConfig): string => {
|
|
201
|
-
const parts: string[] = [
|
|
202
|
-
`// auto-generated — do not edit`,
|
|
203
|
-
`import { sqliteTable, text, integer, real, unique, index, primaryKey } from "drizzle-orm/sqlite-core";`,
|
|
204
|
-
``,
|
|
205
|
-
];
|
|
207
|
+
const parts: string[] = [`// auto-generated — do not edit`, SCHEMA_IMPORT_PLACEHOLDER, ``];
|
|
206
208
|
|
|
207
209
|
const authSpecs = getAuthSpecs(config);
|
|
208
210
|
|
|
@@ -386,7 +388,12 @@ const generateSchemaFile = (config: CMSConfig): string => {
|
|
|
386
388
|
}
|
|
387
389
|
parts.push(`export const cmsTables = {\n${tableExports.join("\n")}\n};`);
|
|
388
390
|
|
|
389
|
-
|
|
391
|
+
// Import only the builders the schema calls, so generated code lints clean
|
|
392
|
+
const body = parts.join("\n");
|
|
393
|
+
const builders = ["sqliteTable", "text", "integer", "real", "unique", "index", "primaryKey"].filter((name) =>
|
|
394
|
+
new RegExp(`(?<![.\\w])${name}\\(`).test(body),
|
|
395
|
+
);
|
|
396
|
+
return body.replace(SCHEMA_IMPORT_PLACEHOLDER, `import { ${builders.join(", ")} } from "drizzle-orm/sqlite-core";`);
|
|
390
397
|
};
|
|
391
398
|
|
|
392
399
|
const zodTypeForField = (field: FieldConfig): string => {
|
|
@@ -494,10 +501,12 @@ const typeForField = (field: FieldConfig): string => {
|
|
|
494
501
|
return "unknown";
|
|
495
502
|
};
|
|
496
503
|
|
|
504
|
+
const TYPES_IMPORT_PLACEHOLDER = "/* kide:types-imports */";
|
|
505
|
+
|
|
497
506
|
const generateTypesFile = (config: CMSConfig, coreImportPath: string): string => {
|
|
498
507
|
const parts: string[] = [
|
|
499
508
|
`// auto-generated — do not edit`,
|
|
500
|
-
|
|
509
|
+
TYPES_IMPORT_PLACEHOLDER,
|
|
501
510
|
``,
|
|
502
511
|
`export type CMSCollectionSlug = ${config.collections.map((collection) => JSON.stringify(collection.slug)).join(" | ")};`,
|
|
503
512
|
``,
|
|
@@ -547,7 +556,11 @@ const generateTypesFile = (config: CMSConfig, coreImportPath: string): string =>
|
|
|
547
556
|
snapshot: Record<string, unknown>;
|
|
548
557
|
};`);
|
|
549
558
|
|
|
550
|
-
|
|
559
|
+
const body = parts.join("\n");
|
|
560
|
+
const used = ["RichTextDocument", "ContentDocument"].filter((name) => new RegExp(`\\b${name}\\b`).test(body));
|
|
561
|
+
return used.length > 0
|
|
562
|
+
? body.replace(TYPES_IMPORT_PLACEHOLDER, `import type { ${used.join(", ")} } from "${coreImportPath}";`)
|
|
563
|
+
: body.replace(`${TYPES_IMPORT_PLACEHOLDER}\n`, "");
|
|
551
564
|
};
|
|
552
565
|
|
|
553
566
|
const generateApiFile = (
|
|
@@ -566,7 +579,7 @@ const generateApiFile = (
|
|
|
566
579
|
const apiTypes = config.collections
|
|
567
580
|
.map((collection) => {
|
|
568
581
|
const baseName = pascalCase(collection.slug);
|
|
569
|
-
const ctx = `context?:
|
|
582
|
+
const ctx = `context?: CmsContext`;
|
|
570
583
|
const apiKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(collection.slug) ? collection.slug : `"${collection.slug}"`;
|
|
571
584
|
return ` ${apiKey}: {
|
|
572
585
|
find(options?: import("${coreImportPath}").FindOptions, ${ctx}): Promise<${baseName}Document[]>;
|
|
@@ -577,6 +590,7 @@ const generateApiFile = (
|
|
|
577
590
|
upsert(data: ${baseName}Input & { _id?: string }, ${ctx}): Promise<${baseName}Document>;
|
|
578
591
|
update(id: string, data: Partial<${baseName}Input>, ${ctx}): Promise<${baseName}Document>;
|
|
579
592
|
delete(id: string, ${ctx}): Promise<void>;
|
|
593
|
+
deleteMany(where?: import("${coreImportPath}").FindOptions["where"], ${ctx}): Promise<number>;
|
|
580
594
|
count(filter?: Omit<import("${coreImportPath}").FindOptions, "limit" | "offset" | "sort">, ${ctx}): Promise<number>;
|
|
581
595
|
versions(id: string, ${ctx}): Promise<import("./types").StoredVersion[]>;
|
|
582
596
|
restore(id: string, versionNumber: number, ${ctx}): Promise<${baseName}Document>;
|
|
@@ -596,10 +610,20 @@ import type {
|
|
|
596
610
|
${imports.map((entry) => `${entry},`).join("\n ")}
|
|
597
611
|
} from "./types";
|
|
598
612
|
|
|
613
|
+
export type CmsContext = {
|
|
614
|
+
user?: { id: string; role?: string; email?: string; [key: string]: unknown } | null;
|
|
615
|
+
cache?: { invalidate: (opts: { tags: string[] }) => void | Promise<void> };
|
|
616
|
+
/** Bypass access rules (server-side / system operations). */
|
|
617
|
+
_system?: boolean;
|
|
618
|
+
/** Skip search indexing for bulk writes; reindex once afterwards. */
|
|
619
|
+
_skipSearch?: boolean;
|
|
620
|
+
};
|
|
621
|
+
|
|
599
622
|
export const cms = createCms(config) as {
|
|
600
623
|
${apiTypes}
|
|
601
624
|
meta: ReturnType<typeof createCms>["meta"];
|
|
602
625
|
scheduled: ReturnType<typeof createCms>["scheduled"];
|
|
626
|
+
tasks: ReturnType<typeof createCms>["tasks"];
|
|
603
627
|
};
|
|
604
628
|
`;
|
|
605
629
|
};
|
package/core/index.ts
CHANGED
|
@@ -112,7 +112,7 @@ export type {
|
|
|
112
112
|
} from "./define";
|
|
113
113
|
|
|
114
114
|
export { createCms, FieldError } from "./api";
|
|
115
|
-
export type { FindOptions } from "./api";
|
|
115
|
+
export type { FindOptions, WhereOperators } from "./api";
|
|
116
116
|
|
|
117
117
|
export { enqueueTask, drainTasks, tickSchedules, pruneTasks } from "./tasks";
|
|
118
118
|
export { peekRateLimit, hitRateLimit, recordRateLimit, clearRateLimit, pruneRateLimits } from "./rate-limit";
|
package/internals/context.ts
CHANGED
|
@@ -32,10 +32,15 @@ import {
|
|
|
32
32
|
} from "../core";
|
|
33
33
|
import { loadProjectConfig, loadProjectRuntime } from "./project";
|
|
34
34
|
|
|
35
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Pass the generated API type to get typed collections in scripts:
|
|
37
|
+
*
|
|
38
|
+
* const { cms } = await createCmsContext<typeof import("@/cms/.generated/api").cms>();
|
|
39
|
+
*/
|
|
40
|
+
export const createCmsContext = async <TCms = ReturnType<typeof createCms>>() => {
|
|
36
41
|
await loadProjectRuntime(); // side effect: configureCmsRuntime()
|
|
37
42
|
const config = await loadProjectConfig();
|
|
38
|
-
const cms = createCms(config);
|
|
43
|
+
const cms = createCms(config) as TCms;
|
|
39
44
|
const db = await getDb();
|
|
40
45
|
return {
|
|
41
46
|
/** Typed local API: `cms.posts.create(...)`, `cms.pages.deleteMany(...)`, … */
|
|
@@ -51,7 +56,7 @@ export const createCmsContext = async () => {
|
|
|
51
56
|
load: (
|
|
52
57
|
items: ImportItem[],
|
|
53
58
|
options?: { dryRun?: boolean; throwOnFailed?: boolean; context?: Record<string, unknown> },
|
|
54
|
-
) => importDocuments(cms as Record<string, any>, config, items, options),
|
|
59
|
+
) => importDocuments(cms as unknown as Record<string, any>, config, items, options),
|
|
55
60
|
/** The machine-readable content model (same as `.kide/model.json`). */
|
|
56
61
|
model: () => describeModel(config),
|
|
57
62
|
/** Rebuild the search index for all searchable collections (uses this config's locales). */
|
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), 'missing' only those that don't; the default 'fallback' lists every document.",
|
|
202
|
+
"List documents in a collection with optional filters, search, sort, locale, status, limit, and offset. where: a plain value is equality; an object applies operators — scalar fields: ne, gt, gte, lt, lte, in, notIn (e.g. { startDate: { gte: '2026-01-01' } }); hasMany relation / array fields: contains, in (any of), notIn. 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(),
|
|
@@ -219,7 +219,8 @@ server.registerTool(
|
|
|
219
219
|
"kide_count_documents",
|
|
220
220
|
{
|
|
221
221
|
title: "Count documents",
|
|
222
|
-
description:
|
|
222
|
+
description:
|
|
223
|
+
"Count documents in a collection with optional filters, search, locale, and status. where accepts the same operators as kide_list_documents.",
|
|
223
224
|
inputSchema: {
|
|
224
225
|
collection: z.string().min(1),
|
|
225
226
|
where: jsonObjectSchema.optional(),
|