@nodeart/emdash-plugin-picture 0.0.0-stage → 0.1.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.
@@ -0,0 +1,158 @@
1
+ import { DEFAULT_IMAGE_CATALOG, ImageCatalog, ImageOutputFormat, ImageRoleName } from "./catalog.mjs";
2
+
3
+ //#region src/resolve-media.d.ts
4
+ declare const EMDASH_MEDIA_PREFIX = "/_emdash/api/media/file/";
5
+ declare const MEDIA_FILE_PREFIX = "/_emdash/api/media/file/";
6
+ declare const EMDASH_IMAGE_ENDPOINT = "/_image";
7
+ declare const MAX_CUSTOM_WIDTHS = 16;
8
+ type PictureFallbackFormat = ImageOutputFormat;
9
+ interface MediaSourceCandidate {
10
+ url: string;
11
+ width: number;
12
+ height?: number;
13
+ }
14
+ interface MediaVariantFormats {
15
+ avif: MediaSourceCandidate[];
16
+ png: MediaSourceCandidate[];
17
+ width?: number;
18
+ height?: number;
19
+ sizes?: string;
20
+ }
21
+ type MediaVariant = MediaVariantFormats;
22
+ interface MediaSource {
23
+ url: string;
24
+ width?: number;
25
+ height?: number;
26
+ alt?: string;
27
+ mimeType?: string;
28
+ filename?: string;
29
+ }
30
+ interface MediaProps {
31
+ url: string;
32
+ originalUrl?: string;
33
+ variants?: Record<string, MediaVariantFormats>;
34
+ alt?: string;
35
+ width?: number;
36
+ height?: number;
37
+ mimeType?: string;
38
+ filename?: string;
39
+ }
40
+ interface MediaRef {
41
+ id?: string | null;
42
+ mediaId?: string | null;
43
+ provider?: string | null;
44
+ storageKey?: string | null;
45
+ src?: string | null;
46
+ url?: string | null;
47
+ alt?: string | null;
48
+ width?: number | null;
49
+ height?: number | null;
50
+ mimeType?: string | null;
51
+ filename?: string | null;
52
+ asset?: {
53
+ _ref?: string | null;
54
+ url?: string | null;
55
+ src?: string | null;
56
+ storageKey?: string | null;
57
+ provider?: string | null;
58
+ meta?: Record<string, unknown> | null;
59
+ } | null;
60
+ meta?: Record<string, unknown> | null;
61
+ }
62
+ type ResolveMediaInput = MediaProps | MediaRef | string | null | undefined;
63
+ interface ResolveMediaOptions {
64
+ allowedHosts?: readonly string[];
65
+ }
66
+ type MediaRoleScope<TCatalog extends ImageCatalog = ImageCatalog> = 'all' | readonly ImageRoleName<TCatalog>[] | readonly string[];
67
+ interface PictureRenderSource {
68
+ type: 'image/avif' | 'image/png';
69
+ srcset: string;
70
+ sizes?: string;
71
+ }
72
+ interface PictureRenderImg {
73
+ src: string;
74
+ srcset?: string;
75
+ sizes?: string;
76
+ alt: string;
77
+ width?: number;
78
+ height?: number;
79
+ }
80
+ interface PictureRenderProps {
81
+ resolved: MediaProps;
82
+ resolvedSizes?: string;
83
+ fallbackSrc: string;
84
+ pngSrcSet?: string;
85
+ avifSrcSet?: string;
86
+ alt: string;
87
+ width?: number;
88
+ height?: number;
89
+ sources: PictureRenderSource[];
90
+ img: PictureRenderImg;
91
+ }
92
+ interface ResolvePictureOptions<TCatalog extends ImageCatalog = ImageCatalog> {
93
+ media: unknown;
94
+ preset: (ImageRoleName<TCatalog> | (string & {})) | null;
95
+ catalog?: TCatalog;
96
+ sizes?: string;
97
+ alt?: string;
98
+ width?: number;
99
+ height?: number;
100
+ fallbackFormat?: PictureFallbackFormat;
101
+ allowedHosts?: readonly string[];
102
+ }
103
+ /**
104
+ * Error shaped to satisfy EmDash's duck-typed `isPluginRouteError()` guard
105
+ * without importing `emdash` inside the isolated sandbox runtime.
106
+ */
107
+ declare class PictureRouteError extends Error {
108
+ readonly code: string;
109
+ readonly status: number;
110
+ constructor(message: string, code?: string, status?: number);
111
+ }
112
+ /**
113
+ * Build a `/_image` URL with parameters in EmDash's canonical order (`href`, `w`, `h`, `q`, `f`)
114
+ * so `@emdash-cms/cloudflare/image-endpoint` serves the transform directly without a 301 redirect.
115
+ * Quality is omitted for `png` so Cloudflare Images keeps PNG output lossless instead of PNG8.
116
+ */
117
+ declare function buildEmDashTransformUrl(opts: {
118
+ href: string;
119
+ width: number;
120
+ height?: number;
121
+ format: ImageOutputFormat;
122
+ quality?: number;
123
+ }): string;
124
+ /** Check whether a media path points to a safe internal EmDash storage object. */
125
+ declare function isTransformableEmDashPath(href: string): boolean;
126
+ /**
127
+ * EmDash library files (flat storage key without query/traversal) and canonical `/_image`
128
+ * transforms referencing local/same-origin library files are eligible for edge caching.
129
+ */
130
+ declare function isImmutableMediaRequest(url: URL): boolean;
131
+ declare function isSafeMediaUrl(raw: string): boolean;
132
+ /**
133
+ * Resolve any EmDash media ref, PortableText image payload, URL string, or pre-resolved `MediaProps`
134
+ * into a serializable `MediaProps` containing AVIF and PNG srcset variants for the requested roles.
135
+ */
136
+ declare function resolveMedia<TCatalog extends ImageCatalog = typeof DEFAULT_IMAGE_CATALOG>(input: unknown, roles?: MediaRoleScope<TCatalog>, catalog?: TCatalog, options?: ResolveMediaOptions): MediaProps | null;
137
+ declare function mediaSrc(media: MediaProps | null | undefined): string;
138
+ declare function candidateSrcSet(candidates: MediaSourceCandidate[]): string;
139
+ declare function intrinsicDimensions(media: MediaProps, variants: MediaVariantFormats | undefined): {
140
+ width?: number;
141
+ height?: number;
142
+ };
143
+ /** Shared view-model resolver for `<MediaPicture.astro>`, `<MediaPicture.svelte>`, and plugin routes. */
144
+ declare function resolvePictureRenderProps<TCatalog extends ImageCatalog = typeof DEFAULT_IMAGE_CATALOG>(opts: ResolvePictureOptions<TCatalog>): PictureRenderProps | null;
145
+ type ResolvePictureRouteResult = {
146
+ ok: true;
147
+ preset: string;
148
+ media: MediaProps;
149
+ sources: PictureRenderSource[];
150
+ img: PictureRenderImg;
151
+ } | {
152
+ ok: false;
153
+ error: string;
154
+ };
155
+ /** Pure route handler logic shared by the sandboxed `src/plugin.ts` and in-process `createPlugin()`. */
156
+ declare function resolvePictureRouteQuery(input: unknown): ResolvePictureRouteResult;
157
+ //#endregion
158
+ export { EMDASH_IMAGE_ENDPOINT, EMDASH_MEDIA_PREFIX, MAX_CUSTOM_WIDTHS, MEDIA_FILE_PREFIX, MediaProps, MediaRef, MediaRoleScope, MediaSource, MediaSourceCandidate, MediaVariant, MediaVariantFormats, PictureFallbackFormat, PictureRenderImg, PictureRenderProps, PictureRenderSource, PictureRouteError, ResolveMediaInput, ResolveMediaOptions, ResolvePictureOptions, ResolvePictureRouteResult, buildEmDashTransformUrl, candidateSrcSet, intrinsicDimensions, isImmutableMediaRequest, isSafeMediaUrl, isTransformableEmDashPath, mediaSrc, resolveMedia, resolvePictureRenderProps, resolvePictureRouteQuery };
@@ -0,0 +1,505 @@
1
+ import { DEFAULT_IMAGE_CATALOG, MAX_IMAGE_DIMENSION, computeVariantDimensions, defineImageCatalog, isTransformableImage } from "./catalog.mjs";
2
+
3
+ //#region src/resolve-media.ts
4
+ const EMDASH_MEDIA_PREFIX = "/_emdash/api/media/file/";
5
+ const MEDIA_FILE_PREFIX = EMDASH_MEDIA_PREFIX;
6
+ const EMDASH_IMAGE_ENDPOINT = "/_image";
7
+ const MAX_CUSTOM_WIDTHS = 16;
8
+ const SAFE_STORAGE_KEY_RE = /^[A-Za-z0-9._-]+$/;
9
+ const POSITIVE_INT_RE = /^[1-9]\d*$/;
10
+ const ALLOWED_IMAGE_PARAMS = new Set([
11
+ "href",
12
+ "w",
13
+ "h",
14
+ "q",
15
+ "f"
16
+ ]);
17
+ const ALLOWED_TRANSFORM_FORMATS = new Set([
18
+ "avif",
19
+ "webp",
20
+ "png",
21
+ "jpeg"
22
+ ]);
23
+ const DEFAULT_AVIF_QUALITY = 76;
24
+ const MAX_URL_LENGTH = 2048;
25
+ const MAX_TEXT_PARAM_LENGTH = 512;
26
+ /**
27
+ * Error shaped to satisfy EmDash's duck-typed `isPluginRouteError()` guard
28
+ * without importing `emdash` inside the isolated sandbox runtime.
29
+ */
30
+ var PictureRouteError = class extends Error {
31
+ code;
32
+ status;
33
+ constructor(message, code = "BAD_REQUEST", status = 400) {
34
+ super(message);
35
+ this.name = "PluginRouteError";
36
+ this.code = code;
37
+ this.status = status;
38
+ }
39
+ };
40
+ /**
41
+ * Build a `/_image` URL with parameters in EmDash's canonical order (`href`, `w`, `h`, `q`, `f`)
42
+ * so `@emdash-cms/cloudflare/image-endpoint` serves the transform directly without a 301 redirect.
43
+ * Quality is omitted for `png` so Cloudflare Images keeps PNG output lossless instead of PNG8.
44
+ */
45
+ function buildEmDashTransformUrl(opts) {
46
+ const params = new URLSearchParams();
47
+ params.set("href", opts.href);
48
+ params.set("w", String(opts.width));
49
+ if (opts.height !== void 0) params.set("h", String(opts.height));
50
+ if (opts.format !== "png" && opts.quality !== void 0) params.set("q", String(opts.quality));
51
+ params.set("f", opts.format);
52
+ return `${EMDASH_IMAGE_ENDPOINT}?${params.toString()}`;
53
+ }
54
+ /** Check whether a media path points to a safe internal EmDash storage object. */
55
+ function isTransformableEmDashPath(href) {
56
+ if (!href.startsWith(EMDASH_MEDIA_PREFIX)) return false;
57
+ const storageKey = href.slice(24);
58
+ return storageKey.length > 0 && SAFE_STORAGE_KEY_RE.test(storageKey) && !storageKey.includes("..");
59
+ }
60
+ function parsePositiveIntInRange(raw, min, max) {
61
+ if (raw === null || !POSITIVE_INT_RE.test(raw)) return null;
62
+ const n = Number(raw);
63
+ return Number.isSafeInteger(n) && n >= min && n <= max ? n : null;
64
+ }
65
+ /**
66
+ * EmDash library files (flat storage key without query/traversal) and canonical `/_image`
67
+ * transforms referencing local/same-origin library files are eligible for edge caching.
68
+ */
69
+ function isImmutableMediaRequest(url) {
70
+ if (url.pathname.startsWith(EMDASH_MEDIA_PREFIX)) return url.search === "" && isTransformableEmDashPath(url.pathname);
71
+ if (url.pathname !== EMDASH_IMAGE_ENDPOINT) return false;
72
+ for (const key of url.searchParams.keys()) if (!ALLOWED_IMAGE_PARAMS.has(key) || url.searchParams.getAll(key).length !== 1) return false;
73
+ const href = url.searchParams.get("href");
74
+ if (!href) return false;
75
+ if (parsePositiveIntInRange(url.searchParams.get("w"), 1, MAX_IMAGE_DIMENSION) === null) return false;
76
+ const hRaw = url.searchParams.get("h");
77
+ if (hRaw !== null && parsePositiveIntInRange(hRaw, 1, MAX_IMAGE_DIMENSION) === null) return false;
78
+ const qRaw = url.searchParams.get("q");
79
+ if (qRaw !== null && parsePositiveIntInRange(qRaw, 1, 100) === null) return false;
80
+ const fRaw = url.searchParams.get("f");
81
+ if (fRaw !== null && !ALLOWED_TRANSFORM_FORMATS.has(fRaw)) return false;
82
+ if (isTransformableEmDashPath(href)) return true;
83
+ try {
84
+ const parsed = new URL(href);
85
+ return parsed.origin === url.origin && parsed.search === "" && parsed.hash === "" && isTransformableEmDashPath(parsed.pathname);
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+ function isRecord(value) {
91
+ return typeof value === "object" && value !== null && !Array.isArray(value);
92
+ }
93
+ function stringOrUndefined(value) {
94
+ if (typeof value !== "string") return void 0;
95
+ const trimmed = value.trim();
96
+ return trimmed.length > 0 ? trimmed : void 0;
97
+ }
98
+ function positiveDimension(value) {
99
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.round(value) : void 0;
100
+ }
101
+ function isSafeMediaUrl(raw) {
102
+ const trimmed = raw.trim();
103
+ if (!trimmed || trimmed.length > MAX_URL_LENGTH) return false;
104
+ if (trimmed.startsWith("//")) return false;
105
+ if (trimmed.startsWith("/")) return true;
106
+ try {
107
+ const parsed = new URL(trimmed);
108
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
113
+ function isAllowedHost(hostname, allowedHosts) {
114
+ if (!allowedHosts || allowedHosts.length === 0) return false;
115
+ const normalized = hostname.toLowerCase();
116
+ return allowedHosts.some((pattern) => {
117
+ const p = pattern.trim().toLowerCase();
118
+ if (!p) return false;
119
+ if (p.startsWith("*.")) {
120
+ const suffix = p.slice(1);
121
+ return normalized.endsWith(suffix) && normalized.length > suffix.length;
122
+ }
123
+ return normalized === p;
124
+ });
125
+ }
126
+ function emdashMediaPath(raw, hasLocalProvenance, allowedHosts) {
127
+ const trimmed = raw.trim();
128
+ if (!isSafeMediaUrl(trimmed)) return null;
129
+ if (trimmed.startsWith(EMDASH_MEDIA_PREFIX)) {
130
+ try {
131
+ const normalized = new URL(trimmed, "http://localhost");
132
+ if (isTransformableEmDashPath(normalized.pathname)) return normalized.pathname;
133
+ } catch {
134
+ return null;
135
+ }
136
+ return null;
137
+ }
138
+ if (trimmed.startsWith("/")) return null;
139
+ try {
140
+ const url = new URL(trimmed);
141
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
142
+ if (isTransformableEmDashPath(url.pathname) && (hasLocalProvenance || isAllowedHost(url.hostname, allowedHosts))) return url.pathname;
143
+ } catch {
144
+ return null;
145
+ }
146
+ return null;
147
+ }
148
+ function safeStorageKey(value) {
149
+ const str = stringOrUndefined(value);
150
+ if (!str) return void 0;
151
+ return SAFE_STORAGE_KEY_RE.test(str) && !str.includes("..") ? str : void 0;
152
+ }
153
+ function hasLocalMediaProvenance(rawObj) {
154
+ const provider = stringOrUndefined(rawObj.provider);
155
+ if (provider && provider !== "local") return false;
156
+ const asset = isRecord(rawObj.asset) ? rawObj.asset : void 0;
157
+ const assetProvider = stringOrUndefined(asset?.provider);
158
+ if (assetProvider && assetProvider !== "local") return false;
159
+ return Boolean(stringOrUndefined(rawObj.id) ?? stringOrUndefined(rawObj.mediaId) ?? stringOrUndefined(rawObj.storageKey) ?? stringOrUndefined(asset?._ref) ?? stringOrUndefined(asset?.storageKey));
160
+ }
161
+ function extractMediaUrl(rawObj, allowedHosts) {
162
+ const meta = isRecord(rawObj.meta) ? rawObj.meta : void 0;
163
+ const asset = isRecord(rawObj.asset) ? rawObj.asset : void 0;
164
+ const assetMeta = asset && isRecord(asset.meta) ? asset.meta : void 0;
165
+ const provider = stringOrUndefined(rawObj.provider) ?? stringOrUndefined(asset?.provider);
166
+ const isLocal = !provider || provider === "local";
167
+ const key = safeStorageKey(rawObj.storageKey) ?? safeStorageKey(meta?.storageKey) ?? safeStorageKey(asset?.storageKey) ?? safeStorageKey(assetMeta?.storageKey) ?? (isLocal ? safeStorageKey(asset?._ref) : void 0);
168
+ const raw = stringOrUndefined(rawObj.src) ?? stringOrUndefined(rawObj.url) ?? stringOrUndefined(asset?.url) ?? stringOrUndefined(asset?.src) ?? (key ? `${EMDASH_MEDIA_PREFIX}${key}` : void 0);
169
+ if (!raw || !isSafeMediaUrl(raw)) return null;
170
+ return emdashMediaPath(raw, hasLocalMediaProvenance(rawObj), allowedHosts) ?? raw.trim();
171
+ }
172
+ function resolveCandidates(href, definition, sourceWidth, sourceHeight, format) {
173
+ const byWidth = /* @__PURE__ */ new Map();
174
+ const quality = format === "avif" ? definition.avifQuality ?? DEFAULT_AVIF_QUALITY : void 0;
175
+ for (const candidate of [...definition.candidates].sort((a, b) => a.width - b.width)) {
176
+ const rendered = computeVariantDimensions(sourceWidth, sourceHeight, {
177
+ width: candidate.width,
178
+ fit: definition.fit,
179
+ ...candidate.height === void 0 ? {} : { height: candidate.height }
180
+ });
181
+ byWidth.set(rendered.width, {
182
+ url: buildEmDashTransformUrl({
183
+ href,
184
+ width: rendered.width,
185
+ ...candidate.height === void 0 ? {} : { height: rendered.height },
186
+ format,
187
+ quality
188
+ }),
189
+ width: rendered.width,
190
+ ...rendered.height === void 0 ? {} : { height: rendered.height }
191
+ });
192
+ }
193
+ return [...byWidth.values()].sort((a, b) => a.width - b.width);
194
+ }
195
+ function resolveVariant(href, definition, sourceWidth, sourceHeight) {
196
+ const avif = resolveCandidates(href, definition, sourceWidth, sourceHeight, "avif");
197
+ const png = resolveCandidates(href, definition, sourceWidth, sourceHeight, "png");
198
+ const largest = avif.at(-1);
199
+ return {
200
+ avif,
201
+ png,
202
+ ...largest?.width === void 0 ? {} : { width: largest.width },
203
+ ...largest?.height === void 0 ? {} : { height: largest.height },
204
+ sizes: definition.defaultSizes
205
+ };
206
+ }
207
+ function isMediaProps(value) {
208
+ return isRecord(value) && typeof value.url === "string" && value.url.trim().length > 0 && isSafeMediaUrl(value.url) && ("variants" in value || "originalUrl" in value);
209
+ }
210
+ function resolveMedia(input, roles = "all", catalog = DEFAULT_IMAGE_CATALOG, options) {
211
+ if (!input) return null;
212
+ const allowedHosts = options?.allowedHosts;
213
+ if (isMediaProps(input)) {
214
+ const normalizedUrl = emdashMediaPath(input.url, false, allowedHosts) ?? input.url.trim();
215
+ const normalizedInput = normalizedUrl === input.url ? input : {
216
+ ...input,
217
+ url: normalizedUrl
218
+ };
219
+ const roleNames = roles === "all" ? Object.keys(catalog.roles) : roles.filter((role) => Object.hasOwn(catalog.roles, role));
220
+ if (roleNames.every((role) => Boolean(normalizedInput.variants && Object.hasOwn(normalizedInput.variants, role)))) return normalizedInput;
221
+ if (!isTransformableEmDashPath(normalizedUrl) || !isTransformableImage({
222
+ mimeType: normalizedInput.mimeType,
223
+ filename: normalizedInput.filename,
224
+ url: normalizedUrl
225
+ })) return normalizedInput;
226
+ const nextVariants = { ...normalizedInput.variants ?? {} };
227
+ for (const role of roleNames) if (!Object.hasOwn(nextVariants, role)) {
228
+ const def = catalog.roles[role];
229
+ if (def) nextVariants[role] = resolveVariant(normalizedUrl, def, normalizedInput.width, normalizedInput.height);
230
+ }
231
+ return Object.keys(nextVariants).length > 0 ? {
232
+ ...normalizedInput,
233
+ variants: nextVariants
234
+ } : normalizedInput;
235
+ }
236
+ const rawObj = typeof input === "string" ? { src: input } : isRecord(input) ? input : null;
237
+ if (!rawObj) return null;
238
+ const meta = isRecord(rawObj.meta) ? rawObj.meta : void 0;
239
+ const asset = isRecord(rawObj.asset) ? rawObj.asset : void 0;
240
+ const assetMeta = asset && isRecord(asset.meta) ? asset.meta : void 0;
241
+ const url = extractMediaUrl(rawObj, allowedHosts);
242
+ if (!url) return null;
243
+ const alt = typeof rawObj.alt === "string" ? rawObj.alt : typeof asset?.alt === "string" ? asset.alt : void 0;
244
+ const width = positiveDimension(rawObj.width) ?? positiveDimension(asset?.width);
245
+ const height = positiveDimension(rawObj.height) ?? positiveDimension(asset?.height);
246
+ const mimeType = stringOrUndefined(rawObj.mimeType) ?? stringOrUndefined(asset?.mimeType) ?? stringOrUndefined(meta?.mimeType) ?? stringOrUndefined(assetMeta?.mimeType);
247
+ const filename = stringOrUndefined(rawObj.filename) ?? stringOrUndefined(asset?.filename) ?? stringOrUndefined(meta?.filename) ?? stringOrUndefined(assetMeta?.filename);
248
+ const media = {
249
+ url,
250
+ originalUrl: url,
251
+ ...alt !== void 0 ? { alt } : {},
252
+ ...width !== void 0 ? { width } : {},
253
+ ...height !== void 0 ? { height } : {},
254
+ ...mimeType !== void 0 ? { mimeType } : {},
255
+ ...filename !== void 0 ? { filename } : {}
256
+ };
257
+ if (isTransformableEmDashPath(url) && isTransformableImage({
258
+ mimeType,
259
+ filename,
260
+ url
261
+ })) {
262
+ const selectedRoles = Object.entries(catalog.roles).filter(([role]) => roles === "all" || roles.includes(role));
263
+ if (selectedRoles.length > 0) media.variants = Object.fromEntries(selectedRoles.map(([role, definition]) => [role, resolveVariant(url, definition, width, height)]));
264
+ }
265
+ return media;
266
+ }
267
+ function mediaSrc(media) {
268
+ return media?.originalUrl || media?.url || "";
269
+ }
270
+ function candidateSrcSet(candidates) {
271
+ return candidates.map(({ url, width }) => `${url} ${width}w`).join(", ");
272
+ }
273
+ function intrinsicDimensions(media, variants) {
274
+ if (!media.width && !media.height) return {};
275
+ if (media.width && !media.height) return { width: variants?.width !== void 0 ? Math.min(media.width, variants.width) : media.width };
276
+ if (!media.width && media.height) return { height: variants?.height !== void 0 ? Math.min(media.height, variants.height) : media.height };
277
+ const knownWidth = media.width;
278
+ const knownHeight = media.height;
279
+ if (variants?.width === void 0) return {
280
+ width: knownWidth,
281
+ height: knownHeight
282
+ };
283
+ if (variants.height !== void 0) return {
284
+ width: variants.width,
285
+ height: variants.height
286
+ };
287
+ return {
288
+ width: variants.width,
289
+ height: Math.max(1, Math.round(variants.width * knownHeight / knownWidth))
290
+ };
291
+ }
292
+ function resolveOverrideDimensions(resolved, baseDims, width, height) {
293
+ if (width !== void 0 && height !== void 0) return {
294
+ width,
295
+ height
296
+ };
297
+ const aspectRatio = resolved.width && resolved.height ? resolved.width / resolved.height : baseDims.width && baseDims.height ? baseDims.width / baseDims.height : void 0;
298
+ if (width !== void 0) return {
299
+ width,
300
+ ...aspectRatio ? { height: Math.max(1, Math.round(width / aspectRatio)) } : baseDims.height !== void 0 ? { height: baseDims.height } : {}
301
+ };
302
+ if (height !== void 0) return {
303
+ ...aspectRatio ? { width: Math.max(1, Math.round(height * aspectRatio)) } : baseDims.width !== void 0 ? { width: baseDims.width } : {},
304
+ height
305
+ };
306
+ return baseDims;
307
+ }
308
+ function resolvePictureRenderProps(opts) {
309
+ const { media, preset, catalog = DEFAULT_IMAGE_CATALOG, sizes, alt, width, height, fallbackFormat = "png", allowedHosts } = opts;
310
+ const activeCatalog = catalog;
311
+ const resolved = resolveMedia(media, preset ? [preset] : [], activeCatalog, { allowedHosts });
312
+ if (!resolved || !resolved.url) return null;
313
+ const variants = preset && resolved.variants && Object.hasOwn(resolved.variants, preset) ? resolved.variants[preset] : void 0;
314
+ const roleDef = preset && Object.hasOwn(activeCatalog.roles, preset) ? activeCatalog.roles[preset] : void 0;
315
+ const resolvedSizes = sizes ?? roleDef?.defaultSizes ?? variants?.sizes;
316
+ const pngCandidates = variants?.png ?? [];
317
+ const avifCandidates = variants?.avif ?? [];
318
+ const pngSrcSet = pngCandidates.length > 0 ? candidateSrcSet(pngCandidates) : void 0;
319
+ const avifSrcSet = avifCandidates.length > 0 ? candidateSrcSet(avifCandidates) : void 0;
320
+ const fallbackCandidates = fallbackFormat === "avif" ? avifCandidates : pngCandidates;
321
+ const fallbackSrcSet = fallbackFormat === "avif" ? avifSrcSet : pngSrcSet;
322
+ const fallbackSrc = fallbackCandidates.at(-1)?.url ?? mediaSrc(resolved);
323
+ const sources = [];
324
+ if (avifSrcSet) sources.push({
325
+ type: "image/avif",
326
+ srcset: avifSrcSet,
327
+ ...resolvedSizes ? { sizes: resolvedSizes } : {}
328
+ });
329
+ if (pngSrcSet) sources.push({
330
+ type: "image/png",
331
+ srcset: pngSrcSet,
332
+ ...resolvedSizes ? { sizes: resolvedSizes } : {}
333
+ });
334
+ const dims = resolveOverrideDimensions(resolved, intrinsicDimensions(resolved, variants), width, height);
335
+ const resolvedAlt = alt ?? resolved.alt ?? "";
336
+ return {
337
+ resolved,
338
+ resolvedSizes,
339
+ fallbackSrc,
340
+ pngSrcSet,
341
+ avifSrcSet,
342
+ alt: resolvedAlt,
343
+ width: dims.width,
344
+ height: dims.height,
345
+ sources,
346
+ img: {
347
+ src: fallbackSrc,
348
+ ...sources.length === 0 && fallbackSrcSet ? { srcset: fallbackSrcSet } : {},
349
+ ...sources.length === 0 && fallbackSrcSet && resolvedSizes ? { sizes: resolvedSizes } : {},
350
+ alt: resolvedAlt,
351
+ ...dims.width === void 0 ? {} : { width: dims.width },
352
+ ...dims.height === void 0 ? {} : { height: dims.height }
353
+ }
354
+ };
355
+ }
356
+ function queryParam(input, key) {
357
+ if (!isRecord(input) || !Object.hasOwn(input, key)) return void 0;
358
+ const raw = input[key];
359
+ if (typeof raw === "string") return stringOrUndefined(raw);
360
+ if (Array.isArray(raw) && typeof raw[0] === "string") return stringOrUndefined(raw[0]);
361
+ }
362
+ function parseWidthsParam(raw) {
363
+ if (raw === void 0) return {
364
+ ok: true,
365
+ widths: void 0
366
+ };
367
+ const parts = raw.split(",").map((part) => part.trim());
368
+ if (parts.length === 0 || parts.length > MAX_CUSTOM_WIDTHS) return {
369
+ ok: false,
370
+ error: `Invalid "widths" parameter: expected 1..${MAX_CUSTOM_WIDTHS} comma-separated integers.`
371
+ };
372
+ const widths = [];
373
+ for (const part of parts) {
374
+ const n = parsePositiveIntInRange(part, 1, MAX_IMAGE_DIMENSION);
375
+ if (n === null) return {
376
+ ok: false,
377
+ error: `Invalid width "${part}": expected integer between 1 and ${MAX_IMAGE_DIMENSION}.`
378
+ };
379
+ widths.push(n);
380
+ }
381
+ return {
382
+ ok: true,
383
+ widths: [...new Set(widths)].sort((a, b) => a - b)
384
+ };
385
+ }
386
+ /** Pure route handler logic shared by the sandboxed `src/plugin.ts` and in-process `createPlugin()`. */
387
+ function resolvePictureRouteQuery(input) {
388
+ const src = queryParam(input, "src") ?? queryParam(input, "href");
389
+ if (!src || !isSafeMediaUrl(src)) return {
390
+ ok: false,
391
+ error: "Invalid or missing \"src\"/\"href\" query parameter."
392
+ };
393
+ const parsedWidths = parseWidthsParam(queryParam(input, "widths"));
394
+ if (!parsedWidths.ok) return parsedWidths;
395
+ const rawWidth = queryParam(input, "width");
396
+ let width;
397
+ if (rawWidth !== void 0) {
398
+ const parsed = parsePositiveIntInRange(rawWidth, 1, MAX_IMAGE_DIMENSION);
399
+ if (parsed === null) return {
400
+ ok: false,
401
+ error: `Invalid "width" parameter: expected integer between 1 and ${MAX_IMAGE_DIMENSION}.`
402
+ };
403
+ width = parsed;
404
+ }
405
+ const rawHeight = queryParam(input, "height");
406
+ let height;
407
+ if (rawHeight !== void 0) {
408
+ const parsed = parsePositiveIntInRange(rawHeight, 1, MAX_IMAGE_DIMENSION);
409
+ if (parsed === null) return {
410
+ ok: false,
411
+ error: `Invalid "height" parameter: expected integer between 1 and ${MAX_IMAGE_DIMENSION}.`
412
+ };
413
+ height = parsed;
414
+ }
415
+ const rawQuality = queryParam(input, "quality");
416
+ let quality;
417
+ if (rawQuality !== void 0) {
418
+ const parsed = parsePositiveIntInRange(rawQuality, 1, 100);
419
+ if (parsed === null) return {
420
+ ok: false,
421
+ error: "Invalid \"quality\" parameter: expected integer between 1 and 100."
422
+ };
423
+ quality = parsed;
424
+ }
425
+ const sizes = queryParam(input, "sizes");
426
+ if (sizes && sizes.length > MAX_TEXT_PARAM_LENGTH) return {
427
+ ok: false,
428
+ error: "\"sizes\" parameter exceeds maximum length."
429
+ };
430
+ const alt = queryParam(input, "alt");
431
+ if (alt && alt.length > MAX_TEXT_PARAM_LENGTH) return {
432
+ ok: false,
433
+ error: "\"alt\" parameter exceeds maximum length."
434
+ };
435
+ const fitParam = queryParam(input, "fit");
436
+ if (fitParam !== void 0 && fitParam !== "contain" && fitParam !== "cover") return {
437
+ ok: false,
438
+ error: "Invalid \"fit\" parameter: expected \"contain\" or \"cover\"."
439
+ };
440
+ const fit = fitParam ?? "contain";
441
+ const fallbackParam = queryParam(input, "fallbackFormat");
442
+ if (fallbackParam !== void 0 && fallbackParam !== "png" && fallbackParam !== "avif") return {
443
+ ok: false,
444
+ error: "Invalid \"fallbackFormat\" parameter: expected \"png\" or \"avif\"."
445
+ };
446
+ const fallbackFormat = fallbackParam ?? "png";
447
+ const rawPreset = queryParam(input, "preset") ?? "card";
448
+ let catalog = DEFAULT_IMAGE_CATALOG;
449
+ let presetName = rawPreset;
450
+ if (parsedWidths.widths) {
451
+ presetName = "custom";
452
+ catalog = defineImageCatalog({
453
+ version: "1",
454
+ roles: { custom: {
455
+ fit,
456
+ defaultSizes: sizes ?? "100vw",
457
+ candidates: parsedWidths.widths.map((w) => ({ width: w })),
458
+ ...quality !== void 0 ? { avifQuality: quality } : {}
459
+ } }
460
+ });
461
+ } else {
462
+ const defaultCatalog = DEFAULT_IMAGE_CATALOG;
463
+ if (!Object.hasOwn(defaultCatalog.roles, rawPreset)) return {
464
+ ok: false,
465
+ error: `Unknown preset "${rawPreset}". Available presets: ${Object.keys(defaultCatalog.roles).join(", ")}.`
466
+ };
467
+ if (quality !== void 0) {
468
+ const baseRole = defaultCatalog.roles[rawPreset];
469
+ catalog = defineImageCatalog({
470
+ version: defaultCatalog.version,
471
+ roles: { [rawPreset]: {
472
+ ...baseRole,
473
+ avifQuality: quality
474
+ } }
475
+ });
476
+ }
477
+ }
478
+ const rendered = resolvePictureRenderProps({
479
+ media: {
480
+ src,
481
+ ...width !== void 0 ? { width } : {},
482
+ ...height !== void 0 ? { height } : {},
483
+ ...alt !== void 0 ? { alt } : {}
484
+ },
485
+ preset: presetName,
486
+ catalog,
487
+ sizes,
488
+ alt,
489
+ fallbackFormat
490
+ });
491
+ if (!rendered) return {
492
+ ok: false,
493
+ error: "Unable to resolve media input."
494
+ };
495
+ return {
496
+ ok: true,
497
+ preset: presetName,
498
+ media: rendered.resolved,
499
+ sources: rendered.sources,
500
+ img: rendered.img
501
+ };
502
+ }
503
+
504
+ //#endregion
505
+ export { EMDASH_IMAGE_ENDPOINT, EMDASH_MEDIA_PREFIX, MAX_CUSTOM_WIDTHS, MEDIA_FILE_PREFIX, PictureRouteError, buildEmDashTransformUrl, candidateSrcSet, intrinsicDimensions, isImmutableMediaRequest, isSafeMediaUrl, isTransformableEmDashPath, mediaSrc, resolveMedia, resolvePictureRenderProps, resolvePictureRouteQuery };
@@ -0,0 +1,31 @@
1
+ {
2
+ "$schema": "./node_modules/@emdash-cms/plugin-cli/schemas/emdash-plugin.schema.json",
3
+
4
+ "slug": "emdash-picture",
5
+ "publisher": "nodeart.io",
6
+
7
+ "license": "MIT",
8
+ "author": {
9
+ "name": "NodeArt",
10
+ "url": "https://nodeart.io",
11
+ "email": "hello@nodeart.io"
12
+ },
13
+ "security": {
14
+ "email": "hello@nodeart.io",
15
+ "url": "https://nodeart.io"
16
+ },
17
+
18
+ "name": "EmDash Picture",
19
+ "description": "Responsive <picture> image catalog, AVIF/PNG variant resolver, and Astro/Svelte components for EmDash CMS.",
20
+ "keywords": ["picture", "avif", "png", "responsive-images", "media"],
21
+ "repo": "https://github.com/NodeArt/emdash-plugin-picture",
22
+
23
+ "capabilities": [],
24
+ "allowedHosts": [],
25
+ "storage": {},
26
+ "release": {
27
+ "requires": {
28
+ "env:emdash": ">=1.3.0"
29
+ }
30
+ }
31
+ }