summaryrefslogtreecommitdiff
path: root/packages/integrations/cloudflare/src/entrypoints/image-service.ts
blob: d4cf8ff932cad1cf4d7f6ba3d647a604bea0cecc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import type { ExternalImageService } from 'astro';

import { joinPaths } from '@astrojs/internal-helpers/path';
import { baseService } from 'astro/assets';
import { isESMImportedImage, isRemoteAllowed } from '../utils/assets.js';

const service: ExternalImageService = {
	...baseService,
	getURL: (options, imageConfig) => {
		const resizingParams = ['onerror=redirect'];
		if (options.width) resizingParams.push(`width=${options.width}`);
		if (options.height) resizingParams.push(`height=${options.height}`);
		if (options.quality) resizingParams.push(`quality=${options.quality}`);
		if (options.fit) resizingParams.push(`fit=${options.fit}`);
		if (options.format) resizingParams.push(`format=${options.format}`);

		let imageSource = '';
		if (isESMImportedImage(options.src)) {
			imageSource = options.src.src;
		} else if (isRemoteAllowed(options.src, imageConfig)) {
			imageSource = options.src;
		} else {
			// If it's not an imported image, nor is it allowed using the current domains or remote patterns, we'll just return the original URL
			return options.src;
		}

		const imageEndpoint = joinPaths(
			// @ts-expect-error Can't recognise import.meta.env
			import.meta.env.BASE_URL,
			'/cdn-cgi/image',
			resizingParams.join(','),
			imageSource,
		);

		return imageEndpoint;
	},
};

export default service;