@kidecms/core 0.1.10 → 0.13.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/LICENSE +21 -0
- package/admin/components/AssetsGrid.tsx +366 -173
- package/admin/components/BlockEditor.tsx +260 -679
- package/admin/components/CheckboxField.tsx +2 -2
- package/admin/components/CollaborationReviewBar.tsx +384 -0
- package/admin/components/ColorField.tsx +87 -0
- package/admin/components/CommandPalette.tsx +169 -0
- package/admin/components/ContentEditor.tsx +687 -0
- package/admin/components/DocumentActions.tsx +4 -2
- package/admin/components/DocumentsDataTable.tsx +91 -10
- package/admin/components/FieldControl.astro +151 -26
- package/admin/components/FocalPointSelector.tsx +27 -1
- package/admin/components/InternalLinkPicker.tsx +4 -3
- package/admin/components/LinkField.tsx +126 -0
- package/admin/components/RelationField.tsx +105 -26
- package/admin/components/RepeaterInput.tsx +46 -0
- package/admin/components/RichTextEditor.tsx +44 -9
- package/admin/components/SharedSectionBlockField.tsx +93 -0
- package/admin/components/SidebarUserMenu.tsx +1 -1
- package/admin/components/Toast.astro +1 -1
- package/admin/components/TreeItemsEditor.tsx +20 -19
- package/admin/components/TreeSelect.tsx +2 -2
- package/admin/components/YoutubeField.tsx +48 -0
- package/admin/components/block-fields.tsx +777 -0
- package/admin/components/content-block-spec.ts +114 -0
- package/admin/components/slash-command.tsx +242 -0
- package/admin/components/tree-utils.ts +14 -2
- package/admin/components/ui/badge.tsx +2 -3
- package/admin/components/ui/button.tsx +5 -4
- package/admin/components/ui/checkbox.tsx +1 -1
- package/admin/components/ui/input.tsx +1 -1
- package/admin/components/ui/select.tsx +1 -1
- package/admin/components/ui/table.tsx +1 -1
- package/admin/components/ui/textarea.tsx +1 -1
- package/admin/layouts/AdminLayout.astro +323 -123
- package/admin/lib/access.ts +54 -0
- package/admin/lib/collaboration.ts +178 -0
- package/admin/lib/edit-data.ts +448 -0
- package/admin/views/AccessDeniedView.astro +8 -0
- package/admin/views/EditView.astro +706 -0
- package/admin/views/ListView.astro +202 -0
- package/admin/views/RecentView.astro +76 -0
- package/admin/views/SinglesView.astro +65 -0
- package/admin/views/edit/EditScripts.astro +145 -0
- package/admin/views/edit/ReverseReferencesList.astro +68 -0
- package/core/admin.ts +193 -0
- package/core/ai.ts +87 -0
- package/core/api.ts +1392 -0
- package/core/assets.ts +336 -0
- package/core/audit.ts +84 -0
- package/core/auth-config.ts +44 -0
- package/core/auth.ts +303 -0
- package/core/collaboration.ts +276 -0
- package/core/content.ts +27 -0
- package/core/create-admin.ts +28 -0
- package/core/define.ts +625 -0
- package/core/field-model.ts +172 -0
- package/core/generator.ts +519 -0
- package/core/http.ts +42 -0
- package/core/image.ts +219 -0
- package/core/index.ts +211 -0
- package/core/locks.ts +52 -0
- package/core/log.ts +37 -0
- package/core/migrate.ts +278 -0
- package/core/rate-limit.ts +110 -0
- package/core/request-scope.ts +33 -0
- package/core/richtext.ts +1 -0
- package/core/runtime.ts +63 -0
- package/core/schema.ts +32 -0
- package/core/search.ts +489 -0
- package/core/seed.ts +101 -0
- package/core/shared-sections.ts +96 -0
- package/core/tasks.ts +176 -0
- package/core/values.ts +433 -0
- package/core/webhooks.ts +85 -0
- package/core/youtube.ts +39 -0
- package/internals/cli.mjs +34 -0
- package/internals/context.ts +67 -0
- package/internals/create-admin.ts +40 -0
- package/internals/describe.ts +25 -0
- package/internals/eject.ts +144 -0
- package/internals/generator.ts +11 -0
- package/internals/integration.ts +481 -0
- package/internals/mcp.ts +397 -0
- package/internals/project.ts +26 -0
- package/internals/push.ts +160 -0
- package/internals/reindex.ts +11 -0
- package/internals/restore.ts +257 -0
- package/internals/seed.data.ts +7 -0
- package/internals/seed.ts +11 -0
- package/internals/upgrade.ts +776 -0
- package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
- package/middleware/auth.ts +130 -17
- package/middleware/push.ts +121 -0
- package/package.json +55 -67
- package/platform/cloudflare/cf-env.ts +60 -0
- package/platform/cloudflare/database.ts +28 -0
- package/platform/cloudflare/globals.d.ts +5 -0
- package/platform/cloudflare/storage.ts +33 -0
- package/platform/cloudflare/uploads-route.ts +37 -0
- package/platform/node/database.ts +39 -0
- package/platform/node/storage.ts +52 -0
- package/routes/admin/[...path].astro +71 -0
- package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
- package/routes/admin/assets/index.astro +90 -0
- package/routes/admin/forgot-password.astro +60 -0
- package/routes/{pages/admin → admin}/invite.astro +7 -6
- package/routes/admin/login.astro +103 -0
- package/routes/admin/reset-password.astro +73 -0
- package/routes/{pages/admin → admin}/setup.astro +32 -8
- package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
- package/routes/api/admin/search.ts +89 -0
- package/routes/api/{cms/assets → assets}/[id].ts +24 -14
- package/routes/api/{cms/assets → assets}/index.ts +4 -2
- package/routes/api/assets/upload.ts +147 -0
- package/routes/api/auth/forgot-password.ts +77 -0
- package/routes/api/{cms/auth → auth}/invite.ts +41 -9
- package/routes/api/auth/login.ts +167 -0
- package/routes/api/{cms/auth → auth}/logout.ts +11 -2
- package/routes/api/auth/reset-password.ts +85 -0
- package/routes/api/auth/setup.ts +110 -0
- package/routes/api/auth/sso/[provider]/start.ts +34 -0
- package/routes/api/collaboration/index.ts +106 -0
- package/routes/api/cron/_authorize.ts +25 -0
- package/routes/api/{cms/cron → cron}/publish.ts +3 -9
- package/routes/api/cron/tasks.ts +33 -0
- package/routes/api/forms/submit/[slug].ts +143 -0
- package/routes/api/img/[...path].ts +65 -0
- package/routes/api/{cms/preview → preview}/render.ts +8 -3
- package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
- package/routes/api/webhooks/[provider].ts +54 -0
- package/README.md +0 -28
- package/dist/admin.d.ts +0 -33
- package/dist/admin.js +0 -92
- package/dist/ai.d.ts +0 -15
- package/dist/ai.js +0 -70
- package/dist/api.d.ts +0 -14
- package/dist/api.js +0 -833
- package/dist/assets.d.ts +0 -51
- package/dist/assets.js +0 -163
- package/dist/auth.d.ts +0 -30
- package/dist/auth.js +0 -132
- package/dist/content.d.ts +0 -3
- package/dist/content.js +0 -29
- package/dist/create-admin.d.ts +0 -5
- package/dist/create-admin.js +0 -23
- package/dist/define.d.ts +0 -254
- package/dist/define.js +0 -36
- package/dist/generator.d.ts +0 -9
- package/dist/generator.js +0 -370
- package/dist/image.d.ts +0 -9
- package/dist/image.js +0 -69
- package/dist/index.d.ts +0 -28
- package/dist/index.js +0 -16
- package/dist/integration.d.ts +0 -14
- package/dist/integration.js +0 -327
- package/dist/locks.d.ts +0 -7
- package/dist/locks.js +0 -37
- package/dist/richtext.d.ts +0 -1
- package/dist/richtext.js +0 -1
- package/dist/runtime.d.ts +0 -24
- package/dist/runtime.js +0 -26
- package/dist/schema.d.ts +0 -17
- package/dist/schema.js +0 -13
- package/dist/seed.d.ts +0 -2
- package/dist/seed.js +0 -84
- package/dist/values.d.ts +0 -8
- package/dist/values.js +0 -102
- package/dist/webhooks.d.ts +0 -2
- package/dist/webhooks.js +0 -73
- package/routes/api/cms/assets/upload.ts +0 -112
- package/routes/api/cms/auth/login.ts +0 -124
- package/routes/api/cms/auth/setup.ts +0 -77
- package/routes/api/cms/img/[...path].ts +0 -24
- package/routes/pages/admin/[...path].astro +0 -1107
- package/routes/pages/admin/assets/index.astro +0 -63
- package/routes/pages/admin/login.astro +0 -57
- /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
- /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
- /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
- /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
- /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
package/core/http.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export class PayloadTooLargeError extends Error {}
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Parses a request body as FormData while enforcing a hard byte cap on the stream itself —
|
|
5
|
+
* unlike checking `Content-Length` (optional, and absent on chunked-encoded requests) or
|
|
6
|
+
* `file.size` after `request.formData()` already buffered the whole body, this aborts mid-stream
|
|
7
|
+
* before more than `maxBytes` have been read. Rejects with `PayloadTooLargeError` when exceeded.
|
|
8
|
+
*/
|
|
9
|
+
export const readLimitedFormData = async (request: Request, maxBytes: number): Promise<FormData> => {
|
|
10
|
+
if (!request.body) return new FormData();
|
|
11
|
+
|
|
12
|
+
let total = 0;
|
|
13
|
+
const reader = request.body.getReader();
|
|
14
|
+
const limited = new ReadableStream<Uint8Array>({
|
|
15
|
+
async pull(controller) {
|
|
16
|
+
const { done, value } = await reader.read();
|
|
17
|
+
if (done) {
|
|
18
|
+
controller.close();
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
total += value.byteLength;
|
|
22
|
+
if (total > maxBytes) {
|
|
23
|
+
controller.error(new PayloadTooLargeError(`Body exceeds ${maxBytes} bytes`));
|
|
24
|
+
await reader.cancel().catch(() => {});
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
controller.enqueue(value);
|
|
28
|
+
},
|
|
29
|
+
cancel(reason) {
|
|
30
|
+
return reader.cancel(reason);
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const limitedRequest = new Request(request.url, {
|
|
35
|
+
method: request.method,
|
|
36
|
+
headers: request.headers,
|
|
37
|
+
body: limited,
|
|
38
|
+
// @ts-expect-error -- required by the Fetch spec for a streaming request body (Node + Workers).
|
|
39
|
+
duplex: "half",
|
|
40
|
+
});
|
|
41
|
+
return limitedRequest.formData();
|
|
42
|
+
};
|
package/core/image.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import type { ImagePreset } from "./define";
|
|
2
|
+
|
|
3
|
+
const ALLOWED_WIDTHS = [320, 480, 640, 768, 960, 1024, 1280, 1536, 1920];
|
|
4
|
+
const ALLOWED_FORMATS = ["webp", "avif", "jpeg", "png"] as const;
|
|
5
|
+
|
|
6
|
+
type Format = (typeof ALLOWED_FORMATS)[number];
|
|
7
|
+
|
|
8
|
+
/** Built-in renditions. Config presets in cms.config.ts are merged over these. */
|
|
9
|
+
export const DEFAULT_PRESETS: Record<string, ImagePreset> = {
|
|
10
|
+
hero: { aspect: "21/9", widths: [768, 1024, 1280, 1920], formats: ["avif", "webp"], sizes: "100vw" },
|
|
11
|
+
heroMobile: { aspect: "4/5", widths: [480, 768], formats: ["avif", "webp"], sizes: "100vw" },
|
|
12
|
+
banner: { aspect: "16/9", widths: [640, 960, 1280, 1920], formats: ["avif", "webp"], sizes: "100vw" },
|
|
13
|
+
card: {
|
|
14
|
+
aspect: "16/9",
|
|
15
|
+
widths: [320, 480, 640],
|
|
16
|
+
formats: ["avif", "webp"],
|
|
17
|
+
sizes: "(max-width: 768px) 100vw, 33vw",
|
|
18
|
+
},
|
|
19
|
+
square: {
|
|
20
|
+
aspect: "1/1",
|
|
21
|
+
widths: [320, 480, 640],
|
|
22
|
+
formats: ["avif", "webp"],
|
|
23
|
+
sizes: "(max-width: 768px) 100vw, 50vw",
|
|
24
|
+
},
|
|
25
|
+
thumb: { aspect: "1/1", widths: [320, 480], formats: ["webp"], sizes: "192px" },
|
|
26
|
+
// No aspect → resize only, preserving the source's natural ratio.
|
|
27
|
+
content: { widths: [480, 768, 1024, 1280], formats: ["avif", "webp"], sizes: "(max-width: 768px) 100vw, 768px" },
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const FALLBACK_PRESET: ImagePreset = { widths: [480, 768, 1024, 1280], formats: ["avif", "webp"], sizes: "100vw" };
|
|
31
|
+
|
|
32
|
+
/** Resolve a preset by name: config override → built-in default → generic full-width fallback. */
|
|
33
|
+
export function resolveImagePreset(name: string, overrides?: Record<string, ImagePreset>): ImagePreset {
|
|
34
|
+
return overrides?.[name] ?? DEFAULT_PRESETS[name] ?? FALLBACK_PRESET;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type CropOptions = {
|
|
38
|
+
/** Aspect ratio as "W/H" (e.g. "21/9"). When set, the image is cover-cropped to this ratio. */
|
|
39
|
+
aspect?: string;
|
|
40
|
+
/** Focal point as 0–100 percentages. Crop is centered on this point and clamped to stay in frame. */
|
|
41
|
+
focalX?: number | null;
|
|
42
|
+
focalY?: number | null;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// Unlike width, height has no preset list to snap to and is caller-supplied.
|
|
46
|
+
const MAX_HEIGHT = 4320;
|
|
47
|
+
|
|
48
|
+
function clampHeight(height: number): number {
|
|
49
|
+
return Math.min(Math.max(1, Math.round(height)), MAX_HEIGHT);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function clampPercent(value: number, fallback: number): number {
|
|
53
|
+
if (!Number.isFinite(value)) return fallback;
|
|
54
|
+
return Math.min(Math.max(0, Math.round(value)), 100);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function clampWidth(width: number): number {
|
|
58
|
+
return ALLOWED_WIDTHS.reduce((prev, curr) => (Math.abs(curr - width) < Math.abs(prev - width) ? curr : prev));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Parse "21/9", "21:9" or "21x9" into a numeric ratio. Returns undefined when malformed. */
|
|
62
|
+
function parseAspect(aspect?: string): number | undefined {
|
|
63
|
+
if (!aspect) return undefined;
|
|
64
|
+
const [w, h] = aspect.split(/[/:x]/).map(Number);
|
|
65
|
+
if (!w || !h || !isFinite(w) || !isFinite(h)) return undefined;
|
|
66
|
+
return w / h;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isCloudflare(): boolean {
|
|
70
|
+
return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function cmsImage(src: string, width?: number, format: Format = "webp", crop?: CropOptions): string {
|
|
74
|
+
if (!src) return "";
|
|
75
|
+
|
|
76
|
+
const ratio = parseAspect(crop?.aspect);
|
|
77
|
+
const clamped = width ? clampWidth(width) : undefined;
|
|
78
|
+
const height = clamped && ratio ? Math.round(clamped / ratio) : undefined;
|
|
79
|
+
const hasFocal = crop?.focalX != null && crop?.focalY != null;
|
|
80
|
+
|
|
81
|
+
if (isCloudflare()) {
|
|
82
|
+
const parts: string[] = [];
|
|
83
|
+
if (clamped) parts.push(`width=${clamped}`);
|
|
84
|
+
if (height) parts.push(`height=${height}`, "fit=cover");
|
|
85
|
+
if (height)
|
|
86
|
+
parts.push(
|
|
87
|
+
hasFocal ? `gravity=${(crop!.focalX! / 100).toFixed(2)}x${(crop!.focalY! / 100).toFixed(2)}` : "gravity=auto",
|
|
88
|
+
);
|
|
89
|
+
parts.push(`format=${format}`);
|
|
90
|
+
parts.push("quality=80");
|
|
91
|
+
return `/cdn-cgi/image/${parts.join(",")}${src}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const params = new URLSearchParams();
|
|
95
|
+
if (clamped) params.set("w", String(clamped));
|
|
96
|
+
if (height) params.set("h", String(height));
|
|
97
|
+
if (height && hasFocal) {
|
|
98
|
+
params.set("fx", String(Math.round(crop!.focalX!)));
|
|
99
|
+
params.set("fy", String(Math.round(crop!.focalY!)));
|
|
100
|
+
}
|
|
101
|
+
if (format !== "webp") params.set("f", format);
|
|
102
|
+
const qs = params.toString();
|
|
103
|
+
return `/api/cms/img${src}${qs ? `?${qs}` : ""}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function cmsSrcset(
|
|
107
|
+
src: string,
|
|
108
|
+
widths: number[] = [480, 768, 1024, 1280],
|
|
109
|
+
format: Format = "webp",
|
|
110
|
+
crop?: CropOptions,
|
|
111
|
+
): string {
|
|
112
|
+
if (!src) return "";
|
|
113
|
+
return widths.map((width) => `${cmsImage(src, width, format, crop)} ${width}w`).join(", ");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export type TransformOptions = {
|
|
117
|
+
width?: number;
|
|
118
|
+
height?: number;
|
|
119
|
+
format?: string;
|
|
120
|
+
quality?: number;
|
|
121
|
+
focalX?: number | null;
|
|
122
|
+
focalY?: number | null;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
export async function transformImage(
|
|
126
|
+
src: string,
|
|
127
|
+
options: TransformOptions = {},
|
|
128
|
+
): Promise<{ buffer: Buffer; contentType: string } | null> {
|
|
129
|
+
const { existsSync, mkdirSync, readFileSync } = await import("node:fs");
|
|
130
|
+
const { writeFile } = await import("node:fs/promises");
|
|
131
|
+
const path = await import("node:path");
|
|
132
|
+
const sharpModule = "sharp";
|
|
133
|
+
const sharp = (await import(/* @vite-ignore */ sharpModule)).default;
|
|
134
|
+
|
|
135
|
+
// Must match the storage adapter: the source lives wherever uploads are written.
|
|
136
|
+
const uploadsDir = process.env.CMS_UPLOADS_DIR
|
|
137
|
+
? path.resolve(process.env.CMS_UPLOADS_DIR)
|
|
138
|
+
: path.join(process.cwd(), "public", "uploads");
|
|
139
|
+
const cacheDir = path.join(process.cwd(), ".cms-cache", "img");
|
|
140
|
+
|
|
141
|
+
// Resolve the source safely under uploadsDir, rejecting traversal.
|
|
142
|
+
const rel = src.replace(/^\/+/, "").replace(/^uploads(?:\/|$)/, "");
|
|
143
|
+
const filePath = path.resolve(uploadsDir, rel);
|
|
144
|
+
if (filePath !== uploadsDir && !filePath.startsWith(uploadsDir + path.sep)) return null;
|
|
145
|
+
if (!existsSync(filePath)) return null;
|
|
146
|
+
|
|
147
|
+
const resolvedFormat: Format = ALLOWED_FORMATS.includes(options.format as Format)
|
|
148
|
+
? (options.format as Format)
|
|
149
|
+
: "webp";
|
|
150
|
+
const resolvedWidth = options.width ? clampWidth(options.width) : undefined;
|
|
151
|
+
const resolvedHeight = options.height ? clampHeight(options.height) : undefined;
|
|
152
|
+
// Snapped to whole numbers: these are cache-key inputs on a route that needs no session,
|
|
153
|
+
// so continuous values would let one image mint unlimited cache entries.
|
|
154
|
+
const resolvedQuality = clampPercent(options.quality ?? 80, 80);
|
|
155
|
+
const crop = resolvedWidth != null && resolvedHeight != null;
|
|
156
|
+
const focalX = crop && options.focalX != null ? clampPercent(options.focalX, 50) : null;
|
|
157
|
+
const focalY = crop && options.focalY != null ? clampPercent(options.focalY, 50) : null;
|
|
158
|
+
|
|
159
|
+
if (!existsSync(cacheDir)) mkdirSync(cacheDir, { recursive: true });
|
|
160
|
+
const safeName = src.replace(/[^a-zA-Z0-9.-]/g, "_");
|
|
161
|
+
const autoCrop = crop && focalX == null && focalY == null;
|
|
162
|
+
const focalKey = crop ? (autoCrop ? "_fauto" : `_f${focalX ?? "c"}-${focalY ?? "c"}`) : "";
|
|
163
|
+
const cacheKey = `${safeName}_${resolvedWidth ?? 0}x${resolvedHeight ?? 0}${focalKey}_q${resolvedQuality}.${resolvedFormat}`;
|
|
164
|
+
const cachePath = path.join(cacheDir, cacheKey);
|
|
165
|
+
|
|
166
|
+
if (existsSync(cachePath)) {
|
|
167
|
+
return {
|
|
168
|
+
buffer: readFileSync(cachePath),
|
|
169
|
+
contentType: `image/${resolvedFormat}`,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
let pipeline = sharp(readFileSync(filePath));
|
|
174
|
+
|
|
175
|
+
if (autoCrop) {
|
|
176
|
+
pipeline = pipeline.resize(resolvedWidth!, resolvedHeight!, {
|
|
177
|
+
fit: "cover",
|
|
178
|
+
position: sharp.strategy.attention,
|
|
179
|
+
});
|
|
180
|
+
} else if (crop) {
|
|
181
|
+
// Focal-aware cover crop: pick the largest source window matching the target
|
|
182
|
+
// aspect, positioned so the focal point stays framed, then resize to target.
|
|
183
|
+
const meta = await pipeline.metadata();
|
|
184
|
+
const sw = meta.width;
|
|
185
|
+
const sh = meta.height;
|
|
186
|
+
if (sw && sh) {
|
|
187
|
+
const targetAspect = resolvedWidth! / resolvedHeight!;
|
|
188
|
+
const sourceAspect = sw / sh;
|
|
189
|
+
let cropW: number;
|
|
190
|
+
let cropH: number;
|
|
191
|
+
if (sourceAspect > targetAspect) {
|
|
192
|
+
cropH = sh;
|
|
193
|
+
cropW = Math.round(sh * targetAspect);
|
|
194
|
+
} else {
|
|
195
|
+
cropW = sw;
|
|
196
|
+
cropH = Math.round(sw / targetAspect);
|
|
197
|
+
}
|
|
198
|
+
const fx = (focalX ?? 50) / 100;
|
|
199
|
+
const fy = (focalY ?? 50) / 100;
|
|
200
|
+
const left = Math.max(0, Math.min(Math.round(fx * sw - cropW / 2), sw - cropW));
|
|
201
|
+
const top = Math.max(0, Math.min(Math.round(fy * sh - cropH / 2), sh - cropH));
|
|
202
|
+
pipeline = pipeline.extract({ left, top, width: cropW, height: cropH }).resize(resolvedWidth!, resolvedHeight!);
|
|
203
|
+
} else {
|
|
204
|
+
pipeline = pipeline.resize(resolvedWidth!, resolvedHeight!, { fit: "cover" });
|
|
205
|
+
}
|
|
206
|
+
} else if (resolvedWidth) {
|
|
207
|
+
pipeline = pipeline.resize(resolvedWidth, undefined, { withoutEnlargement: true });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
pipeline = pipeline.toFormat(resolvedFormat, { quality: resolvedQuality });
|
|
211
|
+
|
|
212
|
+
const buffer = await pipeline.toBuffer();
|
|
213
|
+
writeFile(cachePath, buffer).catch(() => {});
|
|
214
|
+
|
|
215
|
+
return {
|
|
216
|
+
buffer,
|
|
217
|
+
contentType: `image/${resolvedFormat}`,
|
|
218
|
+
};
|
|
219
|
+
}
|
package/core/index.ts
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
export {
|
|
2
|
+
configureCmsRuntime,
|
|
3
|
+
resetCmsRuntime,
|
|
4
|
+
getCmsRuntime,
|
|
5
|
+
getDb,
|
|
6
|
+
closeDb,
|
|
7
|
+
getStorage,
|
|
8
|
+
getEmail,
|
|
9
|
+
readEnv,
|
|
10
|
+
trackTask,
|
|
11
|
+
flushTasks,
|
|
12
|
+
runWithRequestScope,
|
|
13
|
+
} from "./runtime";
|
|
14
|
+
export type { CmsRuntimeConfig, CmsStorageAdapter, CmsEmailAdapter, RequestScope } from "./runtime";
|
|
15
|
+
|
|
16
|
+
export { initSchema, getSchema, resetSchema } from "./schema";
|
|
17
|
+
|
|
18
|
+
export {
|
|
19
|
+
FIELD_MODEL,
|
|
20
|
+
CONTENT_AST_SCHEMA,
|
|
21
|
+
describeField,
|
|
22
|
+
describeBlockTypes,
|
|
23
|
+
describeCollection,
|
|
24
|
+
describeModel,
|
|
25
|
+
} from "./field-model";
|
|
26
|
+
export type { FieldModelEntry } from "./field-model";
|
|
27
|
+
|
|
28
|
+
export { validateDocument, importDocuments, renderModelMarkdown } from "./migrate";
|
|
29
|
+
export type { ValidationIssue, ValidationResult, ImportItem, ImportReport } from "./migrate";
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
fields,
|
|
33
|
+
defineCollection,
|
|
34
|
+
defineConfig,
|
|
35
|
+
withSite,
|
|
36
|
+
getCollectionMap,
|
|
37
|
+
getDefaultLocale,
|
|
38
|
+
getTranslatableFieldNames,
|
|
39
|
+
isStructuralField,
|
|
40
|
+
getCollectionLabel,
|
|
41
|
+
getLabelField,
|
|
42
|
+
hasRole,
|
|
43
|
+
resolveCollaboration,
|
|
44
|
+
isApprover,
|
|
45
|
+
} from "./define";
|
|
46
|
+
export { customAuth, getSsoProvider, resolveAdminAuth } from "./auth-config";
|
|
47
|
+
export type { ResolvedAdminAuthConfig } from "./auth-config";
|
|
48
|
+
export type {
|
|
49
|
+
CMSConfig,
|
|
50
|
+
CollaborationConfig,
|
|
51
|
+
CollaborationCollection,
|
|
52
|
+
ResolvedCollaboration,
|
|
53
|
+
CollectionConfig,
|
|
54
|
+
CollectionFieldMap,
|
|
55
|
+
FieldConfig,
|
|
56
|
+
TextFieldConfig,
|
|
57
|
+
SlugFieldConfig,
|
|
58
|
+
EmailFieldConfig,
|
|
59
|
+
NumberFieldConfig,
|
|
60
|
+
BooleanFieldConfig,
|
|
61
|
+
DateFieldConfig,
|
|
62
|
+
SelectFieldConfig,
|
|
63
|
+
RichTextFieldConfig,
|
|
64
|
+
ContentFieldConfig,
|
|
65
|
+
ImageFieldConfig,
|
|
66
|
+
RelationFieldConfig,
|
|
67
|
+
ArrayFieldConfig,
|
|
68
|
+
JsonFieldConfig,
|
|
69
|
+
BlocksFieldConfig,
|
|
70
|
+
RichTextNode,
|
|
71
|
+
RichTextDocument,
|
|
72
|
+
ContentNode,
|
|
73
|
+
ContentBlockNode,
|
|
74
|
+
ContentDocument,
|
|
75
|
+
CollectionLabels,
|
|
76
|
+
DatabaseConfig,
|
|
77
|
+
LocaleConfig,
|
|
78
|
+
AdminConfig,
|
|
79
|
+
IntegrationsConfig,
|
|
80
|
+
TaskHandler,
|
|
81
|
+
TaskScheduleConfig,
|
|
82
|
+
AdminAuthConfig,
|
|
83
|
+
AdminAuthMfaConfig,
|
|
84
|
+
AdminAuthPasswordConfig,
|
|
85
|
+
AdminAuthSsoProviderConfig,
|
|
86
|
+
AdminCustomAuthProvider,
|
|
87
|
+
ColorOption,
|
|
88
|
+
ImagePreset,
|
|
89
|
+
ImagesConfig,
|
|
90
|
+
AdminNavItem,
|
|
91
|
+
SearchableConfig,
|
|
92
|
+
WebhookConfig,
|
|
93
|
+
WebhookEvent,
|
|
94
|
+
WebhookContext,
|
|
95
|
+
AdminFieldComponent,
|
|
96
|
+
CollectionAdminConfig,
|
|
97
|
+
FieldCondition,
|
|
98
|
+
SeedDocument,
|
|
99
|
+
CollectionViewConfig,
|
|
100
|
+
AccessContext,
|
|
101
|
+
AccessRule,
|
|
102
|
+
CollectionAccess,
|
|
103
|
+
HookContext,
|
|
104
|
+
CollectionHooks,
|
|
105
|
+
WithSiteOptions,
|
|
106
|
+
} from "./define";
|
|
107
|
+
|
|
108
|
+
export { createCms } from "./api";
|
|
109
|
+
export type { FindOptions } from "./api";
|
|
110
|
+
|
|
111
|
+
export { enqueueTask, drainTasks, tickSchedules, pruneTasks } from "./tasks";
|
|
112
|
+
export { peekRateLimit, hitRateLimit, recordRateLimit, clearRateLimit, pruneRateLimits } from "./rate-limit";
|
|
113
|
+
export type { RateLimitResult, RateLimitOptions } from "./rate-limit";
|
|
114
|
+
export type { EnqueueTaskOptions, DrainResult } from "./tasks";
|
|
115
|
+
|
|
116
|
+
export type CustomFieldProps = {
|
|
117
|
+
name: string;
|
|
118
|
+
field: import("./define").FieldConfig;
|
|
119
|
+
value: string;
|
|
120
|
+
readOnly: boolean;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
export {
|
|
124
|
+
hashPassword,
|
|
125
|
+
verifyPassword,
|
|
126
|
+
hashToken,
|
|
127
|
+
MIN_PASSWORD_LENGTH,
|
|
128
|
+
createSession,
|
|
129
|
+
validateSession,
|
|
130
|
+
destroySession,
|
|
131
|
+
getSessionUser,
|
|
132
|
+
createInvite,
|
|
133
|
+
validateInvite,
|
|
134
|
+
consumeInvite,
|
|
135
|
+
createPasswordReset,
|
|
136
|
+
validatePasswordReset,
|
|
137
|
+
consumePasswordReset,
|
|
138
|
+
SESSION_COOKIE_NAME,
|
|
139
|
+
setSessionCookie,
|
|
140
|
+
clearSessionCookie,
|
|
141
|
+
} from "./auth";
|
|
142
|
+
export type { SessionUser } from "./auth";
|
|
143
|
+
|
|
144
|
+
export { assets, folders } from "./assets";
|
|
145
|
+
export type { AssetRecord, FolderRecord } from "./assets";
|
|
146
|
+
|
|
147
|
+
export { parseBlocks, parseList, cacheTags } from "./content";
|
|
148
|
+
export { renderRichText, createRichTextFromPlainText, richTextToPlainText, htmlToRichText } from "./richtext";
|
|
149
|
+
export {
|
|
150
|
+
SHARED_BLOCK_TYPE,
|
|
151
|
+
SHARED_SECTIONS_COLLECTION,
|
|
152
|
+
extractSharedSectionRefsFromBlocks,
|
|
153
|
+
extractSharedSectionRefsFromContent,
|
|
154
|
+
extractSharedSectionRefsFromDocument,
|
|
155
|
+
getSharedBlockTypes,
|
|
156
|
+
getSharedSectionCacheTags,
|
|
157
|
+
getSharedSectionTagsFromBlocks,
|
|
158
|
+
isSharedBlockReference,
|
|
159
|
+
type SharedBlockReference,
|
|
160
|
+
type SharedSectionOption,
|
|
161
|
+
} from "./shared-sections";
|
|
162
|
+
export {
|
|
163
|
+
cloneValue,
|
|
164
|
+
slugify,
|
|
165
|
+
escapeHtml,
|
|
166
|
+
safeUrl,
|
|
167
|
+
serializeFieldValue,
|
|
168
|
+
contentSegments,
|
|
169
|
+
contentBlocks,
|
|
170
|
+
contentToPlainText,
|
|
171
|
+
} from "./values";
|
|
172
|
+
export type { ContentSegment } from "./values";
|
|
173
|
+
export { cmsImage, cmsSrcset, transformImage, DEFAULT_PRESETS, resolveImagePreset } from "./image";
|
|
174
|
+
export type { CropOptions, TransformOptions } from "./image";
|
|
175
|
+
|
|
176
|
+
export {
|
|
177
|
+
initDateFormat,
|
|
178
|
+
formatDate,
|
|
179
|
+
resolveAdminRoute,
|
|
180
|
+
humanize,
|
|
181
|
+
formatFieldValue,
|
|
182
|
+
getListColumns,
|
|
183
|
+
getFieldGroups,
|
|
184
|
+
getFieldSets,
|
|
185
|
+
} from "./admin";
|
|
186
|
+
export type { AdminRoute } from "./admin";
|
|
187
|
+
|
|
188
|
+
export { acquireLock, releaseLock } from "./locks";
|
|
189
|
+
|
|
190
|
+
export { readLimitedFormData, PayloadTooLargeError } from "./http";
|
|
191
|
+
|
|
192
|
+
export { recordAudit, logAudit, pruneAuditLog, auditRequestMeta, tokenReference } from "./audit";
|
|
193
|
+
export type { AuditEvent, AuditActor } from "./audit";
|
|
194
|
+
export { collaboration, REVIEW_STATES, isReviewState } from "./collaboration";
|
|
195
|
+
export type { ReviewState, CollaborationState, CommentRecord, ActivityRecord } from "./collaboration";
|
|
196
|
+
|
|
197
|
+
export {
|
|
198
|
+
search,
|
|
199
|
+
indexDocument,
|
|
200
|
+
removeDocument,
|
|
201
|
+
reindexAll,
|
|
202
|
+
ensureSearchSchema,
|
|
203
|
+
isCollectionSearchable,
|
|
204
|
+
} from "./search";
|
|
205
|
+
export type { SearchResult, SearchOptions, SearchSort } from "./search";
|
|
206
|
+
|
|
207
|
+
export { isAiEnabled, getAiModel, streamAltText, streamSeoDescription, streamTranslation } from "./ai";
|
|
208
|
+
|
|
209
|
+
export { generate } from "./generator";
|
|
210
|
+
export { seedDatabase } from "./seed";
|
|
211
|
+
export { createAdminUser } from "./create-admin";
|
package/core/locks.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { and, eq, lte } from "drizzle-orm";
|
|
2
|
+
import { nanoid } from "nanoid";
|
|
3
|
+
|
|
4
|
+
import { getDb } from "./runtime";
|
|
5
|
+
import { getSchema } from "./schema";
|
|
6
|
+
|
|
7
|
+
const LOCK_TTL_MS = 5 * 60 * 1000;
|
|
8
|
+
|
|
9
|
+
const getLockTable = () => getSchema().cmsLocks as any;
|
|
10
|
+
const isExpired = (lockedAt: string) => new Date(lockedAt).getTime() + LOCK_TTL_MS < Date.now();
|
|
11
|
+
|
|
12
|
+
export const acquireLock = async (
|
|
13
|
+
collection: string,
|
|
14
|
+
documentId: string,
|
|
15
|
+
userId: string,
|
|
16
|
+
userEmail: string,
|
|
17
|
+
): Promise<{ acquired: true } | { acquired: false; userEmail: string }> => {
|
|
18
|
+
const db = await getDb();
|
|
19
|
+
const table = getLockTable();
|
|
20
|
+
|
|
21
|
+
await db.delete(table).where(lte(table.lockedAt, new Date(Date.now() - LOCK_TTL_MS).toISOString()));
|
|
22
|
+
|
|
23
|
+
const rows = await db
|
|
24
|
+
.select()
|
|
25
|
+
.from(table)
|
|
26
|
+
.where(and(eq(table.collection, collection), eq(table.documentId, documentId)));
|
|
27
|
+
|
|
28
|
+
const existing = rows[0];
|
|
29
|
+
const now = new Date().toISOString();
|
|
30
|
+
|
|
31
|
+
if (existing) {
|
|
32
|
+
if (existing.userId === userId) {
|
|
33
|
+
await db.update(table).set({ lockedAt: now }).where(eq(table._id, existing._id));
|
|
34
|
+
return { acquired: true };
|
|
35
|
+
}
|
|
36
|
+
if (!isExpired(existing.lockedAt)) {
|
|
37
|
+
return { acquired: false, userEmail: existing.userEmail };
|
|
38
|
+
}
|
|
39
|
+
await db.delete(table).where(eq(table._id, existing._id));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
await db.insert(table).values({ _id: nanoid(), collection, documentId, userId, userEmail, lockedAt: now });
|
|
43
|
+
return { acquired: true };
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export const releaseLock = async (collection: string, documentId: string, userId: string): Promise<void> => {
|
|
47
|
+
const db = await getDb();
|
|
48
|
+
const table = getLockTable();
|
|
49
|
+
await db
|
|
50
|
+
.delete(table)
|
|
51
|
+
.where(and(eq(table.collection, collection), eq(table.documentId, documentId), eq(table.userId, userId)));
|
|
52
|
+
};
|
package/core/log.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny leveled logger for CMS internals.
|
|
3
|
+
*
|
|
4
|
+
* Level is read from CMS_LOG_LEVEL (silent | error | warn | info | debug),
|
|
5
|
+
* defaulting to "info". Set CMS_LOG_LEVEL=warn (or silent) to quiet the
|
|
6
|
+
* structured audit lines and other info chatter during bulk scripts:
|
|
7
|
+
*
|
|
8
|
+
* CMS_LOG_LEVEL=warn pnpm cms:seed
|
|
9
|
+
*
|
|
10
|
+
* Reads process.env directly (no runtime coupling) so it works in scripts and
|
|
11
|
+
* in the Worker alike.
|
|
12
|
+
*/
|
|
13
|
+
export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
|
|
14
|
+
|
|
15
|
+
const ORDER: Record<LogLevel, number> = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 };
|
|
16
|
+
|
|
17
|
+
const currentLevel = (): LogLevel => {
|
|
18
|
+
const raw = (typeof process !== "undefined" ? process.env?.CMS_LOG_LEVEL : undefined)?.toLowerCase();
|
|
19
|
+
return raw && raw in ORDER ? (raw as LogLevel) : "info";
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const enabled = (level: Exclude<LogLevel, "silent">) => ORDER[level] <= ORDER[currentLevel()];
|
|
23
|
+
|
|
24
|
+
export const log = {
|
|
25
|
+
error: (...args: unknown[]) => {
|
|
26
|
+
if (enabled("error")) console.error(...args);
|
|
27
|
+
},
|
|
28
|
+
warn: (...args: unknown[]) => {
|
|
29
|
+
if (enabled("warn")) console.warn(...args);
|
|
30
|
+
},
|
|
31
|
+
info: (...args: unknown[]) => {
|
|
32
|
+
if (enabled("info")) console.log(...args);
|
|
33
|
+
},
|
|
34
|
+
debug: (...args: unknown[]) => {
|
|
35
|
+
if (enabled("debug")) console.debug(...args);
|
|
36
|
+
},
|
|
37
|
+
};
|