@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,906 @@
1
+ import {
2
+ computeVariantDimensions,
3
+ DEFAULT_IMAGE_CATALOG,
4
+ defineImageCatalog,
5
+ isTransformableImage,
6
+ MAX_IMAGE_DIMENSION,
7
+ type ImageCatalog,
8
+ type ImageOutputFormat,
9
+ type ImageRoleDefinition,
10
+ type ImageRoleName
11
+ } from './catalog.js';
12
+
13
+ export const EMDASH_MEDIA_PREFIX = '/_emdash/api/media/file/';
14
+ export const MEDIA_FILE_PREFIX = EMDASH_MEDIA_PREFIX;
15
+ export const EMDASH_IMAGE_ENDPOINT = '/_image';
16
+ export const MAX_CUSTOM_WIDTHS = 16;
17
+
18
+ const SAFE_STORAGE_KEY_RE = /^[A-Za-z0-9._-]+$/;
19
+ const POSITIVE_INT_RE = /^[1-9]\d*$/;
20
+ const ALLOWED_IMAGE_PARAMS = new Set(['href', 'w', 'h', 'q', 'f']);
21
+ const ALLOWED_TRANSFORM_FORMATS = new Set(['avif', 'webp', 'png', 'jpeg']);
22
+ const DEFAULT_AVIF_QUALITY = 76;
23
+ const MAX_URL_LENGTH = 2048;
24
+ const MAX_TEXT_PARAM_LENGTH = 512;
25
+
26
+ export type PictureFallbackFormat = ImageOutputFormat;
27
+
28
+ export interface MediaSourceCandidate {
29
+ url: string;
30
+ width: number;
31
+ height?: number;
32
+ }
33
+
34
+ export interface MediaVariantFormats {
35
+ avif: MediaSourceCandidate[];
36
+ png: MediaSourceCandidate[];
37
+ width?: number;
38
+ height?: number;
39
+ sizes?: string;
40
+ }
41
+
42
+ export type MediaVariant = MediaVariantFormats;
43
+
44
+ export interface MediaSource {
45
+ url: string;
46
+ width?: number;
47
+ height?: number;
48
+ alt?: string;
49
+ mimeType?: string;
50
+ filename?: string;
51
+ }
52
+
53
+ export interface MediaProps {
54
+ url: string;
55
+ originalUrl?: string;
56
+ variants?: Record<string, MediaVariantFormats>;
57
+ alt?: string;
58
+ width?: number;
59
+ height?: number;
60
+ mimeType?: string;
61
+ filename?: string;
62
+ }
63
+
64
+ export interface MediaRef {
65
+ id?: string | null;
66
+ mediaId?: string | null;
67
+ provider?: string | null;
68
+ storageKey?: string | null;
69
+ src?: string | null;
70
+ url?: string | null;
71
+ alt?: string | null;
72
+ width?: number | null;
73
+ height?: number | null;
74
+ mimeType?: string | null;
75
+ filename?: string | null;
76
+ asset?: {
77
+ _ref?: string | null;
78
+ url?: string | null;
79
+ src?: string | null;
80
+ storageKey?: string | null;
81
+ provider?: string | null;
82
+ meta?: Record<string, unknown> | null;
83
+ } | null;
84
+ meta?: Record<string, unknown> | null;
85
+ }
86
+
87
+ export type ResolveMediaInput = MediaProps | MediaRef | string | null | undefined;
88
+
89
+ export interface ResolveMediaOptions {
90
+ allowedHosts?: readonly string[];
91
+ }
92
+
93
+ export type MediaRoleScope<TCatalog extends ImageCatalog = ImageCatalog> =
94
+ | 'all'
95
+ | readonly ImageRoleName<TCatalog>[]
96
+ | readonly string[];
97
+
98
+ export interface PictureRenderSource {
99
+ type: 'image/avif' | 'image/png';
100
+ srcset: string;
101
+ sizes?: string;
102
+ }
103
+
104
+ export interface PictureRenderImg {
105
+ src: string;
106
+ srcset?: string;
107
+ sizes?: string;
108
+ alt: string;
109
+ width?: number;
110
+ height?: number;
111
+ }
112
+
113
+ export interface PictureRenderProps {
114
+ resolved: MediaProps;
115
+ resolvedSizes?: string;
116
+ fallbackSrc: string;
117
+ pngSrcSet?: string;
118
+ avifSrcSet?: string;
119
+ alt: string;
120
+ width?: number;
121
+ height?: number;
122
+ sources: PictureRenderSource[];
123
+ img: PictureRenderImg;
124
+ }
125
+
126
+ export interface ResolvePictureOptions<TCatalog extends ImageCatalog = ImageCatalog> {
127
+ media: unknown;
128
+ preset: (ImageRoleName<TCatalog> | (string & {})) | null;
129
+ catalog?: TCatalog;
130
+ sizes?: string;
131
+ alt?: string;
132
+ width?: number;
133
+ height?: number;
134
+ fallbackFormat?: PictureFallbackFormat;
135
+ allowedHosts?: readonly string[];
136
+ }
137
+
138
+ /**
139
+ * Error shaped to satisfy EmDash's duck-typed `isPluginRouteError()` guard
140
+ * without importing `emdash` inside the isolated sandbox runtime.
141
+ */
142
+ export class PictureRouteError extends Error {
143
+ readonly code: string;
144
+ readonly status: number;
145
+
146
+ constructor(message: string, code = 'BAD_REQUEST', status = 400) {
147
+ super(message);
148
+ this.name = 'PluginRouteError';
149
+ this.code = code;
150
+ this.status = status;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Build a `/_image` URL with parameters in EmDash's canonical order (`href`, `w`, `h`, `q`, `f`)
156
+ * so `@emdash-cms/cloudflare/image-endpoint` serves the transform directly without a 301 redirect.
157
+ * Quality is omitted for `png` so Cloudflare Images keeps PNG output lossless instead of PNG8.
158
+ */
159
+ export function buildEmDashTransformUrl(opts: {
160
+ href: string;
161
+ width: number;
162
+ height?: number;
163
+ format: ImageOutputFormat;
164
+ quality?: number;
165
+ }): string {
166
+ const params = new URLSearchParams();
167
+ params.set('href', opts.href);
168
+ params.set('w', String(opts.width));
169
+ if (opts.height !== undefined) {
170
+ params.set('h', String(opts.height));
171
+ }
172
+ if (opts.format !== 'png' && opts.quality !== undefined) {
173
+ params.set('q', String(opts.quality));
174
+ }
175
+ params.set('f', opts.format);
176
+ return `${EMDASH_IMAGE_ENDPOINT}?${params.toString()}`;
177
+ }
178
+
179
+ /** Check whether a media path points to a safe internal EmDash storage object. */
180
+ export function isTransformableEmDashPath(href: string): boolean {
181
+ if (!href.startsWith(EMDASH_MEDIA_PREFIX)) return false;
182
+ const storageKey = href.slice(EMDASH_MEDIA_PREFIX.length);
183
+ return storageKey.length > 0 && SAFE_STORAGE_KEY_RE.test(storageKey) && !storageKey.includes('..');
184
+ }
185
+
186
+ function parsePositiveIntInRange(raw: string | null, min: number, max: number): number | null {
187
+ if (raw === null || !POSITIVE_INT_RE.test(raw)) return null;
188
+ const n = Number(raw);
189
+ return Number.isSafeInteger(n) && n >= min && n <= max ? n : null;
190
+ }
191
+
192
+ /**
193
+ * EmDash library files (flat storage key without query/traversal) and canonical `/_image`
194
+ * transforms referencing local/same-origin library files are eligible for edge caching.
195
+ */
196
+ export function isImmutableMediaRequest(url: URL): boolean {
197
+ if (url.pathname.startsWith(EMDASH_MEDIA_PREFIX)) {
198
+ return url.search === '' && isTransformableEmDashPath(url.pathname);
199
+ }
200
+ if (url.pathname !== EMDASH_IMAGE_ENDPOINT) return false;
201
+
202
+ for (const key of url.searchParams.keys()) {
203
+ if (!ALLOWED_IMAGE_PARAMS.has(key) || url.searchParams.getAll(key).length !== 1) {
204
+ return false;
205
+ }
206
+ }
207
+
208
+ const href = url.searchParams.get('href');
209
+ if (!href) return false;
210
+
211
+ const w = parsePositiveIntInRange(url.searchParams.get('w'), 1, MAX_IMAGE_DIMENSION);
212
+ if (w === null) return false;
213
+
214
+ const hRaw = url.searchParams.get('h');
215
+ if (hRaw !== null && parsePositiveIntInRange(hRaw, 1, MAX_IMAGE_DIMENSION) === null) {
216
+ return false;
217
+ }
218
+
219
+ const qRaw = url.searchParams.get('q');
220
+ if (qRaw !== null && parsePositiveIntInRange(qRaw, 1, 100) === null) {
221
+ return false;
222
+ }
223
+
224
+ const fRaw = url.searchParams.get('f');
225
+ if (fRaw !== null && !ALLOWED_TRANSFORM_FORMATS.has(fRaw)) {
226
+ return false;
227
+ }
228
+
229
+ if (isTransformableEmDashPath(href)) return true;
230
+
231
+ try {
232
+ const parsed = new URL(href);
233
+ return (
234
+ parsed.origin === url.origin &&
235
+ parsed.search === '' &&
236
+ parsed.hash === '' &&
237
+ isTransformableEmDashPath(parsed.pathname)
238
+ );
239
+ } catch {
240
+ return false;
241
+ }
242
+ }
243
+
244
+ function isRecord(value: unknown): value is Record<string, unknown> {
245
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
246
+ }
247
+
248
+ function stringOrUndefined(value: unknown): string | undefined {
249
+ if (typeof value !== 'string') return undefined;
250
+ const trimmed = value.trim();
251
+ return trimmed.length > 0 ? trimmed : undefined;
252
+ }
253
+
254
+ function positiveDimension(value: unknown): number | undefined {
255
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
256
+ ? Math.round(value)
257
+ : undefined;
258
+ }
259
+
260
+ export function isSafeMediaUrl(raw: string): boolean {
261
+ const trimmed = raw.trim();
262
+ if (!trimmed || trimmed.length > MAX_URL_LENGTH) return false;
263
+ if (trimmed.startsWith('//')) return false;
264
+ if (trimmed.startsWith('/')) return true;
265
+ try {
266
+ const parsed = new URL(trimmed);
267
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
268
+ } catch {
269
+ return false;
270
+ }
271
+ }
272
+
273
+ function isAllowedHost(hostname: string, allowedHosts?: readonly string[]): boolean {
274
+ if (!allowedHosts || allowedHosts.length === 0) return false;
275
+ const normalized = hostname.toLowerCase();
276
+ return allowedHosts.some((pattern) => {
277
+ const p = pattern.trim().toLowerCase();
278
+ if (!p) return false;
279
+ if (p.startsWith('*.')) {
280
+ const suffix = p.slice(1);
281
+ return normalized.endsWith(suffix) && normalized.length > suffix.length;
282
+ }
283
+ return normalized === p;
284
+ });
285
+ }
286
+
287
+ function emdashMediaPath(
288
+ raw: string,
289
+ hasLocalProvenance: boolean,
290
+ allowedHosts?: readonly string[]
291
+ ): string | null {
292
+ const trimmed = raw.trim();
293
+ if (!isSafeMediaUrl(trimmed)) return null;
294
+
295
+ if (trimmed.startsWith(EMDASH_MEDIA_PREFIX)) {
296
+ try {
297
+ const normalized = new URL(trimmed, 'http://localhost');
298
+ if (isTransformableEmDashPath(normalized.pathname)) {
299
+ return normalized.pathname;
300
+ }
301
+ } catch {
302
+ return null;
303
+ }
304
+ return null;
305
+ }
306
+
307
+ if (trimmed.startsWith('/')) return null;
308
+
309
+ try {
310
+ const url = new URL(trimmed);
311
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
312
+ if (
313
+ isTransformableEmDashPath(url.pathname) &&
314
+ (hasLocalProvenance || isAllowedHost(url.hostname, allowedHosts))
315
+ ) {
316
+ return url.pathname;
317
+ }
318
+ } catch {
319
+ return null;
320
+ }
321
+ return null;
322
+ }
323
+
324
+ function safeStorageKey(value: unknown): string | undefined {
325
+ const str = stringOrUndefined(value);
326
+ if (!str) return undefined;
327
+ return SAFE_STORAGE_KEY_RE.test(str) && !str.includes('..') ? str : undefined;
328
+ }
329
+
330
+ function hasLocalMediaProvenance(rawObj: Record<string, unknown>): boolean {
331
+ const provider = stringOrUndefined(rawObj.provider);
332
+ if (provider && provider !== 'local') return false;
333
+ const asset = isRecord(rawObj.asset) ? rawObj.asset : undefined;
334
+ const assetProvider = stringOrUndefined(asset?.provider);
335
+ if (assetProvider && assetProvider !== 'local') return false;
336
+
337
+ return Boolean(
338
+ stringOrUndefined(rawObj.id) ??
339
+ stringOrUndefined(rawObj.mediaId) ??
340
+ stringOrUndefined(rawObj.storageKey) ??
341
+ stringOrUndefined(asset?._ref) ??
342
+ stringOrUndefined(asset?.storageKey)
343
+ );
344
+ }
345
+
346
+ function extractMediaUrl(
347
+ rawObj: Record<string, unknown>,
348
+ allowedHosts?: readonly string[]
349
+ ): string | null {
350
+ const meta = isRecord(rawObj.meta) ? rawObj.meta : undefined;
351
+ const asset = isRecord(rawObj.asset) ? rawObj.asset : undefined;
352
+ const assetMeta = asset && isRecord(asset.meta) ? asset.meta : undefined;
353
+
354
+ const provider = stringOrUndefined(rawObj.provider) ?? stringOrUndefined(asset?.provider);
355
+ const isLocal = !provider || provider === 'local';
356
+
357
+ const key =
358
+ safeStorageKey(rawObj.storageKey) ??
359
+ safeStorageKey(meta?.storageKey) ??
360
+ safeStorageKey(asset?.storageKey) ??
361
+ safeStorageKey(assetMeta?.storageKey) ??
362
+ (isLocal ? safeStorageKey(asset?._ref) : undefined);
363
+
364
+ const raw =
365
+ stringOrUndefined(rawObj.src) ??
366
+ stringOrUndefined(rawObj.url) ??
367
+ stringOrUndefined(asset?.url) ??
368
+ stringOrUndefined(asset?.src) ??
369
+ (key ? `${EMDASH_MEDIA_PREFIX}${key}` : undefined);
370
+
371
+ if (!raw || !isSafeMediaUrl(raw)) return null;
372
+ return emdashMediaPath(raw, hasLocalMediaProvenance(rawObj), allowedHosts) ?? raw.trim();
373
+ }
374
+
375
+ function resolveCandidates(
376
+ href: string,
377
+ definition: ImageRoleDefinition,
378
+ sourceWidth: number | undefined,
379
+ sourceHeight: number | undefined,
380
+ format: ImageOutputFormat
381
+ ): MediaSourceCandidate[] {
382
+ const byWidth = new Map<number, MediaSourceCandidate>();
383
+ const quality = format === 'avif' ? (definition.avifQuality ?? DEFAULT_AVIF_QUALITY) : undefined;
384
+
385
+ for (const candidate of [...definition.candidates].sort((a, b) => a.width - b.width)) {
386
+ const rendered = computeVariantDimensions(sourceWidth, sourceHeight, {
387
+ width: candidate.width,
388
+ fit: definition.fit,
389
+ ...(candidate.height === undefined ? {} : { height: candidate.height })
390
+ });
391
+
392
+ byWidth.set(rendered.width, {
393
+ url: buildEmDashTransformUrl({
394
+ href,
395
+ width: rendered.width,
396
+ ...(candidate.height === undefined ? {} : { height: rendered.height }),
397
+ format,
398
+ quality
399
+ }),
400
+ width: rendered.width,
401
+ ...(rendered.height === undefined ? {} : { height: rendered.height })
402
+ });
403
+ }
404
+
405
+ return [...byWidth.values()].sort((a, b) => a.width - b.width);
406
+ }
407
+
408
+ function resolveVariant(
409
+ href: string,
410
+ definition: ImageRoleDefinition,
411
+ sourceWidth: number | undefined,
412
+ sourceHeight: number | undefined
413
+ ): MediaVariantFormats {
414
+ const avif = resolveCandidates(href, definition, sourceWidth, sourceHeight, 'avif');
415
+ const png = resolveCandidates(href, definition, sourceWidth, sourceHeight, 'png');
416
+ const largest = avif.at(-1);
417
+
418
+ return {
419
+ avif,
420
+ png,
421
+ ...(largest?.width === undefined ? {} : { width: largest.width }),
422
+ ...(largest?.height === undefined ? {} : { height: largest.height }),
423
+ sizes: definition.defaultSizes
424
+ };
425
+ }
426
+
427
+ function isMediaProps(value: unknown): value is MediaProps {
428
+ return (
429
+ isRecord(value) &&
430
+ typeof value.url === 'string' &&
431
+ value.url.trim().length > 0 &&
432
+ isSafeMediaUrl(value.url) &&
433
+ ('variants' in value || 'originalUrl' in value)
434
+ );
435
+ }
436
+
437
+ /**
438
+ * Resolve any EmDash media ref, PortableText image payload, URL string, or pre-resolved `MediaProps`
439
+ * into a serializable `MediaProps` containing AVIF and PNG srcset variants for the requested roles.
440
+ */
441
+ export function resolveMedia<TCatalog extends ImageCatalog = typeof DEFAULT_IMAGE_CATALOG>(
442
+ input: unknown,
443
+ roles?: MediaRoleScope<TCatalog>,
444
+ catalog?: TCatalog,
445
+ options?: ResolveMediaOptions
446
+ ): MediaProps | null;
447
+ export function resolveMedia(
448
+ input: unknown,
449
+ roles: readonly string[] | 'all' = 'all',
450
+ catalog: ImageCatalog = DEFAULT_IMAGE_CATALOG,
451
+ options?: ResolveMediaOptions
452
+ ): MediaProps | null {
453
+ if (!input) return null;
454
+ const allowedHosts = options?.allowedHosts;
455
+
456
+ if (isMediaProps(input)) {
457
+ const normalizedUrl = emdashMediaPath(input.url, false, allowedHosts) ?? input.url.trim();
458
+ const normalizedInput =
459
+ normalizedUrl === input.url ? input : { ...input, url: normalizedUrl };
460
+
461
+ const roleNames =
462
+ roles === 'all'
463
+ ? Object.keys(catalog.roles)
464
+ : (roles as readonly string[]).filter((role) => Object.hasOwn(catalog.roles, role));
465
+ const hasAllRequested = roleNames.every((role) =>
466
+ Boolean(normalizedInput.variants && Object.hasOwn(normalizedInput.variants, role))
467
+ );
468
+ if (hasAllRequested) return normalizedInput;
469
+
470
+ if (
471
+ !isTransformableEmDashPath(normalizedUrl) ||
472
+ !isTransformableImage({
473
+ mimeType: normalizedInput.mimeType,
474
+ filename: normalizedInput.filename,
475
+ url: normalizedUrl
476
+ })
477
+ ) {
478
+ return normalizedInput;
479
+ }
480
+
481
+ const nextVariants: Record<string, MediaVariantFormats> = {
482
+ ...(normalizedInput.variants ?? {})
483
+ };
484
+ for (const role of roleNames) {
485
+ if (!Object.hasOwn(nextVariants, role)) {
486
+ const def = catalog.roles[role];
487
+ if (def) {
488
+ nextVariants[role] = resolveVariant(
489
+ normalizedUrl,
490
+ def,
491
+ normalizedInput.width,
492
+ normalizedInput.height
493
+ );
494
+ }
495
+ }
496
+ }
497
+ return Object.keys(nextVariants).length > 0
498
+ ? { ...normalizedInput, variants: nextVariants }
499
+ : normalizedInput;
500
+ }
501
+
502
+ const rawObj =
503
+ typeof input === 'string'
504
+ ? ({ src: input } satisfies Record<string, unknown>)
505
+ : isRecord(input)
506
+ ? input
507
+ : null;
508
+ if (!rawObj) return null;
509
+
510
+ const meta = isRecord(rawObj.meta) ? rawObj.meta : undefined;
511
+ const asset = isRecord(rawObj.asset) ? rawObj.asset : undefined;
512
+ const assetMeta = asset && isRecord(asset.meta) ? asset.meta : undefined;
513
+
514
+ const url = extractMediaUrl(rawObj, allowedHosts);
515
+ if (!url) return null;
516
+
517
+ const alt =
518
+ typeof rawObj.alt === 'string'
519
+ ? rawObj.alt
520
+ : typeof asset?.alt === 'string'
521
+ ? asset.alt
522
+ : undefined;
523
+ const width = positiveDimension(rawObj.width) ?? positiveDimension(asset?.width);
524
+ const height = positiveDimension(rawObj.height) ?? positiveDimension(asset?.height);
525
+ const mimeType =
526
+ stringOrUndefined(rawObj.mimeType) ??
527
+ stringOrUndefined(asset?.mimeType) ??
528
+ stringOrUndefined(meta?.mimeType) ??
529
+ stringOrUndefined(assetMeta?.mimeType);
530
+ const filename =
531
+ stringOrUndefined(rawObj.filename) ??
532
+ stringOrUndefined(asset?.filename) ??
533
+ stringOrUndefined(meta?.filename) ??
534
+ stringOrUndefined(assetMeta?.filename);
535
+
536
+ const media: MediaProps = {
537
+ url,
538
+ originalUrl: url,
539
+ ...(alt !== undefined ? { alt } : {}),
540
+ ...(width !== undefined ? { width } : {}),
541
+ ...(height !== undefined ? { height } : {}),
542
+ ...(mimeType !== undefined ? { mimeType } : {}),
543
+ ...(filename !== undefined ? { filename } : {})
544
+ };
545
+
546
+ if (isTransformableEmDashPath(url) && isTransformableImage({ mimeType, filename, url })) {
547
+ const selectedRoles = Object.entries(catalog.roles).filter(
548
+ ([role]) => roles === 'all' || (roles as readonly string[]).includes(role)
549
+ );
550
+ if (selectedRoles.length > 0) {
551
+ media.variants = Object.fromEntries(
552
+ selectedRoles.map(([role, definition]) => [
553
+ role,
554
+ resolveVariant(url, definition, width, height)
555
+ ])
556
+ );
557
+ }
558
+ }
559
+
560
+ return media;
561
+ }
562
+
563
+ export function mediaSrc(media: MediaProps | null | undefined): string {
564
+ return media?.originalUrl || media?.url || '';
565
+ }
566
+
567
+ export function candidateSrcSet(candidates: MediaSourceCandidate[]): string {
568
+ return candidates.map(({ url, width }) => `${url} ${width}w`).join(', ');
569
+ }
570
+
571
+ export function intrinsicDimensions(
572
+ media: MediaProps,
573
+ variants: MediaVariantFormats | undefined
574
+ ): { width?: number; height?: number } {
575
+ if (!media.width && !media.height) {
576
+ return {};
577
+ }
578
+ if (media.width && !media.height) {
579
+ return {
580
+ width: variants?.width !== undefined ? Math.min(media.width, variants.width) : media.width
581
+ };
582
+ }
583
+ if (!media.width && media.height) {
584
+ return {
585
+ height: variants?.height !== undefined ? Math.min(media.height, variants.height) : media.height
586
+ };
587
+ }
588
+
589
+ const knownWidth = media.width as number;
590
+ const knownHeight = media.height as number;
591
+ if (variants?.width === undefined) {
592
+ return { width: knownWidth, height: knownHeight };
593
+ }
594
+ if (variants.height !== undefined) {
595
+ return { width: variants.width, height: variants.height };
596
+ }
597
+ return {
598
+ width: variants.width,
599
+ height: Math.max(1, Math.round((variants.width * knownHeight) / knownWidth))
600
+ };
601
+ }
602
+
603
+ function resolveOverrideDimensions(
604
+ resolved: MediaProps,
605
+ baseDims: { width?: number; height?: number },
606
+ width: number | undefined,
607
+ height: number | undefined
608
+ ): { width?: number; height?: number } {
609
+ if (width !== undefined && height !== undefined) {
610
+ return { width, height };
611
+ }
612
+ const aspectRatio =
613
+ resolved.width && resolved.height
614
+ ? resolved.width / resolved.height
615
+ : baseDims.width && baseDims.height
616
+ ? baseDims.width / baseDims.height
617
+ : undefined;
618
+
619
+ if (width !== undefined) {
620
+ return {
621
+ width,
622
+ ...(aspectRatio
623
+ ? { height: Math.max(1, Math.round(width / aspectRatio)) }
624
+ : baseDims.height !== undefined
625
+ ? { height: baseDims.height }
626
+ : {})
627
+ };
628
+ }
629
+ if (height !== undefined) {
630
+ return {
631
+ ...(aspectRatio
632
+ ? { width: Math.max(1, Math.round(height * aspectRatio)) }
633
+ : baseDims.width !== undefined
634
+ ? { width: baseDims.width }
635
+ : {}),
636
+ height
637
+ };
638
+ }
639
+ return baseDims;
640
+ }
641
+
642
+ /** Shared view-model resolver for `<MediaPicture.astro>`, `<MediaPicture.svelte>`, and plugin routes. */
643
+ export function resolvePictureRenderProps<
644
+ TCatalog extends ImageCatalog = typeof DEFAULT_IMAGE_CATALOG
645
+ >(opts: ResolvePictureOptions<TCatalog>): PictureRenderProps | null;
646
+ export function resolvePictureRenderProps(
647
+ opts: ResolvePictureOptions<ImageCatalog>
648
+ ): PictureRenderProps | null {
649
+ const {
650
+ media,
651
+ preset,
652
+ catalog = DEFAULT_IMAGE_CATALOG,
653
+ sizes,
654
+ alt,
655
+ width,
656
+ height,
657
+ fallbackFormat = 'png',
658
+ allowedHosts
659
+ } = opts;
660
+ const activeCatalog: ImageCatalog = catalog;
661
+ const resolved = resolveMedia(media, preset ? [preset] : [], activeCatalog, { allowedHosts });
662
+ if (!resolved || !resolved.url) return null;
663
+
664
+ const variants =
665
+ preset && resolved.variants && Object.hasOwn(resolved.variants, preset)
666
+ ? resolved.variants[preset]
667
+ : undefined;
668
+ const roleDef =
669
+ preset && Object.hasOwn(activeCatalog.roles, preset) ? activeCatalog.roles[preset] : undefined;
670
+ const resolvedSizes = sizes ?? roleDef?.defaultSizes ?? variants?.sizes;
671
+ const pngCandidates = variants?.png ?? [];
672
+ const avifCandidates = variants?.avif ?? [];
673
+ const pngSrcSet = pngCandidates.length > 0 ? candidateSrcSet(pngCandidates) : undefined;
674
+ const avifSrcSet = avifCandidates.length > 0 ? candidateSrcSet(avifCandidates) : undefined;
675
+
676
+ const fallbackCandidates = fallbackFormat === 'avif' ? avifCandidates : pngCandidates;
677
+ const fallbackSrcSet = fallbackFormat === 'avif' ? avifSrcSet : pngSrcSet;
678
+ const fallbackSrc = fallbackCandidates.at(-1)?.url ?? mediaSrc(resolved);
679
+
680
+ const sources: PictureRenderSource[] = [];
681
+ if (avifSrcSet) {
682
+ sources.push({
683
+ type: 'image/avif',
684
+ srcset: avifSrcSet,
685
+ ...(resolvedSizes ? { sizes: resolvedSizes } : {})
686
+ });
687
+ }
688
+ if (pngSrcSet) {
689
+ sources.push({
690
+ type: 'image/png',
691
+ srcset: pngSrcSet,
692
+ ...(resolvedSizes ? { sizes: resolvedSizes } : {})
693
+ });
694
+ }
695
+
696
+ const baseDims = intrinsicDimensions(resolved, variants);
697
+ const dims = resolveOverrideDimensions(resolved, baseDims, width, height);
698
+ const resolvedAlt = alt ?? resolved.alt ?? '';
699
+
700
+ return {
701
+ resolved,
702
+ resolvedSizes,
703
+ fallbackSrc,
704
+ pngSrcSet,
705
+ avifSrcSet,
706
+ alt: resolvedAlt,
707
+ width: dims.width,
708
+ height: dims.height,
709
+ sources,
710
+ img: {
711
+ src: fallbackSrc,
712
+ ...(sources.length === 0 && fallbackSrcSet ? { srcset: fallbackSrcSet } : {}),
713
+ ...(sources.length === 0 && fallbackSrcSet && resolvedSizes
714
+ ? { sizes: resolvedSizes }
715
+ : {}),
716
+ alt: resolvedAlt,
717
+ ...(dims.width === undefined ? {} : { width: dims.width }),
718
+ ...(dims.height === undefined ? {} : { height: dims.height })
719
+ }
720
+ };
721
+ }
722
+
723
+ function queryParam(input: unknown, key: string): string | undefined {
724
+ if (!isRecord(input) || !Object.hasOwn(input, key)) return undefined;
725
+ const raw = input[key];
726
+ if (typeof raw === 'string') return stringOrUndefined(raw);
727
+ if (Array.isArray(raw) && typeof raw[0] === 'string') return stringOrUndefined(raw[0]);
728
+ return undefined;
729
+ }
730
+
731
+ function parseWidthsParam(
732
+ raw: string | undefined
733
+ ): { ok: true; widths?: number[] } | { ok: false; error: string } {
734
+ if (raw === undefined) return { ok: true, widths: undefined };
735
+ const parts = raw.split(',').map((part) => part.trim());
736
+ if (parts.length === 0 || parts.length > MAX_CUSTOM_WIDTHS) {
737
+ return {
738
+ ok: false,
739
+ error: `Invalid "widths" parameter: expected 1..${MAX_CUSTOM_WIDTHS} comma-separated integers.`
740
+ };
741
+ }
742
+
743
+ const widths: number[] = [];
744
+ for (const part of parts) {
745
+ const n = parsePositiveIntInRange(part, 1, MAX_IMAGE_DIMENSION);
746
+ if (n === null) {
747
+ return {
748
+ ok: false,
749
+ error: `Invalid width "${part}": expected integer between 1 and ${MAX_IMAGE_DIMENSION}.`
750
+ };
751
+ }
752
+ widths.push(n);
753
+ }
754
+
755
+ return { ok: true, widths: [...new Set(widths)].sort((a, b) => a - b) };
756
+ }
757
+
758
+ export type ResolvePictureRouteResult =
759
+ | {
760
+ ok: true;
761
+ preset: string;
762
+ media: MediaProps;
763
+ sources: PictureRenderSource[];
764
+ img: PictureRenderImg;
765
+ }
766
+ | {
767
+ ok: false;
768
+ error: string;
769
+ };
770
+
771
+ /** Pure route handler logic shared by the sandboxed `src/plugin.ts` and in-process `createPlugin()`. */
772
+ export function resolvePictureRouteQuery(input: unknown): ResolvePictureRouteResult {
773
+ const src = queryParam(input, 'src') ?? queryParam(input, 'href');
774
+ if (!src || !isSafeMediaUrl(src)) {
775
+ return { ok: false, error: 'Invalid or missing "src"/"href" query parameter.' };
776
+ }
777
+
778
+ const rawWidths = queryParam(input, 'widths');
779
+ const parsedWidths = parseWidthsParam(rawWidths);
780
+ if (!parsedWidths.ok) {
781
+ return parsedWidths;
782
+ }
783
+
784
+ const rawWidth = queryParam(input, 'width');
785
+ let width: number | undefined;
786
+ if (rawWidth !== undefined) {
787
+ const parsed = parsePositiveIntInRange(rawWidth, 1, MAX_IMAGE_DIMENSION);
788
+ if (parsed === null) {
789
+ return {
790
+ ok: false,
791
+ error: `Invalid "width" parameter: expected integer between 1 and ${MAX_IMAGE_DIMENSION}.`
792
+ };
793
+ }
794
+ width = parsed;
795
+ }
796
+
797
+ const rawHeight = queryParam(input, 'height');
798
+ let height: number | undefined;
799
+ if (rawHeight !== undefined) {
800
+ const parsed = parsePositiveIntInRange(rawHeight, 1, MAX_IMAGE_DIMENSION);
801
+ if (parsed === null) {
802
+ return {
803
+ ok: false,
804
+ error: `Invalid "height" parameter: expected integer between 1 and ${MAX_IMAGE_DIMENSION}.`
805
+ };
806
+ }
807
+ height = parsed;
808
+ }
809
+
810
+ const rawQuality = queryParam(input, 'quality');
811
+ let quality: number | undefined;
812
+ if (rawQuality !== undefined) {
813
+ const parsed = parsePositiveIntInRange(rawQuality, 1, 100);
814
+ if (parsed === null) {
815
+ return { ok: false, error: 'Invalid "quality" parameter: expected integer between 1 and 100.' };
816
+ }
817
+ quality = parsed;
818
+ }
819
+
820
+ const sizes = queryParam(input, 'sizes');
821
+ if (sizes && sizes.length > MAX_TEXT_PARAM_LENGTH) {
822
+ return { ok: false, error: '"sizes" parameter exceeds maximum length.' };
823
+ }
824
+
825
+ const alt = queryParam(input, 'alt');
826
+ if (alt && alt.length > MAX_TEXT_PARAM_LENGTH) {
827
+ return { ok: false, error: '"alt" parameter exceeds maximum length.' };
828
+ }
829
+
830
+ const fitParam = queryParam(input, 'fit');
831
+ if (fitParam !== undefined && fitParam !== 'contain' && fitParam !== 'cover') {
832
+ return { ok: false, error: 'Invalid "fit" parameter: expected "contain" or "cover".' };
833
+ }
834
+ const fit = fitParam ?? 'contain';
835
+
836
+ const fallbackParam = queryParam(input, 'fallbackFormat');
837
+ if (fallbackParam !== undefined && fallbackParam !== 'png' && fallbackParam !== 'avif') {
838
+ return { ok: false, error: 'Invalid "fallbackFormat" parameter: expected "png" or "avif".' };
839
+ }
840
+ const fallbackFormat: PictureFallbackFormat = fallbackParam ?? 'png';
841
+
842
+ const rawPreset = queryParam(input, 'preset') ?? 'card';
843
+ let catalog: ImageCatalog = DEFAULT_IMAGE_CATALOG;
844
+ let presetName = rawPreset;
845
+
846
+ if (parsedWidths.widths) {
847
+ presetName = 'custom';
848
+ catalog = defineImageCatalog({
849
+ version: '1',
850
+ roles: {
851
+ custom: {
852
+ fit,
853
+ defaultSizes: sizes ?? '100vw',
854
+ candidates: parsedWidths.widths.map((w) => ({ width: w })),
855
+ ...(quality !== undefined ? { avifQuality: quality } : {})
856
+ }
857
+ }
858
+ });
859
+ } else {
860
+ const defaultCatalog: ImageCatalog = DEFAULT_IMAGE_CATALOG;
861
+ if (!Object.hasOwn(defaultCatalog.roles, rawPreset)) {
862
+ return {
863
+ ok: false,
864
+ error: `Unknown preset "${rawPreset}". Available presets: ${Object.keys(defaultCatalog.roles).join(', ')}.`
865
+ };
866
+ }
867
+ if (quality !== undefined) {
868
+ const baseRole = defaultCatalog.roles[rawPreset];
869
+ catalog = defineImageCatalog({
870
+ version: defaultCatalog.version,
871
+ roles: {
872
+ [rawPreset]: {
873
+ ...baseRole,
874
+ avifQuality: quality
875
+ }
876
+ }
877
+ });
878
+ }
879
+ }
880
+
881
+ const rendered = resolvePictureRenderProps({
882
+ media: {
883
+ src,
884
+ ...(width !== undefined ? { width } : {}),
885
+ ...(height !== undefined ? { height } : {}),
886
+ ...(alt !== undefined ? { alt } : {})
887
+ },
888
+ preset: presetName,
889
+ catalog,
890
+ sizes,
891
+ alt,
892
+ fallbackFormat
893
+ });
894
+
895
+ if (!rendered) {
896
+ return { ok: false, error: 'Unable to resolve media input.' };
897
+ }
898
+
899
+ return {
900
+ ok: true,
901
+ preset: presetName,
902
+ media: rendered.resolved,
903
+ sources: rendered.sources,
904
+ img: rendered.img
905
+ };
906
+ }