summaryrefslogtreecommitdiff
path: root/packages/integrations/image
diff options
context:
space:
mode:
Diffstat (limited to 'packages/integrations/image')
-rw-r--r--packages/integrations/image/CHANGELOG.md7
-rw-r--r--packages/integrations/image/package.json2
-rw-r--r--packages/integrations/image/src/endpoints/dev.ts6
-rw-r--r--packages/integrations/image/src/endpoints/prod.ts12
-rw-r--r--packages/integrations/image/src/index.ts78
-rw-r--r--packages/integrations/image/src/loaders/sharp.ts44
-rw-r--r--packages/integrations/image/src/metadata.ts4
-rw-r--r--packages/integrations/image/src/types.ts37
-rw-r--r--packages/integrations/image/src/utils.ts6
-rw-r--r--packages/integrations/image/src/vite-plugin-astro-image.ts11
-rw-r--r--packages/integrations/image/test/image-ssg.test.js14
-rw-r--r--packages/integrations/image/test/sharp.test.js4
12 files changed, 132 insertions, 93 deletions
diff --git a/packages/integrations/image/CHANGELOG.md b/packages/integrations/image/CHANGELOG.md
new file mode 100644
index 000000000..ce9fc333f
--- /dev/null
+++ b/packages/integrations/image/CHANGELOG.md
@@ -0,0 +1,7 @@
+# @astrojs/image
+
+## 0.0.2
+
+### Patch Changes
+
+- [#3788](https://github.com/withastro/astro/pull/3788) [`f4943e0f`](https://github.com/withastro/astro/commit/f4943e0fbced044f0ba4435cb41d77b67c98e69f) Thanks [@tony-sull](https://github.com/tony-sull)! - Initial release! 🎉
diff --git a/packages/integrations/image/package.json b/packages/integrations/image/package.json
index 2626f951d..adf4f9e1c 100644
--- a/packages/integrations/image/package.json
+++ b/packages/integrations/image/package.json
@@ -1,7 +1,7 @@
{
"name": "@astrojs/image",
"description": "Load and transform images in your Astro site.",
- "version": "0.0.1",
+ "version": "0.0.2",
"type": "module",
"types": "./dist/types.d.ts",
"author": "withastro",
diff --git a/packages/integrations/image/src/endpoints/dev.ts b/packages/integrations/image/src/endpoints/dev.ts
index 9b1c2eff2..4d0ed365a 100644
--- a/packages/integrations/image/src/endpoints/dev.ts
+++ b/packages/integrations/image/src/endpoints/dev.ts
@@ -24,10 +24,10 @@ export const get: APIRoute = async ({ request }) => {
return new Response(data, {
status: 200,
headers: {
- 'Content-Type': lookup(format) || ''
- }
+ 'Content-Type': lookup(format) || '',
+ },
});
} catch (err: unknown) {
return new Response(`Server Error: ${err}`, { status: 500 });
}
-}
+};
diff --git a/packages/integrations/image/src/endpoints/prod.ts b/packages/integrations/image/src/endpoints/prod.ts
index 65a8202a0..1ff56df48 100644
--- a/packages/integrations/image/src/endpoints/prod.ts
+++ b/packages/integrations/image/src/endpoints/prod.ts
@@ -15,7 +15,9 @@ export const get: APIRoute = async ({ request }) => {
}
// TODO: Can we lean on fs to load local images in SSR prod builds?
- const href = isRemoteImage(transform.src) ? new URL(transform.src) : new URL(transform.src, url.origin);
+ const href = isRemoteImage(transform.src)
+ ? new URL(transform.src)
+ : new URL(transform.src, url.origin);
const inputBuffer = await loadRemoteImage(href.toString());
@@ -30,11 +32,11 @@ export const get: APIRoute = async ({ request }) => {
headers: {
'Content-Type': lookup(format) || '',
'Cache-Control': 'public, max-age=31536000',
- 'ETag': etag(inputBuffer),
- 'Date': (new Date()).toUTCString(),
- }
+ ETag: etag(inputBuffer),
+ Date: new Date().toUTCString(),
+ },
});
} catch (err: unknown) {
return new Response(`Server Error: ${err}`, { status: 500 });
}
-}
+};
diff --git a/packages/integrations/image/src/index.ts b/packages/integrations/image/src/index.ts
index 7f1e1b456..43cf8fd1e 100644
--- a/packages/integrations/image/src/index.ts
+++ b/packages/integrations/image/src/index.ts
@@ -2,10 +2,21 @@ import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import slash from 'slash';
-import { ensureDir, isRemoteImage, loadLocalImage, loadRemoteImage, propsToFilename } from './utils.js';
+import {
+ ensureDir,
+ isRemoteImage,
+ loadLocalImage,
+ loadRemoteImage,
+ propsToFilename,
+} from './utils.js';
import { createPlugin } from './vite-plugin-astro-image.js';
import type { AstroConfig, AstroIntegration } from 'astro';
-import type { ImageAttributes, IntegrationOptions, SSRImageService, TransformOptions } from './types';
+import type {
+ ImageAttributes,
+ IntegrationOptions,
+ SSRImageService,
+ TransformOptions,
+} from './types';
const PKG_NAME = '@astrojs/image';
const ROUTE_PATTERN = '/_image';
@@ -13,15 +24,18 @@ const OUTPUT_DIR = '/_image';
/**
* Gets the HTML attributes required to build an `<img />` for the transformed image.
- *
+ *
* @param loader @type {ImageService} The image service used for transforming images.
* @param transform @type {TransformOptions} The transformations requested for the optimized image.
* @returns @type {ImageAttributes} The HTML attributes to be included on the built `<img />` element.
*/
-export async function getImage(loader: SSRImageService, transform: TransformOptions): Promise<ImageAttributes> {
+export async function getImage(
+ loader: SSRImageService,
+ transform: TransformOptions
+): Promise<ImageAttributes> {
(globalThis as any).loader = loader;
- const attributes = await loader.getImageAttributes(transform);
+ const attributes = await loader.getImageAttributes(transform);
// For SSR services, build URLs for the injected route
if (typeof loader.transform === 'function') {
@@ -32,14 +46,15 @@ export async function getImage(loader: SSRImageService, transform: TransformOpti
(globalThis as any)?.addStaticImage(transform);
}
- const src = globalThis && (globalThis as any).filenameFormat
- ? (globalThis as any).filenameFormat(transform, searchParams)
- : `${ROUTE_PATTERN}?${searchParams.toString()}`;
+ const src =
+ globalThis && (globalThis as any).filenameFormat
+ ? (globalThis as any).filenameFormat(transform, searchParams)
+ : `${ROUTE_PATTERN}?${searchParams.toString()}`;
- return {
- ...attributes,
- src: slash(src), // Windows compat
- }
+ return {
+ ...attributes,
+ src: slash(src), // Windows compat
+ };
}
// For hosted services, return the <img /> attributes as-is
@@ -49,7 +64,7 @@ export async function getImage(loader: SSRImageService, transform: TransformOpti
const createIntegration = (options: IntegrationOptions = {}): AstroIntegration => {
const resolvedOptions = {
serviceEntryPoint: '@astrojs/image/sharp',
- ...options
+ ...options,
};
// During SSG builds, this is used to track all transformed images required.
@@ -59,10 +74,8 @@ const createIntegration = (options: IntegrationOptions = {}): AstroIntegration =
function getViteConfiguration() {
return {
- plugins: [
- createPlugin(_config, resolvedOptions)
- ]
- }
+ plugins: [createPlugin(_config, resolvedOptions)],
+ };
}
return {
@@ -80,23 +93,31 @@ const createIntegration = (options: IntegrationOptions = {}): AstroIntegration =
// Added to globalThis to share the same map in Node and Vite
(globalThis as any).addStaticImage = (transform: TransformOptions) => {
staticImages.set(propsToFilename(transform), transform);
- }
+ };
// TODO: Add support for custom, user-provided filename format functions
- (globalThis as any).filenameFormat = (transform: TransformOptions, searchParams: URLSearchParams) => {
+ (globalThis as any).filenameFormat = (
+ transform: TransformOptions,
+ searchParams: URLSearchParams
+ ) => {
if (mode === 'ssg') {
return isRemoteImage(transform.src)
? path.join(OUTPUT_DIR, path.basename(propsToFilename(transform)))
- : path.join(OUTPUT_DIR, path.dirname(transform.src), path.basename(propsToFilename(transform)));
+ : path.join(
+ OUTPUT_DIR,
+ path.dirname(transform.src),
+ path.basename(propsToFilename(transform))
+ );
} else {
return `${ROUTE_PATTERN}?${searchParams.toString()}`;
}
- }
+ };
if (mode === 'ssr') {
injectRoute({
pattern: ROUTE_PATTERN,
- entryPoint: command === 'dev' ? '@astrojs/image/endpoints/dev' : '@astrojs/image/endpoints/prod'
+ entryPoint:
+ command === 'dev' ? '@astrojs/image/endpoints/dev' : '@astrojs/image/endpoints/prod',
});
}
},
@@ -111,7 +132,10 @@ const createIntegration = (options: IntegrationOptions = {}): AstroIntegration =
// try to load the remote image
inputBuffer = await loadRemoteImage(transform.src);
- const outputFileURL = new URL(path.join('./', OUTPUT_DIR, path.basename(filename)), dir);
+ const outputFileURL = new URL(
+ path.join('./', OUTPUT_DIR, path.basename(filename)),
+ dir
+ );
outputFile = fileURLToPath(outputFileURL);
} else {
const inputFileURL = new URL(`.${transform.src}`, _config.srcDir);
@@ -131,9 +155,9 @@ const createIntegration = (options: IntegrationOptions = {}): AstroIntegration =
ensureDir(path.dirname(outputFile));
await fs.writeFile(outputFile, data);
}
- }
- }
- }
-}
+ },
+ },
+ };
+};
export default createIntegration;
diff --git a/packages/integrations/image/src/loaders/sharp.ts b/packages/integrations/image/src/loaders/sharp.ts
index 5c79c7338..d5d3da8f0 100644
--- a/packages/integrations/image/src/loaders/sharp.ts
+++ b/packages/integrations/image/src/loaders/sharp.ts
@@ -2,42 +2,42 @@ import sharp from 'sharp';
import { isAspectRatioString, isOutputFormat } from '../utils.js';
import type { TransformOptions, OutputFormat, SSRImageService } from '../types';
-class SharpService implements SSRImageService {
+class SharpService implements SSRImageService {
async getImageAttributes(transform: TransformOptions) {
const { width, height, src, format, quality, aspectRatio, ...rest } = transform;
-
+
return {
...rest,
width: width,
- height: height
- }
+ height: height,
+ };
}
serializeTransform(transform: TransformOptions) {
const searchParams = new URLSearchParams();
-
+
if (transform.quality) {
searchParams.append('q', transform.quality.toString());
}
-
+
if (transform.format) {
searchParams.append('f', transform.format);
}
-
+
if (transform.width) {
searchParams.append('w', transform.width.toString());
}
-
+
if (transform.height) {
searchParams.append('h', transform.height.toString());
}
-
+
if (transform.aspectRatio) {
searchParams.append('ar', transform.aspectRatio.toString());
}
-
+
searchParams.append('href', transform.src);
-
+
return { searchParams };
}
@@ -45,54 +45,54 @@ class SharpService implements SSRImageService {
if (!searchParams.has('href')) {
return undefined;
}
-
+
let transform: TransformOptions = { src: searchParams.get('href')! };
if (searchParams.has('q')) {
transform.quality = parseInt(searchParams.get('q')!);
}
-
+
if (searchParams.has('f')) {
const format = searchParams.get('f')!;
if (isOutputFormat(format)) {
transform.format = format;
}
}
-
+
if (searchParams.has('w')) {
transform.width = parseInt(searchParams.get('w')!);
}
-
+
if (searchParams.has('h')) {
transform.height = parseInt(searchParams.get('h')!);
}
-
+
if (searchParams.has('ar')) {
const ratio = searchParams.get('ar')!;
-
+
if (isAspectRatioString(ratio)) {
transform.aspectRatio = ratio;
} else {
transform.aspectRatio = parseFloat(ratio);
}
}
-
+
return transform;
}
async transform(inputBuffer: Buffer, transform: TransformOptions) {
const sharpImage = sharp(inputBuffer, { failOnError: false });
-
+
if (transform.width || transform.height) {
sharpImage.resize(transform.width, transform.height);
}
-
+
if (transform.format) {
sharpImage.toFormat(transform.format, { quality: transform.quality });
}
-
+
const { data, info } = await sharpImage.toBuffer({ resolveWithObject: true });
-
+
return {
data,
format: info.format as OutputFormat,
diff --git a/packages/integrations/image/src/metadata.ts b/packages/integrations/image/src/metadata.ts
index 3d344ad96..020d9461f 100644
--- a/packages/integrations/image/src/metadata.ts
+++ b/packages/integrations/image/src/metadata.ts
@@ -15,6 +15,6 @@ export async function metadata(src: string): Promise<ImageMetadata | undefined>
src,
width,
height,
- format: type as InputFormat
- }
+ format: type as InputFormat,
+ };
}
diff --git a/packages/integrations/image/src/types.ts b/packages/integrations/image/src/types.ts
index b161c15ed..1292169b2 100644
--- a/packages/integrations/image/src/types.ts
+++ b/packages/integrations/image/src/types.ts
@@ -1,7 +1,7 @@
export * from './index';
export type InputFormat =
- | 'heic'
+ | 'heic'
| 'heif'
| 'avif'
| 'jpeg'
@@ -11,15 +11,11 @@ export type InputFormat =
| 'webp'
| 'gif';
-export type OutputFormat =
- | 'avif'
- | 'jpeg'
- | 'png'
- | 'webp';
+export type OutputFormat = 'avif' | 'jpeg' | 'png' | 'webp';
/**
* Converts a set of image transforms to the filename to use when building for static.
- *
+ *
* This is only used for static production builds and ignored when an SSR adapter is used,
* or in `astro dev` for static builds.
*/
@@ -38,20 +34,20 @@ export interface IntegrationOptions {
export interface TransformOptions {
/**
* Source for the original image file.
- *
+ *
* For images in your project's repository, use the `src` relative to the `public` directory.
* For remote images, provide the full URL.
*/
src: string;
/**
* The output format to be used in the optimized image.
- *
+ *
* @default undefined The original image format will be used.
- */
+ */
format?: OutputFormat;
/**
* The compression quality used during optimization.
- *
+ *
* @default undefined Allows the image service to determine defaults.
*/
quality?: number;
@@ -68,7 +64,7 @@ export interface TransformOptions {
/**
* The desired aspect ratio of the output image. Combine with either `width` or `height`
* to automatically calculate and crop the other dimension.
- *
+ *
* @example 1.777 - numbers can be used for computed ratios, useful for doing `{width/height}`
* @example "16:9" - strings can be used in the format of `{ratioWidth}:{ratioHeight}`.
*/
@@ -84,21 +80,22 @@ export interface HostedImageService<T extends TransformOptions = TransformOption
getImageAttributes(transform: T): Promise<ImageAttributes>;
}
-export interface SSRImageService<T extends TransformOptions = TransformOptions> extends HostedImageService<T> {
+export interface SSRImageService<T extends TransformOptions = TransformOptions>
+ extends HostedImageService<T> {
/**
* Gets the HTML attributes needed for the server rendered `<img />` element.
*/
- getImageAttributes(transform: T): Promise<Exclude<ImageAttributes, 'src'>>;
+ getImageAttributes(transform: T): Promise<Exclude<ImageAttributes, 'src'>>;
/**
* Serializes image transformation properties to URLSearchParams, used to build
* the final `src` that points to the self-hosted SSR endpoint.
- *
+ *
* @param transform @type {TransformOptions} defining the requested image transformation.
*/
serializeTransform(transform: T): { searchParams: URLSearchParams };
/**
* The reverse of `serializeTransform(transform)`, this parsed the @type {TransformOptions} back out of a given URL.
- *
+ *
* @param searchParams @type {URLSearchParams}
* @returns @type {TransformOptions} used to generate the URL, or undefined if the URL isn't valid.
*/
@@ -106,14 +103,16 @@ export interface SSRImageService<T extends TransformOptions = TransformOptions>
/**
* Performs the image transformations on the input image and returns both the binary data and
* final image format of the optimized image.
- *
+ *
* @param inputBuffer Binary buffer containing the original image.
* @param transform @type {TransformOptions} defining the requested transformations.
*/
- transform(inputBuffer: Buffer, transform: T): Promise<{ data: Buffer, format: OutputFormat }>;
+ transform(inputBuffer: Buffer, transform: T): Promise<{ data: Buffer; format: OutputFormat }>;
}
-export type ImageService<T extends TransformOptions = TransformOptions> = HostedImageService<T> | SSRImageService<T>;
+export type ImageService<T extends TransformOptions = TransformOptions> =
+ | HostedImageService<T>
+ | SSRImageService<T>;
export interface ImageMetadata {
src: string;
diff --git a/packages/integrations/image/src/utils.ts b/packages/integrations/image/src/utils.ts
index 48249aff1..95e0fb2a1 100644
--- a/packages/integrations/image/src/utils.ts
+++ b/packages/integrations/image/src/utils.ts
@@ -2,7 +2,7 @@ import fs from 'fs';
import path from 'path';
import type { OutputFormat, TransformOptions } from './types';
- export function isOutputFormat(value: string): value is OutputFormat {
+export function isOutputFormat(value: string): value is OutputFormat {
return ['avif', 'jpeg', 'png', 'webp'].includes(value);
}
@@ -41,9 +41,7 @@ export async function loadRemoteImage(src: string) {
}
export async function loadImage(src: string) {
- return isRemoteImage(src)
- ? await loadRemoteImage(src)
- : await loadLocalImage(src);
+ return isRemoteImage(src) ? await loadRemoteImage(src) : await loadLocalImage(src);
}
export function propsToFilename({ src, width, height, format }: TransformOptions) {
diff --git a/packages/integrations/image/src/vite-plugin-astro-image.ts b/packages/integrations/image/src/vite-plugin-astro-image.ts
index 852e9c58f..e2fcfffcb 100644
--- a/packages/integrations/image/src/vite-plugin-astro-image.ts
+++ b/packages/integrations/image/src/vite-plugin-astro-image.ts
@@ -8,7 +8,8 @@ import type { AstroConfig } from 'astro';
import type { IntegrationOptions } from './types';
export function createPlugin(config: AstroConfig, options: Required<IntegrationOptions>): Plugin {
- const filter = (id: string) => /^(?!\/_image?).*.(heic|heif|avif|jpeg|jpg|png|tiff|webp|gif)$/.test(id);
+ const filter = (id: string) =>
+ /^(?!\/_image?).*.(heic|heif|avif|jpeg|jpg|png|tiff|webp|gif)$/.test(id);
const virtualModuleId = 'virtual:image-loader';
@@ -43,10 +44,12 @@ export function createPlugin(config: AstroConfig, options: Required<IntegrationO
},
async load(id) {
// only claim image ESM imports
- if (!filter(id)) { return null; }
+ if (!filter(id)) {
+ return null;
+ }
const meta = await metadata(id);
-
+
const fileUrl = pathToFileURL(id);
const src = resolvedConfig.isProduction
? fileUrl.pathname.replace(config.srcDir.pathname, '/')
@@ -66,6 +69,6 @@ export function createPlugin(config: AstroConfig, options: Required<IntegrationO
}
return `export default ${JSON.stringify(output)}`;
- }
+ },
};
}
diff --git a/packages/integrations/image/test/image-ssg.test.js b/packages/integrations/image/test/image-ssg.test.js
index b6c9a38f9..254a3bfae 100644
--- a/packages/integrations/image/test/image-ssg.test.js
+++ b/packages/integrations/image/test/image-ssg.test.js
@@ -56,7 +56,11 @@ describe('SSG images', function () {
});
it('built the optimized image', () => {
- verifyImage('_image/googlelogo_color_272x92dp_544x184.webp', { width: 544, height: 184, type: 'webp' });
+ verifyImage('_image/googlelogo_color_272x92dp_544x184.webp', {
+ width: 544,
+ height: 184,
+ type: 'webp',
+ });
});
});
});
@@ -95,9 +99,9 @@ describe('SSG images', function () {
it('returns the optimized image', async () => {
const image = $('#social-jpg');
-
+
const res = await fixture.fetch(image.attr('src'));
-
+
expect(res.status).to.equal(200);
expect(res.headers.get('Content-Type')).to.equal('image/jpeg');
@@ -119,7 +123,9 @@ describe('SSG images', function () {
expect(searchParams.get('f')).to.equal('webp');
expect(searchParams.get('w')).to.equal('544');
expect(searchParams.get('h')).to.equal('184');
- expect(searchParams.get('href')).to.equal('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png');
+ expect(searchParams.get('href')).to.equal(
+ 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'
+ );
});
});
});
diff --git a/packages/integrations/image/test/sharp.test.js b/packages/integrations/image/test/sharp.test.js
index 04b63ed7b..82e332e3d 100644
--- a/packages/integrations/image/test/sharp.test.js
+++ b/packages/integrations/image/test/sharp.test.js
@@ -13,7 +13,7 @@ describe('Sharp service', () => {
['height', { src, height: 414 }],
['width & height', { src, height: 400, width: 200 }],
['aspect ratio string', { src, aspectRatio: '16:9' }],
- ['aspect ratio float', { src, aspectRatio: 1.7 }]
+ ['aspect ratio float', { src, aspectRatio: 1.7 }],
].forEach(([description, props]) => {
it(description, async () => {
const { searchParams } = await sharp.serializeTransform(props);
@@ -48,7 +48,7 @@ describe('Sharp service', () => {
['height', `h=414&href=${href}`, { src, height: 414 }],
['width & height', `w=200&h=400&href=${href}`, { src, height: 400, width: 200 }],
['aspect ratio string', `ar=16:9&href=${href}`, { src, aspectRatio: '16:9' }],
- ['aspect ratio float', `ar=1.7&href=${href}`, { src, aspectRatio: 1.7 }]
+ ['aspect ratio float', `ar=1.7&href=${href}`, { src, aspectRatio: 1.7 }],
].forEach(([description, params, expected]) => {
it(description, async () => {
const searchParams = new URLSearchParams(params);