@kidecms/core 0.26.1 → 0.27.1

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.
@@ -3,6 +3,7 @@
3
3
  import { useState, useCallback, useEffect, useRef } from "react";
4
4
  import { ArrowUpRight, GripVertical, ChevronRight, Link2, Plus, Save, Trash2, Unlink } from "lucide-react";
5
5
  import { cn } from "../lib/utils";
6
+ import { openPreviewChannel } from "../lib/preview-channel";
6
7
  import {
7
8
  DndContext,
8
9
  closestCenter,
@@ -300,8 +301,9 @@ export default function BlockEditor({
300
301
  // Live preview: broadcast block data for server-side rendering. Also replay the
301
302
  // current value when a preview tab opened after edits announces itself.
302
303
  useEffect(() => {
303
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
304
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
304
305
  const channel = previewChannelRef.current;
306
+ if (!channel) return;
305
307
  const broadcast = () => channel.postMessage({ field: name, value: serializeBlocks(blocks), render: "blocks" });
306
308
  broadcast();
307
309
  channel.onmessage = (e: MessageEvent) => {
@@ -27,6 +27,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
27
27
  import { Input } from "./ui/input";
28
28
  import { cn } from "../lib/utils";
29
29
  import { toggleHeading } from "../lib/editor-commands";
30
+ import { openPreviewChannel } from "../lib/preview-channel";
30
31
  import {
31
32
  LinkDialog,
32
33
  fetchLinkGroups,
@@ -457,8 +458,9 @@ export default function ContentEditor({
457
458
 
458
459
  // Replay the current value when a preview tab opened after edits announces itself
459
460
  useEffect(() => {
460
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
461
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
461
462
  const channel = previewChannelRef.current;
463
+ if (!channel) return;
462
464
  channel.onmessage = (e: MessageEvent) => {
463
465
  if (e.data?.type === "preview-ready") {
464
466
  channel.postMessage({ field: name, value: cmsJson, render: "content" });
@@ -495,8 +497,8 @@ export default function ContentEditor({
495
497
  const json = JSON.stringify(cmsDoc);
496
498
  setCmsJson(json);
497
499
  // Live preview: broadcast for server-side rendering
498
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
499
- previewChannelRef.current.postMessage({ field: name, value: json, render: "content" });
500
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
501
+ previewChannelRef.current?.postMessage({ field: name, value: json, render: "content" });
500
502
  },
501
503
  onSelectionUpdate: forceTick,
502
504
  onTransaction: forceTick,
@@ -27,6 +27,7 @@ import { Label } from "./ui/label";
27
27
  import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
28
28
  import { cn } from "../lib/utils";
29
29
  import { toggleHeading } from "../lib/editor-commands";
30
+ import { openPreviewChannel } from "../lib/preview-channel";
30
31
  import ImageBrowseDialog from "./ImageBrowseDialog";
31
32
 
32
33
  // -----------------------------------------------
@@ -441,8 +442,9 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
441
442
 
442
443
  // Replay the current value when a preview tab opened after edits announces itself
443
444
  useEffect(() => {
444
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
445
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
445
446
  const channel = previewChannelRef.current;
447
+ if (!channel) return;
446
448
  channel.onmessage = (e: MessageEvent) => {
447
449
  if (e.data?.type === "preview-ready") {
448
450
  channel.postMessage({ field: name, value: cmsJson, render: "richText" });
@@ -475,8 +477,8 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
475
477
  setCmsJson(json);
476
478
  onChange?.(json);
477
479
  // Live preview: broadcast for server-side rendering
478
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
479
- previewChannelRef.current.postMessage({ field: name, value: json, render: "richText" });
480
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
481
+ previewChannelRef.current?.postMessage({ field: name, value: json, render: "richText" });
480
482
  },
481
483
  onSelectionUpdate: forceTick,
482
484
  onTransaction: forceTick,
@@ -11,6 +11,7 @@ import {
11
11
  AlertDialogHeader,
12
12
  AlertDialogTitle,
13
13
  } from "./ui/alert-dialog";
14
+ import { openPreviewChannel } from "../lib/preview-channel";
14
15
  import { Button } from "./ui/button";
15
16
 
16
17
  /**
@@ -68,26 +69,27 @@ export default function UnsavedGuard({
68
69
  };
69
70
 
70
71
  // Live preview: broadcast field changes to any open preview tab
71
- const previewChannel = new BroadcastChannel("cms-preview");
72
+ const previewChannel = openPreviewChannel();
72
73
  const broadcastField = (e: Event) => {
73
74
  const target = e.target as HTMLInputElement;
74
75
  if (!target.name || target.name.startsWith("_") || target.name === "redirectTo") return;
75
76
  // Skip hidden inputs — complex fields (rich text, blocks) handle their own broadcasting
76
77
  if (target.type === "hidden") return;
77
- previewChannel.postMessage({ field: target.name, value: target.value });
78
+ previewChannel?.postMessage({ field: target.name, value: target.value });
78
79
  };
79
80
 
80
81
  // A preview tab opened after edits were made announces itself; replay the
81
82
  // current value of every simple field so it doesn't miss unsaved changes.
82
- previewChannel.onmessage = (e: MessageEvent) => {
83
- if (e.data?.type !== "preview-ready") return;
84
- for (const el of Array.from(form.elements)) {
85
- const input = el as HTMLInputElement;
86
- if (!input.name || input.name.startsWith("_") || input.name === "redirectTo") continue;
87
- if (input.type === "hidden" || input.type === "submit" || input.type === "button") continue;
88
- previewChannel.postMessage({ field: input.name, value: input.value });
89
- }
90
- };
83
+ if (previewChannel)
84
+ previewChannel.onmessage = (e: MessageEvent) => {
85
+ if (e.data?.type !== "preview-ready") return;
86
+ for (const el of Array.from(form.elements)) {
87
+ const input = el as HTMLInputElement;
88
+ if (!input.name || input.name.startsWith("_") || input.name === "redirectTo") continue;
89
+ if (input.type === "hidden" || input.type === "submit" || input.type === "button") continue;
90
+ previewChannel?.postMessage({ field: input.name, value: input.value });
91
+ }
92
+ };
91
93
 
92
94
  form.addEventListener("input", checkDirty);
93
95
  form.addEventListener("input", broadcastField);
@@ -101,7 +103,7 @@ export default function UnsavedGuard({
101
103
  form.removeEventListener("change", checkDirty);
102
104
  form.removeEventListener("change", broadcastField);
103
105
  form.removeEventListener("submit", handleSubmit);
104
- previewChannel.close();
106
+ previewChannel?.close();
105
107
  };
106
108
  }, [formId, isNew, isDraft]);
107
109
 
@@ -0,0 +1,13 @@
1
+ // Live preview is scoped per document: the edit view stamps
2
+ // `data-preview-channel="<collection>:<id>"` and links the preview tab with the same
3
+ // key in `?preview=`, so an editor only drives the preview of its own document
4
+ // (a single shared channel let any open edit tab overwrite every preview tab).
5
+
6
+ export const previewChannelName = (key: string) => `cms-preview:${key}`;
7
+
8
+ /** Opens this edit view's preview channel, or null when the document has no preview. */
9
+ export function openPreviewChannel(): BroadcastChannel | null {
10
+ if (typeof document === "undefined" || typeof BroadcastChannel === "undefined") return null;
11
+ const key = document.querySelector<HTMLElement>("[data-preview-channel]")?.dataset.previewChannel;
12
+ return key ? new BroadcastChannel(previewChannelName(key)) : null;
13
+ }
@@ -186,11 +186,12 @@ const hasSidebarMeta = reverseRefs.length > 0 || hasDocMeta;
186
186
  const hasSidebarColumn = !isSubmissionView && (hasSidebarFields || hasSidebarMeta);
187
187
 
188
188
  const hasPreview = !!(mode === "edit" && (collection.preview || (collection.pathPrefix && doc?.slug)));
189
- const previewUrl = hasPreview
190
- ? typeof collection.preview === "string"
191
- ? `${collection.preview}?preview=true`
192
- : `${cms.meta.getRouteForDocument(collection.slug, doc)}?preview=true`
193
- : null;
189
+ // Live-preview channel key: the preview tab only listens to this document's editor.
190
+ const previewKey = hasPreview && documentId ? `${collection.slug}:${documentId}` : null;
191
+ const previewUrl =
192
+ hasPreview && previewKey
193
+ ? `${typeof collection.preview === "string" ? collection.preview : cms.meta.getRouteForDocument(collection.slug, doc)}?preview=${encodeURIComponent(previewKey)}`
194
+ : null;
194
195
 
195
196
  const getCurrentValue = (fieldName: string) => (doc ? doc[fieldName] : undefined);
196
197
  const getSharedValue = (fieldName: string) => (baseDoc ? baseDoc[fieldName] : undefined);
@@ -437,7 +438,7 @@ const publishBlocked =
437
438
  (doc?._status === "draft" || doc?._status === "scheduled" || (doc && getVisualStatus(doc) === "changed")),
438
439
  )}
439
440
  />
440
- <div id="document-edit-area">
441
+ <div id="document-edit-area" data-preview-channel={!translationMode ? previewKey : undefined}>
441
442
  {collection.slug === "users" && mode === "edit" && Astro.url.searchParams.get("inviteToken") && (
442
443
  <AdminCard title={Astro.url.searchParams.get("emailSent") === "true" ? "Invitation sent" : "Invite link"}>
443
444
  {Astro.url.searchParams.get("emailSent") === "true" ? (
@@ -200,7 +200,9 @@
200
200
  }
201
201
  if (u.searchParams.get("_toast") === "success") {
202
202
  try {
203
- new BroadcastChannel("cms-preview").postMessage({ type: "reload" });
203
+ var previewEl = document.querySelector("[data-preview-channel]");
204
+ var previewKey = previewEl && previewEl.getAttribute("data-preview-channel");
205
+ if (previewKey) new BroadcastChannel("cms-preview:" + previewKey).postMessage({ type: "reload" });
204
206
  } catch (e) {}
205
207
  }
206
208
  if (window.parent !== window && u.searchParams.get("_toast") === "success") {
package/client/preview.ts CHANGED
@@ -1,5 +1,8 @@
1
- if (new URLSearchParams(location.search).has("preview")) {
2
- const ch = new BroadcastChannel("cms-preview");
1
+ // `?preview=<collection>:<id>` (as linked from the edit view) scopes live updates to
2
+ // that document's editor. A bare `?preview` / `?preview=true` only shows drafts.
3
+ const previewKey = new URLSearchParams(location.search).get("preview");
4
+ if (previewKey && previewKey !== "true") {
5
+ const ch = new BroadcastChannel(`cms-preview:${previewKey}`);
3
6
  let pending = 0;
4
7
 
5
8
  ch.onmessage = (e: MessageEvent) => {
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 (isCloudflare()) {
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],
@@ -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,
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.26.1",
3
+ "version": "0.27.1",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -15,7 +15,9 @@
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
- export type CfEnv = { CMS_DB?: D1Database; CMS_ASSETS?: R2Bucket } & Record<string, unknown>;
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<string, unknown>;
19
21
 
20
22
  type CfProxy = { env: CfEnv; dispose: () => Promise<void> };
21
23
 
@@ -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
- // On-the-fly resizing needs sharp + a real filesystem (public/). On the
26
- // Cloudflare target sharp is removed and the dev runtime is workerd (no fs),
27
- // and uploads live in object storage rather than public/ — so transformImage
28
- // can't run. Attempt it, but fall back to streaming the untransformed original
29
- // from storage so images still load. (In production on Cloudflare this route
30
- // is bypassed entirely: cmsImageUrl() emits /cdn-cgi/image URLs there.)
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 / no filesystem in this runtime — serve the original.
62
+ // sharp unavailable — serve the original.
50
63
  }
51
64
 
52
65
  const data = await getStorage().getFile(src);