@kidecms/core 0.26.0 → 0.27.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/ContentEditor.tsx +8 -4
- package/client/preview.ts +1 -1
- package/core/api.ts +2 -0
- package/core/define.ts +11 -0
- package/core/image.ts +46 -12
- package/internals/integration.ts +7 -8
- package/internals/virtual.d.ts +22 -0
- package/package.json +1 -1
- package/platform/cloudflare/cf-env.ts +6 -1
- package/platform/cloudflare/images.ts +88 -0
- package/platform/cloudflare/storage.ts +4 -0
- package/routes/api/img/[...path].ts +29 -16
- package/routes/api/preview/render.astro +51 -0
- package/routes/api/preview/render.ts +0 -41
|
@@ -383,6 +383,12 @@ type Props = {
|
|
|
383
383
|
fullscreen?: boolean;
|
|
384
384
|
};
|
|
385
385
|
|
|
386
|
+
// Stable identities: BubbleMenu dispatches an "updateOptions" transaction whenever
|
|
387
|
+
// these props change, and that transaction would trigger forceTick and a new render.
|
|
388
|
+
const BUBBLE_MENU_OPTIONS = { placement: "top" as const };
|
|
389
|
+
const shouldShowBubbleMenu: React.ComponentProps<typeof BubbleMenu>["shouldShow"] = ({ editor, from, to }) =>
|
|
390
|
+
from !== to && !editor.isActive(BLOCK_NODE_NAME) && !editor.isActive("image");
|
|
391
|
+
|
|
386
392
|
export default function ContentEditor({
|
|
387
393
|
name,
|
|
388
394
|
label,
|
|
@@ -653,10 +659,8 @@ export default function ContentEditor({
|
|
|
653
659
|
{/* Selection toolbar — appears when text is highlighted */}
|
|
654
660
|
<BubbleMenu
|
|
655
661
|
editor={editor}
|
|
656
|
-
options={
|
|
657
|
-
shouldShow={
|
|
658
|
-
from !== to && !ed.isActive(BLOCK_NODE_NAME) && !ed.isActive("image")
|
|
659
|
-
}
|
|
662
|
+
options={BUBBLE_MENU_OPTIONS}
|
|
663
|
+
shouldShow={shouldShowBubbleMenu}
|
|
660
664
|
className="bg-popover flex items-center gap-0.5 rounded-md border p-1 shadow-md"
|
|
661
665
|
>
|
|
662
666
|
<ToolbarButton
|
package/client/preview.ts
CHANGED
|
@@ -23,7 +23,7 @@ if (new URLSearchParams(location.search).has("preview")) {
|
|
|
23
23
|
})
|
|
24
24
|
.then((r) => (r.ok ? r.text() : null))
|
|
25
25
|
.then((html) => {
|
|
26
|
-
//
|
|
26
|
+
// Drop stale responses that finish after a newer edit's request.
|
|
27
27
|
if (html != null && id === pending) els.forEach((el) => (el.innerHTML = html));
|
|
28
28
|
})
|
|
29
29
|
.catch(() => {});
|
package/core/api.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { and, asc, desc, eq, inArray, like, lte, ne, or, sql } from "drizzle-orm";
|
|
2
|
+
import { setCloudflareImageMode } from "./image";
|
|
2
3
|
import { nanoid } from "nanoid";
|
|
3
4
|
|
|
4
5
|
import { setUsageConfig } from "./asset-usage";
|
|
@@ -444,6 +445,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
444
445
|
// Lets assets.delete() check whether a file is still referenced without every
|
|
445
446
|
// caller having to thread the config in.
|
|
446
447
|
setUsageConfig(config);
|
|
448
|
+
setCloudflareImageMode(config.images?.cloudflare);
|
|
447
449
|
|
|
448
450
|
// Webhook `name` routes deliveries — must be unique and non-empty.
|
|
449
451
|
const webhookNames = (config.admin?.webhooks ?? []).map((webhook) => webhook.name.trim());
|
package/core/define.ts
CHANGED
|
@@ -401,6 +401,17 @@ export type ImagePreset = {
|
|
|
401
401
|
export type ImagesConfig = {
|
|
402
402
|
/** Named renditions, merged over the built-in defaults in core/image.ts. */
|
|
403
403
|
presets?: Record<string, ImagePreset>;
|
|
404
|
+
/**
|
|
405
|
+
* How public-page renditions are produced on the Cloudflare target.
|
|
406
|
+
*
|
|
407
|
+
* - `"worker"` (default): `/api/cms/img` URLs, resized in the Worker with the
|
|
408
|
+
* Images binding and cached at the edge. No setup — works in `astro dev`, on
|
|
409
|
+
* `*.workers.dev` and on custom domains alike.
|
|
410
|
+
* - `"cdn-cgi"`: `/cdn-cgi/image` URLs handled entirely by Cloudflare's edge,
|
|
411
|
+
* never invoking the Worker. Requires a custom domain with Image
|
|
412
|
+
* Transformations enabled for the zone; `astro dev` still uses the Worker route.
|
|
413
|
+
*/
|
|
414
|
+
cloudflare?: "worker" | "cdn-cgi";
|
|
404
415
|
};
|
|
405
416
|
|
|
406
417
|
// A collection opts into collaboration by appearing in `collections` — either as a
|
package/core/image.ts
CHANGED
|
@@ -70,6 +70,25 @@ function isCloudflare(): boolean {
|
|
|
70
70
|
return typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
export type CloudflareImageMode = "worker" | "cdn-cgi";
|
|
74
|
+
|
|
75
|
+
// Set by createCms() from `images.cloudflare` in cms.config.ts. Module state rather
|
|
76
|
+
// than a parameter so cmsImageUrl()/cmsSrcset() keep their string-in, string-out
|
|
77
|
+
// signature and <CmsImage> needs no plumbing.
|
|
78
|
+
let cloudflareImageMode: CloudflareImageMode = "worker";
|
|
79
|
+
|
|
80
|
+
export function setCloudflareImageMode(mode?: CloudflareImageMode): void {
|
|
81
|
+
cloudflareImageMode = mode ?? "worker";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// /cdn-cgi/image is served by Cloudflare's edge, which only exists for a deployed
|
|
85
|
+
// custom domain — never in astro dev (workerd, but no edge) — so the opt-in is
|
|
86
|
+
// ignored there and dev renders through the Worker route like everything else.
|
|
87
|
+
function cdnCgiEnabled(): boolean {
|
|
88
|
+
if (cloudflareImageMode !== "cdn-cgi" || !isCloudflare()) return false;
|
|
89
|
+
return !(import.meta as ImportMeta & { env?: { DEV?: boolean } }).env?.DEV;
|
|
90
|
+
}
|
|
91
|
+
|
|
73
92
|
/**
|
|
74
93
|
* Builds a URL for one rendition. This is the low-level primitive — it cannot
|
|
75
94
|
* read the asset record, so it knows nothing about the stored focal point or the
|
|
@@ -78,6 +97,10 @@ function isCloudflare(): boolean {
|
|
|
78
97
|
* To render an image, use `<CmsImage>`, which does all three. Reach for this only
|
|
79
98
|
* when you need a string rather than an element: og:image, CSS background-image,
|
|
80
99
|
* JSON-LD, email HTML.
|
|
100
|
+
*
|
|
101
|
+
* URLs point at `/api/cms/img` on every platform (sharp on Node, the Cloudflare
|
|
102
|
+
* Images binding on Workers). With `images: { cloudflare: "cdn-cgi" }` a deployed
|
|
103
|
+
* Worker emits `/cdn-cgi/image` URLs instead, handled entirely by Cloudflare's edge.
|
|
81
104
|
*/
|
|
82
105
|
export function cmsImageUrl(src: string, width?: number, format: Format = "webp", crop?: CropOptions): string {
|
|
83
106
|
if (!src) return "";
|
|
@@ -87,18 +110,7 @@ export function cmsImageUrl(src: string, width?: number, format: Format = "webp"
|
|
|
87
110
|
const height = clamped && ratio ? Math.round(clamped / ratio) : undefined;
|
|
88
111
|
const hasFocal = crop?.focalX != null && crop?.focalY != null;
|
|
89
112
|
|
|
90
|
-
if (
|
|
91
|
-
const parts: string[] = [];
|
|
92
|
-
if (clamped) parts.push(`width=${clamped}`);
|
|
93
|
-
if (height) parts.push(`height=${height}`, "fit=cover");
|
|
94
|
-
if (height)
|
|
95
|
-
parts.push(
|
|
96
|
-
hasFocal ? `gravity=${(crop!.focalX! / 100).toFixed(2)}x${(crop!.focalY! / 100).toFixed(2)}` : "gravity=auto",
|
|
97
|
-
);
|
|
98
|
-
parts.push(`format=${format}`);
|
|
99
|
-
parts.push("quality=80");
|
|
100
|
-
return `/cdn-cgi/image/${parts.join(",")}${src}`;
|
|
101
|
-
}
|
|
113
|
+
if (cdnCgiEnabled()) return cdnCgiImageUrl(src, clamped, height, format, hasFocal ? crop : undefined);
|
|
102
114
|
|
|
103
115
|
const params = new URLSearchParams();
|
|
104
116
|
if (clamped) params.set("w", String(clamped));
|
|
@@ -112,6 +124,28 @@ export function cmsImageUrl(src: string, width?: number, format: Format = "webp"
|
|
|
112
124
|
return `/api/cms/img${src}${qs ? `?${qs}` : ""}`;
|
|
113
125
|
}
|
|
114
126
|
|
|
127
|
+
/** The `/cdn-cgi/image` form of a rendition URL (the `images.cloudflare: "cdn-cgi"` opt-in). */
|
|
128
|
+
export function cdnCgiImageUrl(
|
|
129
|
+
src: string,
|
|
130
|
+
width?: number,
|
|
131
|
+
height?: number,
|
|
132
|
+
format: Format = "webp",
|
|
133
|
+
focal?: { focalX?: number | null; focalY?: number | null },
|
|
134
|
+
): string {
|
|
135
|
+
const parts: string[] = [];
|
|
136
|
+
if (width) parts.push(`width=${width}`);
|
|
137
|
+
if (height) {
|
|
138
|
+
parts.push(`height=${height}`, "fit=cover");
|
|
139
|
+
parts.push(
|
|
140
|
+
focal?.focalX != null && focal?.focalY != null
|
|
141
|
+
? `gravity=${(focal.focalX / 100).toFixed(2)}x${(focal.focalY / 100).toFixed(2)}`
|
|
142
|
+
: "gravity=auto",
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
parts.push(`format=${format}`, "quality=80");
|
|
146
|
+
return `/cdn-cgi/image/${parts.join(",")}${src}`;
|
|
147
|
+
}
|
|
148
|
+
|
|
115
149
|
export function cmsSrcset(
|
|
116
150
|
src: string,
|
|
117
151
|
widths: number[] = [480, 768, 1024, 1280],
|
package/internals/integration.ts
CHANGED
|
@@ -174,6 +174,7 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
|
|
|
174
174
|
"virtual:kide/runtime": path.resolve(root, runtimePath),
|
|
175
175
|
"virtual:kide/db": path.resolve(root, adaptersPath, "db"),
|
|
176
176
|
"virtual:kide/email": path.resolve(root, adaptersPath, "email"),
|
|
177
|
+
"virtual:kide/storage": path.resolve(root, adaptersPath, "storage"),
|
|
177
178
|
"virtual:kide/block-renderer": path.resolve(root, "src/components/BlockRenderer.astro"),
|
|
178
179
|
"virtual:kide/content-renderer": path.resolve(root, "src/components/ContentRenderer.astro"),
|
|
179
180
|
"virtual:kide/admin-css": wrapperCss,
|
|
@@ -339,14 +340,12 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
|
|
|
339
340
|
pattern: "/api/cms/locks/[...path]",
|
|
340
341
|
entrypoint: new URL("../routes/api/locks/[...path].ts", import.meta.url),
|
|
341
342
|
});
|
|
342
|
-
//
|
|
343
|
-
//
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
});
|
|
349
|
-
}
|
|
343
|
+
// A page partial (not an endpoint using the Container API, which doesn't
|
|
344
|
+
// bundle for production) so live preview works in every deployed build.
|
|
345
|
+
injectRoute({
|
|
346
|
+
pattern: "/api/cms/preview/render",
|
|
347
|
+
entrypoint: new URL("../routes/api/preview/render.astro", import.meta.url),
|
|
348
|
+
});
|
|
350
349
|
injectRoute({
|
|
351
350
|
pattern: "/api/cms/references/[collection]/[id]",
|
|
352
351
|
entrypoint: new URL("../routes/api/references/[collection]/[id].ts", import.meta.url),
|
package/internals/virtual.d.ts
CHANGED
|
@@ -87,6 +87,28 @@ declare module "virtual:kide/db" {
|
|
|
87
87
|
export function getDb(): Promise<any>;
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
declare module "virtual:kide/storage" {
|
|
91
|
+
export function putFile(storagePath: string, data: ArrayBuffer | Uint8Array): Promise<void>;
|
|
92
|
+
export function getFile(storagePath: string): Promise<ArrayBuffer | null>;
|
|
93
|
+
export function getFileStream(storagePath: string): Promise<{ body: ReadableStream; size: number } | null>;
|
|
94
|
+
export function deleteFile(storagePath: string): Promise<void>;
|
|
95
|
+
/** Cloudflare profile only: resize an upload with the Images binding. Absent on Node. */
|
|
96
|
+
export const resizeImage:
|
|
97
|
+
| ((
|
|
98
|
+
request: Request,
|
|
99
|
+
storagePath: string,
|
|
100
|
+
options: {
|
|
101
|
+
width?: number;
|
|
102
|
+
height?: number;
|
|
103
|
+
format?: string;
|
|
104
|
+
quality?: number;
|
|
105
|
+
focalX?: number | null;
|
|
106
|
+
focalY?: number | null;
|
|
107
|
+
},
|
|
108
|
+
) => Promise<Response | null>)
|
|
109
|
+
| undefined;
|
|
110
|
+
}
|
|
111
|
+
|
|
90
112
|
declare module "virtual:kide/email" {
|
|
91
113
|
export function sendInviteEmail(to: string, inviteUrl: string): Promise<boolean>;
|
|
92
114
|
export function sendPasswordResetEmail(to: string, resetUrl: string): Promise<boolean>;
|
package/package.json
CHANGED
|
@@ -15,7 +15,12 @@
|
|
|
15
15
|
|
|
16
16
|
// The bindings Kide's own Cloudflare profile reads — kept in sync with wrangler.toml's
|
|
17
17
|
// [[d1_databases]] and [[r2_buckets]]. Catches a binding-name typo at typecheck time.
|
|
18
|
-
|
|
18
|
+
// IMAGES isn't in wrangler.toml: @astrojs/cloudflare adds it to every build (its
|
|
19
|
+
// `imagesBindingName` option), so it's optional here and images.ts copes without it.
|
|
20
|
+
export type CfEnv = { CMS_DB?: D1Database; CMS_ASSETS?: R2Bucket; IMAGES?: ImagesBinding } & Record<
|
|
21
|
+
string,
|
|
22
|
+
unknown
|
|
23
|
+
>;
|
|
19
24
|
|
|
20
25
|
type CfProxy = { env: CfEnv; dispose: () => Promise<void> };
|
|
21
26
|
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { trackTask } from "../../core/request-scope";
|
|
2
|
+
import { getCfEnv } from "./cf-env";
|
|
3
|
+
|
|
4
|
+
// Mirrors core/image.ts's allowed output formats, keyed by the `f=` query value.
|
|
5
|
+
const OUTPUT_FORMATS: Record<string, ImageOutputOptions["format"]> = {
|
|
6
|
+
webp: "image/webp",
|
|
7
|
+
avif: "image/avif",
|
|
8
|
+
jpeg: "image/jpeg",
|
|
9
|
+
jpg: "image/jpeg",
|
|
10
|
+
png: "image/png",
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type ImageResizeOptions = {
|
|
14
|
+
width?: number;
|
|
15
|
+
height?: number;
|
|
16
|
+
format?: string;
|
|
17
|
+
quality?: number;
|
|
18
|
+
focalX?: number | null;
|
|
19
|
+
focalY?: number | null;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// The Workers Cache API. Absent outside workerd; a no-op on *.workers.dev (only
|
|
23
|
+
// custom domains have a functional edge cache), where the browser cache still
|
|
24
|
+
// applies via the immutable headers below.
|
|
25
|
+
const edgeCache = (): Cache | undefined =>
|
|
26
|
+
typeof caches !== "undefined" ? (caches as CacheStorage & { default?: Cache }).default : undefined;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resizes an upload with the Cloudflare Images binding (`env.IMAGES`, which
|
|
30
|
+
* `@astrojs/cloudflare` declares on every build) and streams the result.
|
|
31
|
+
*
|
|
32
|
+
* This is how every `/api/cms/img` URL — public renditions from `<CmsImage>`,
|
|
33
|
+
* admin thumbnails, hand-written URLs — is served on Workers, where sharp isn't
|
|
34
|
+
* available. Renditions are stored in the edge cache keyed by URL, so a given
|
|
35
|
+
* size is transformed once per location rather than per page view.
|
|
36
|
+
*
|
|
37
|
+
* Returns null when the binding or the object is missing so the route can fall
|
|
38
|
+
* back to the original.
|
|
39
|
+
*/
|
|
40
|
+
export async function resizeWithImagesBinding(
|
|
41
|
+
request: Request,
|
|
42
|
+
storagePath: string,
|
|
43
|
+
options: ImageResizeOptions,
|
|
44
|
+
): Promise<Response | null> {
|
|
45
|
+
const env = await getCfEnv();
|
|
46
|
+
const images = env.IMAGES;
|
|
47
|
+
const bucket = env.CMS_ASSETS;
|
|
48
|
+
if (!images || !bucket) return null;
|
|
49
|
+
|
|
50
|
+
// Headers don't affect the rendition, so key on the URL alone.
|
|
51
|
+
const cache = edgeCache();
|
|
52
|
+
const cacheKey = new Request(request.url, { method: "GET" });
|
|
53
|
+
const cached = await cache?.match(cacheKey);
|
|
54
|
+
if (cached) return cached;
|
|
55
|
+
|
|
56
|
+
const object = await bucket.get(storagePath.replace(/^\/+/, ""));
|
|
57
|
+
if (!object) return null;
|
|
58
|
+
|
|
59
|
+
const { width, height } = options;
|
|
60
|
+
const transform: ImageTransform = {};
|
|
61
|
+
if (width) transform.width = width;
|
|
62
|
+
if (height) transform.height = height;
|
|
63
|
+
if (width && height) {
|
|
64
|
+
// Same crop semantics as the /cdn-cgi/image URLs core emits: cover the box,
|
|
65
|
+
// centring it on the stored focal point when there is one.
|
|
66
|
+
transform.fit = "cover";
|
|
67
|
+
transform.gravity =
|
|
68
|
+
options.focalX != null && options.focalY != null
|
|
69
|
+
? { x: options.focalX / 100, y: options.focalY / 100, mode: "box-center" }
|
|
70
|
+
: "auto";
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const result = await images
|
|
74
|
+
.input(object.body)
|
|
75
|
+
.transform(transform)
|
|
76
|
+
.output({ format: OUTPUT_FORMATS[options.format ?? "webp"] ?? "image/webp", quality: options.quality ?? 80 });
|
|
77
|
+
|
|
78
|
+
const response = new Response(result.image(), {
|
|
79
|
+
headers: {
|
|
80
|
+
"Content-Type": result.contentType(),
|
|
81
|
+
"Cache-Control": "public, max-age=31536000, immutable",
|
|
82
|
+
"X-Content-Type-Options": "nosniff",
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
// Write-through after the response starts streaming; waitUntil keeps it alive.
|
|
86
|
+
if (cache) trackTask(cache.put(cacheKey, response.clone()));
|
|
87
|
+
return response;
|
|
88
|
+
}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { getCfEnv } from "./cf-env";
|
|
2
2
|
|
|
3
|
+
// Reached by the /api/cms/img route via virtual:kide/storage, so only projects on
|
|
4
|
+
// the Cloudflare profile bundle the Images-binding code (it imports cloudflare:workers).
|
|
5
|
+
export { resizeWithImagesBinding as resizeImage } from "./images";
|
|
6
|
+
|
|
3
7
|
async function getBucket(): Promise<R2Bucket> {
|
|
4
8
|
const env = await getCfEnv();
|
|
5
9
|
const bucket = env.CMS_ASSETS;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { APIRoute } from "astro";
|
|
2
2
|
import { getStorage, transformImage } from "../../../core";
|
|
3
|
+
import * as storage from "virtual:kide/storage";
|
|
3
4
|
|
|
4
5
|
export const prerender = false;
|
|
5
6
|
|
|
@@ -18,25 +19,37 @@ const INLINE_SAFE_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "imag
|
|
|
18
19
|
const originalContentType = (src: string) =>
|
|
19
20
|
MIME_TYPES[src.slice(src.lastIndexOf(".")).toLowerCase()] ?? "application/octet-stream";
|
|
20
21
|
|
|
21
|
-
export const GET: APIRoute = async ({ params, url }) => {
|
|
22
|
+
export const GET: APIRoute = async ({ params, request, url }) => {
|
|
22
23
|
const src = `/${params.path}`;
|
|
23
24
|
const num = (key: string) => (url.searchParams.get(key) ? Number(url.searchParams.get(key)) : undefined);
|
|
24
25
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
26
|
+
const options = {
|
|
27
|
+
width: num("w"),
|
|
28
|
+
height: num("h"),
|
|
29
|
+
format: url.searchParams.get("f") || "webp",
|
|
30
|
+
quality: num("q"),
|
|
31
|
+
focalX: num("fx") ?? null,
|
|
32
|
+
focalY: num("fy") ?? null,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// The Cloudflare profile's storage adapter resizes with the Images binding
|
|
36
|
+
// (no sharp, no filesystem on Workers), edge-cached per URL. Any failure —
|
|
37
|
+
// binding absent, local dev without Images support — falls through to the
|
|
38
|
+
// original below. The Node profile exports no resizeImage.
|
|
39
|
+
if (storage.resizeImage) {
|
|
40
|
+
try {
|
|
41
|
+
const response = await storage.resizeImage(request, src, options);
|
|
42
|
+
if (response) return response;
|
|
43
|
+
} catch {
|
|
44
|
+
// fall through
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Node: on-the-fly resizing with sharp against the public/ filesystem. If that
|
|
49
|
+
// can't run (sharp missing), fall back to streaming the untransformed original
|
|
50
|
+
// from storage so images still load.
|
|
31
51
|
try {
|
|
32
|
-
const result = await transformImage(src,
|
|
33
|
-
width: num("w"),
|
|
34
|
-
height: num("h"),
|
|
35
|
-
format: url.searchParams.get("f") || "webp",
|
|
36
|
-
quality: num("q"),
|
|
37
|
-
focalX: num("fx") ?? null,
|
|
38
|
-
focalY: num("fy") ?? null,
|
|
39
|
-
});
|
|
52
|
+
const result = await transformImage(src, options);
|
|
40
53
|
if (result) {
|
|
41
54
|
return new Response(new Uint8Array(result.buffer), {
|
|
42
55
|
headers: {
|
|
@@ -46,7 +59,7 @@ export const GET: APIRoute = async ({ params, url }) => {
|
|
|
46
59
|
});
|
|
47
60
|
}
|
|
48
61
|
} catch {
|
|
49
|
-
// sharp unavailable
|
|
62
|
+
// sharp unavailable — serve the original.
|
|
50
63
|
}
|
|
51
64
|
|
|
52
65
|
const data = await getStorage().getFile(src);
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
---
|
|
2
|
+
// Live-preview render endpoint: the preview tab POSTs unsaved rich text /
|
|
3
|
+
// blocks / content JSON and swaps the returned HTML into `[data-cms]` slots.
|
|
4
|
+
//
|
|
5
|
+
// A page partial rather than an API route on purpose: rendering Astro
|
|
6
|
+
// components from an endpoint needs the Container API, which leans on Vite
|
|
7
|
+
// internals and doesn't bundle for production (Cloudflare Workers in
|
|
8
|
+
// particular). A partial is an ordinary on-demand page — no doctype, no
|
|
9
|
+
// layout, just the component's HTML — so it works identically in dev and in
|
|
10
|
+
// every adapter's production build.
|
|
11
|
+
import BlockRenderer from "virtual:kide/block-renderer";
|
|
12
|
+
import ContentRenderer from "virtual:kide/content-renderer";
|
|
13
|
+
import { parseBlocks, renderRichText } from "../../../core";
|
|
14
|
+
|
|
15
|
+
export const prerender = false;
|
|
16
|
+
export const partial = true;
|
|
17
|
+
|
|
18
|
+
if (Astro.request.method !== "POST") {
|
|
19
|
+
return new Response(null, { status: 405, headers: { Allow: "POST" } });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let type: unknown;
|
|
23
|
+
let data: unknown;
|
|
24
|
+
try {
|
|
25
|
+
({ type, data } = await Astro.request.json());
|
|
26
|
+
} catch {
|
|
27
|
+
return new Response("Invalid JSON body", { status: 400 });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Editors send rich text / content documents either as objects or as the
|
|
31
|
+
// serialized form-field string; blocks arrive serialized and parseBlocks
|
|
32
|
+
// handles both.
|
|
33
|
+
let parsed: unknown = data;
|
|
34
|
+
if ((type === "content" || type === "richText") && typeof data === "string") {
|
|
35
|
+
try {
|
|
36
|
+
parsed = JSON.parse(data);
|
|
37
|
+
} catch {
|
|
38
|
+
return new Response("Invalid document JSON", { status: 400 });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (type !== "blocks" && type !== "content" && type !== "richText") {
|
|
43
|
+
return new Response("Unknown preview type", { status: 400 });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
Astro.response.headers.set("Cache-Control", "no-store");
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
{type === "blocks" && <BlockRenderer blocks={parseBlocks(data)} status="any" />}
|
|
50
|
+
{type === "content" && <ContentRenderer content={parsed as any} status="any" />}
|
|
51
|
+
{type === "richText" && <Fragment set:html={renderRichText(parsed as any) ?? ""} />}
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import type { APIRoute } from "astro";
|
|
2
|
-
import { experimental_AstroContainer as AstroContainer } from "astro/container";
|
|
3
|
-
import { loadRenderers } from "astro:container";
|
|
4
|
-
import { getContainerRenderer } from "@astrojs/react/container-renderer";
|
|
5
|
-
|
|
6
|
-
import BlockRenderer from "virtual:kide/block-renderer";
|
|
7
|
-
import ContentRenderer from "virtual:kide/content-renderer";
|
|
8
|
-
import { renderRichText, parseBlocks } from "../../../core";
|
|
9
|
-
|
|
10
|
-
export const prerender = false;
|
|
11
|
-
|
|
12
|
-
let containerPromise: Promise<AstroContainer> | null = null;
|
|
13
|
-
const getContainer = () => {
|
|
14
|
-
if (!containerPromise) {
|
|
15
|
-
containerPromise = (async () => {
|
|
16
|
-
const renderers = await loadRenderers([getContainerRenderer()]);
|
|
17
|
-
return AstroContainer.create({ renderers });
|
|
18
|
-
})();
|
|
19
|
-
}
|
|
20
|
-
return containerPromise;
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
export const POST: APIRoute = async ({ request }) => {
|
|
24
|
-
const { type, data } = await request.json();
|
|
25
|
-
|
|
26
|
-
let html = "";
|
|
27
|
-
if (type === "blocks") {
|
|
28
|
-
const blocks = parseBlocks(data);
|
|
29
|
-
const container = await getContainer();
|
|
30
|
-
html = await container.renderToString(BlockRenderer, { props: { blocks, status: "any" } });
|
|
31
|
-
} else if (type === "content") {
|
|
32
|
-
const parsed = typeof data === "string" ? JSON.parse(data) : data;
|
|
33
|
-
const container = await getContainer();
|
|
34
|
-
html = await container.renderToString(ContentRenderer, { props: { content: parsed, status: "any" } });
|
|
35
|
-
} else if (type === "richText") {
|
|
36
|
-
const parsed = typeof data === "string" ? JSON.parse(data) : data;
|
|
37
|
-
html = renderRichText(parsed) ?? "";
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return new Response(html, { headers: { "Content-Type": "text/html" } });
|
|
41
|
-
};
|