@all-the.rest/astro-image-cdn 0.1.1 → 0.2.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.
- package/README.md +35 -2
- package/package.json +1 -1
- package/src/index.d.ts +34 -1
- package/src/index.js +4 -1
- package/src/processor.js +278 -29
- package/src/service.js +5 -2
package/README.md
CHANGED
|
@@ -65,13 +65,16 @@ With this option, `astro dev` installs the image service and local asset route,
|
|
|
65
65
|
| `sources` | `["src"]` | Project-root-relative directories from which imported local images may be requested. No startup pre-scan is performed. |
|
|
66
66
|
| `outputDir` | `".imagedist"` | Persistent generated variants, relative to the project root. |
|
|
67
67
|
| `cacheDir` | `".astro-image-cdn"` | Private manifest and incremental fingerprints, relative to the project root. |
|
|
68
|
-
| `widths` | `[256, 640, 828, 1080, 1200, 1920, 2048]` | Requested widths
|
|
68
|
+
| `widths` | `[256, 640, 828, 1080, 1200, 1920, 2048]` | Requested widths. Values above the source width are omitted. |
|
|
69
69
|
| `formats` | `["avif", "webp"]` | Output encodings generated for every selected width. Supported: `avif`, `webp`, `jpeg`, `png`. |
|
|
70
70
|
| `quality` | `75` | Sharp encoder quality from 1 to 100. |
|
|
71
|
+
| `includeSourceFormat` | `true` | Also generate each supported source-native format. Set `false` for only the formats listed in `formats`. |
|
|
72
|
+
| `includeNativeWidth` | `true` | Also generate the source's native width when it is not already in `widths`. |
|
|
73
|
+
| `autoRotate` | `true` | Apply EXIF orientation before resizing. Set `false` to preserve the source's stored pixel orientation and dimensions. |
|
|
71
74
|
| `concurrency` | `4` | Maximum number of source images processed at once. |
|
|
72
75
|
| `devOnly` | `false` | Install the integration only for `astro dev`; other Astro commands retain their configured image service. |
|
|
73
76
|
|
|
74
|
-
Configured formats are generated alongside the source's native raster format
|
|
77
|
+
Configured formats are generated alongside the source's native raster format when `includeSourceFormat` is enabled (the default). With it disabled, only `formats` are generated. Astro 7.4's default output for raster images is WebP, independent of the order in `formats`; include `webp` or request a configured format explicitly. If the default or an explicit format is unavailable, the service reports which format needs to be added. `widths` are emitted only when they are no wider than the source. The native width is additionally emitted only when `includeNativeWidth` is enabled; if it is already listed in `widths`, it is naturally generated once. For a requested width between generated sizes, the service selects the next available variant, capped at the source's native width.
|
|
75
78
|
|
|
76
79
|
Animated or multi-page sources are rejected rather than silently flattened to a still frame, including GIF, WebP, AVIF sequences, and multi-page TIFF. Convert them to a static image or exclude them from the configured source directories.
|
|
77
80
|
|
|
@@ -91,6 +94,36 @@ Image identity is the project-relative file path; no frontmatter, YAML sidecars,
|
|
|
91
94
|
- Old content-addressed files are intentionally retained. Request-driven Astro processing preserves unrelated manifest entries; an explicit standalone `processImages()` run reconciles the manifest with the files found under its source directories. Neither mode deletes historical output files.
|
|
92
95
|
- Astro's `dist/` remains Astro-owned; this package does not copy into, clean, or deploy it.
|
|
93
96
|
|
|
97
|
+
### Adopting existing variants
|
|
98
|
+
|
|
99
|
+
Migration scripts can use `adoptImageVariants()` to copy already-encoded files into the package's current fingerprint-based paths without running Sharp's encoders. Pass the current processor options and only technical source/output information; the helper does not read application metadata, YAML, or slugs:
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
import { createHash } from "node:crypto";
|
|
103
|
+
import { readFile } from "node:fs/promises";
|
|
104
|
+
import { adoptImageVariants } from "@all-the.rest/astro-image-cdn";
|
|
105
|
+
|
|
106
|
+
const sourcePath = "src/images/photo.jpg";
|
|
107
|
+
const sourceHash = createHash("sha256").update(await readFile(sourcePath)).digest("hex");
|
|
108
|
+
await adoptImageVariants({
|
|
109
|
+
rootDir: process.cwd(),
|
|
110
|
+
widths: [256, 640, 828, 1080, 1200, 1920, 2048],
|
|
111
|
+
formats: ["webp"],
|
|
112
|
+
includeSourceFormat: false,
|
|
113
|
+
includeNativeWidth: false,
|
|
114
|
+
autoRotate: false,
|
|
115
|
+
}, {
|
|
116
|
+
sourcePath,
|
|
117
|
+
sourceHash,
|
|
118
|
+
variants: [
|
|
119
|
+
{ path: ".legacy-images/photo_256.webp", width: 256, format: "webp" },
|
|
120
|
+
{ path: ".legacy-images/photo_640.webp", width: 640, format: "webp" },
|
|
121
|
+
],
|
|
122
|
+
});
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The helper verifies the current source hash and each required output's actual format and dimensions before writing. It requires the complete variant set implied by the options; extras (such as legacy native-width files) are ignored. Outputs are atomically written under `outputDir`, and the private manifest/cache are updated only after validation. Repeated calls reuse matching targets; failures leave the prior manifest and existing outputs untouched, and old source variants are never removed. Supply the source hash recorded when the existing outputs were produced so a changed source cannot accidentally adopt stale files.
|
|
126
|
+
|
|
94
127
|
## API
|
|
95
128
|
|
|
96
129
|
The default export is the Astro integration. Its image processor runs only when a native Astro image API requests an imported local image. The exported `processImages()` API is a separate, explicit bulk operation for standalone build scripts; calling it scans every supported image under `sources`:
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -7,12 +7,18 @@ interface AstroImageCdnBaseOptions {
|
|
|
7
7
|
outputDir?: string;
|
|
8
8
|
/** Incremental state directory, relative to the project root. Defaults to ".astro-image-cdn". */
|
|
9
9
|
cacheDir?: string;
|
|
10
|
-
/**
|
|
10
|
+
/** Configured widths; values above the source width are omitted. */
|
|
11
11
|
widths?: number[];
|
|
12
12
|
/** Output formats generated for every source. Defaults to ["avif", "webp"]. */
|
|
13
13
|
formats?: Array<"avif" | "webp" | "jpeg" | "png">;
|
|
14
14
|
/** Encoder quality from 1 to 100. Defaults to 75. */
|
|
15
15
|
quality?: number;
|
|
16
|
+
/** Also generate a supported source-native format. Defaults to true. */
|
|
17
|
+
includeSourceFormat?: boolean;
|
|
18
|
+
/** Also generate the source's native width when it is not configured. Defaults to true. */
|
|
19
|
+
includeNativeWidth?: boolean;
|
|
20
|
+
/** Apply EXIF orientation before resizing. Defaults to true. */
|
|
21
|
+
autoRotate?: boolean;
|
|
16
22
|
/** Maximum number of images processed concurrently. Defaults to 4. */
|
|
17
23
|
concurrency?: number;
|
|
18
24
|
}
|
|
@@ -47,6 +53,33 @@ export interface ProcessImagesResult {
|
|
|
47
53
|
legacyPublicManifestPath?: string;
|
|
48
54
|
}
|
|
49
55
|
|
|
56
|
+
export interface AdoptImageVariant {
|
|
57
|
+
/** Existing encoded output path; relative paths are resolved from rootDir. */
|
|
58
|
+
path: string;
|
|
59
|
+
width: number;
|
|
60
|
+
format: "avif" | "webp" | "jpeg" | "png" | "svg";
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface AdoptImageVariantsInput {
|
|
64
|
+
/** Existing source path, relative to rootDir or absolute. */
|
|
65
|
+
sourcePath: string;
|
|
66
|
+
/** SHA-256 of the source bytes when the existing variants were produced. */
|
|
67
|
+
sourceHash: string;
|
|
68
|
+
/** Existing variants to adopt; every output required by the options must be supplied. */
|
|
69
|
+
variants: AdoptImageVariant[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface AdoptImageVariantsResult {
|
|
73
|
+
fingerprint: string;
|
|
74
|
+
adopted: number;
|
|
75
|
+
reused: number;
|
|
76
|
+
manifestPath: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
50
79
|
export default function astroImageCdn(options: AstroImageCdnOptions): AstroIntegration;
|
|
51
80
|
|
|
52
81
|
export declare function processImages(options: ProcessImagesOptions): Promise<ProcessImagesResult>;
|
|
82
|
+
export declare function adoptImageVariants(
|
|
83
|
+
options: ProcessImagesOptions,
|
|
84
|
+
input: AdoptImageVariantsInput,
|
|
85
|
+
): Promise<AdoptImageVariantsResult>;
|
package/src/index.js
CHANGED
|
@@ -111,6 +111,9 @@ export default function astroImageCdn(options) {
|
|
|
111
111
|
widths: options.widths ?? DEFAULT_IMAGE_WIDTHS,
|
|
112
112
|
formats: options.formats ?? DEFAULT_IMAGE_FORMATS,
|
|
113
113
|
quality: options.quality ?? 75,
|
|
114
|
+
includeSourceFormat: options.includeSourceFormat ?? true,
|
|
115
|
+
includeNativeWidth: options.includeNativeWidth ?? true,
|
|
116
|
+
autoRotate: options.autoRotate ?? true,
|
|
114
117
|
concurrency: options.concurrency ?? 4,
|
|
115
118
|
dangerouslyProcessSVG: config.image?.dangerouslyProcessSVG ?? false,
|
|
116
119
|
devMode,
|
|
@@ -150,4 +153,4 @@ export default function astroImageCdn(options) {
|
|
|
150
153
|
};
|
|
151
154
|
}
|
|
152
155
|
|
|
153
|
-
export { processImages } from "./processor.js";
|
|
156
|
+
export { adoptImageVariants, processImages } from "./processor.js";
|
package/src/processor.js
CHANGED
|
@@ -119,6 +119,9 @@ function resolveOptions(options) {
|
|
|
119
119
|
const quality = options.quality ?? 75;
|
|
120
120
|
const concurrency = options.concurrency ?? 4;
|
|
121
121
|
const dangerouslyProcessSVG = options.dangerouslyProcessSVG ?? false;
|
|
122
|
+
const includeSourceFormat = options.includeSourceFormat ?? true;
|
|
123
|
+
const includeNativeWidth = options.includeNativeWidth ?? true;
|
|
124
|
+
const autoRotate = options.autoRotate ?? true;
|
|
122
125
|
|
|
123
126
|
for (const width of widths) validatePositiveInteger(width, "widths");
|
|
124
127
|
for (const format of formats) {
|
|
@@ -131,10 +134,27 @@ function resolveOptions(options) {
|
|
|
131
134
|
if (typeof dangerouslyProcessSVG !== "boolean") {
|
|
132
135
|
throw new TypeError("dangerouslyProcessSVG must be a boolean");
|
|
133
136
|
}
|
|
137
|
+
for (const [label, value] of Object.entries({ includeSourceFormat, includeNativeWidth, autoRotate })) {
|
|
138
|
+
if (typeof value !== "boolean") throw new TypeError(`${label} must be a boolean`);
|
|
139
|
+
}
|
|
134
140
|
if (quality > 100) throw new RangeError("quality must be between 1 and 100");
|
|
135
141
|
if (formats.length === 0) throw new TypeError("formats must contain at least one image format");
|
|
136
142
|
|
|
137
|
-
return {
|
|
143
|
+
return {
|
|
144
|
+
rootDir,
|
|
145
|
+
sourceDirectories,
|
|
146
|
+
publicDir,
|
|
147
|
+
outputDir,
|
|
148
|
+
cacheDir,
|
|
149
|
+
widths,
|
|
150
|
+
formats,
|
|
151
|
+
quality,
|
|
152
|
+
concurrency,
|
|
153
|
+
dangerouslyProcessSVG,
|
|
154
|
+
includeSourceFormat,
|
|
155
|
+
includeNativeWidth,
|
|
156
|
+
autoRotate,
|
|
157
|
+
};
|
|
138
158
|
}
|
|
139
159
|
|
|
140
160
|
async function walk(directory, output, excludedPaths) {
|
|
@@ -215,7 +235,7 @@ function hasAvifSequenceBrand(buffer) {
|
|
|
215
235
|
return false;
|
|
216
236
|
}
|
|
217
237
|
|
|
218
|
-
async function imageMetadata(buffer, filePath) {
|
|
238
|
+
async function imageMetadata(buffer, filePath, autoRotate = true) {
|
|
219
239
|
if (hasAvifSequenceBrand(buffer)) {
|
|
220
240
|
throw new Error(`Animated or multi-page image sources are not supported: ${filePath} is an AVIF image sequence.`);
|
|
221
241
|
}
|
|
@@ -233,7 +253,7 @@ async function imageMetadata(buffer, filePath) {
|
|
|
233
253
|
if ((metadata.pages ?? 1) > 1) {
|
|
234
254
|
throw new Error(`Animated or multi-page image sources are not supported: ${filePath} (${metadata.mediaType ?? metadata.format}, ${metadata.pages} pages).`);
|
|
235
255
|
}
|
|
236
|
-
const rotated = metadata.orientation >= 5 && metadata.orientation <= 8;
|
|
256
|
+
const rotated = autoRotate && metadata.orientation >= 5 && metadata.orientation <= 8;
|
|
237
257
|
return {
|
|
238
258
|
width: rotated ? metadata.height : metadata.width,
|
|
239
259
|
height: rotated ? metadata.width : metadata.height,
|
|
@@ -245,6 +265,42 @@ function getVariants(width, formats) {
|
|
|
245
265
|
return formats.map((format) => ({ width, format }));
|
|
246
266
|
}
|
|
247
267
|
|
|
268
|
+
function pipelineSettings(options) {
|
|
269
|
+
return JSON.stringify({
|
|
270
|
+
widths: options.widths,
|
|
271
|
+
formats: options.formats,
|
|
272
|
+
quality: options.quality,
|
|
273
|
+
transformVersion: TRANSFORM_VERSION,
|
|
274
|
+
sharpVersion: sharp.versions.sharp,
|
|
275
|
+
libvipsVersion: sharp.versions.vips,
|
|
276
|
+
dangerouslyProcessSVG: options.dangerouslyProcessSVG,
|
|
277
|
+
includeSourceFormat: options.includeSourceFormat,
|
|
278
|
+
includeNativeWidth: options.includeNativeWidth,
|
|
279
|
+
autoRotate: options.autoRotate,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function expectedVariants(fingerprint, dimensions, sourceFormat, options) {
|
|
284
|
+
const targetWidths = options.widths.filter((width) => width <= dimensions.width);
|
|
285
|
+
if (options.includeNativeWidth || (sourceFormat === "svg" && (!options.dangerouslyProcessSVG || options.includeSourceFormat))) {
|
|
286
|
+
targetWidths.push(dimensions.width);
|
|
287
|
+
}
|
|
288
|
+
const uniqueWidths = [...new Set(targetWidths)].sort((a, b) => a - b);
|
|
289
|
+
const generatedFormats = sourceFormat === "svg" && !options.dangerouslyProcessSVG
|
|
290
|
+
? ["svg"]
|
|
291
|
+
: options.includeSourceFormat && SUPPORTED_FORMATS.has(sourceFormat)
|
|
292
|
+
? [...new Set([...options.formats, sourceFormat])]
|
|
293
|
+
: options.formats;
|
|
294
|
+
|
|
295
|
+
return uniqueWidths.flatMap((width) => getVariants(width, generatedFormats)
|
|
296
|
+
.filter((variant) => variant.format !== "svg" || width === dimensions.width)
|
|
297
|
+
.map((variant) => ({
|
|
298
|
+
...variant,
|
|
299
|
+
height: Math.max(1, Math.round(width * dimensions.height / dimensions.width)),
|
|
300
|
+
file: `${fingerprint.slice(0, 2)}/${fingerprint}_${width}.${variant.format}`,
|
|
301
|
+
})));
|
|
302
|
+
}
|
|
303
|
+
|
|
248
304
|
async function variantMatches(outputDir, variant) {
|
|
249
305
|
if (!variant || typeof variant.file !== "string" || !/^[a-f0-9]{64}$/.test(variant.digest ?? "")) return false;
|
|
250
306
|
const filePath = path.resolve(outputDir, variant.file);
|
|
@@ -338,12 +394,14 @@ async function ensureVariantDirectory(outputDir, file) {
|
|
|
338
394
|
return filePath;
|
|
339
395
|
}
|
|
340
396
|
|
|
341
|
-
async function writeVariant(buffer, filePath, width, format, quality) {
|
|
397
|
+
async function writeVariant(buffer, filePath, width, format, quality, autoRotate) {
|
|
342
398
|
if (format === "svg") {
|
|
343
399
|
await atomicWrite(filePath, buffer);
|
|
344
400
|
return digest(buffer);
|
|
345
401
|
}
|
|
346
|
-
const image = sharp(buffer, { failOn: "none" })
|
|
402
|
+
const image = sharp(buffer, { failOn: "none" });
|
|
403
|
+
if (autoRotate) image.rotate();
|
|
404
|
+
image.resize({ width, withoutEnlargement: true });
|
|
347
405
|
if (format === "avif") image.avif({ quality });
|
|
348
406
|
else if (format === "webp") image.webp({ quality });
|
|
349
407
|
else if (format === "jpeg") image.jpeg({ quality });
|
|
@@ -371,7 +429,7 @@ async function mapConcurrent(items, concurrency, callback) {
|
|
|
371
429
|
|
|
372
430
|
async function processImagesFromFiles(rawOptions, requestedFiles) {
|
|
373
431
|
const options = resolveOptions(rawOptions);
|
|
374
|
-
const { rootDir, sourceDirectories, publicDir, widths, formats, quality, concurrency, dangerouslyProcessSVG } = options;
|
|
432
|
+
const { rootDir, sourceDirectories, publicDir, widths, formats, quality, concurrency, dangerouslyProcessSVG, autoRotate } = options;
|
|
375
433
|
let { outputDir, cacheDir } = options;
|
|
376
434
|
const reportedManifestPath = path.join(cacheDir, "manifest.json");
|
|
377
435
|
const canonicalRoot = await canonicalizePath(rootDir);
|
|
@@ -468,15 +526,7 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
|
|
|
468
526
|
let processed = 0;
|
|
469
527
|
let skipped = 0;
|
|
470
528
|
|
|
471
|
-
const pipeline =
|
|
472
|
-
widths,
|
|
473
|
-
formats,
|
|
474
|
-
quality,
|
|
475
|
-
transformVersion: TRANSFORM_VERSION,
|
|
476
|
-
sharpVersion: sharp.versions.sharp,
|
|
477
|
-
libvipsVersion: sharp.versions.vips,
|
|
478
|
-
dangerouslyProcessSVG,
|
|
479
|
-
});
|
|
529
|
+
const pipeline = pipelineSettings(options);
|
|
480
530
|
|
|
481
531
|
const results = await mapConcurrent(files, concurrency, async (sourcePath) => {
|
|
482
532
|
const relativePath = normalizeRelativePath(path.relative(rootDir, sourcePath));
|
|
@@ -485,18 +535,9 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
|
|
|
485
535
|
const fingerprint = digest(`${sourceHash}\0${pipeline}`);
|
|
486
536
|
const cacheEntry = oldCache.sources?.[relativePath];
|
|
487
537
|
const previousEntry = oldManifest.images?.[relativePath];
|
|
488
|
-
const dimensions = await imageMetadata(sourceBuffer, sourcePath);
|
|
538
|
+
const dimensions = await imageMetadata(sourceBuffer, sourcePath, autoRotate);
|
|
489
539
|
const sourceFormat = normalizeFormat(dimensions.format);
|
|
490
|
-
const
|
|
491
|
-
const generatedFormats = sourceFormat === "svg" && !dangerouslyProcessSVG
|
|
492
|
-
? ["svg"]
|
|
493
|
-
: SUPPORTED_FORMATS.has(sourceFormat) ? [...new Set([...formats, sourceFormat])] : formats;
|
|
494
|
-
const expectedVariants = targetWidths.flatMap((width) => getVariants(width, generatedFormats)
|
|
495
|
-
.filter((variant) => variant.format !== "svg" || width === dimensions.width)
|
|
496
|
-
.map((variant) => {
|
|
497
|
-
const file = `${fingerprint.slice(0, 2)}/${fingerprint}_${width}.${variant.format}`;
|
|
498
|
-
return { ...variant, height: Math.max(1, Math.round(width * dimensions.height / dimensions.width)), file };
|
|
499
|
-
}));
|
|
540
|
+
const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
|
|
500
541
|
|
|
501
542
|
const isWarm = cacheEntry?.fingerprint === fingerprint
|
|
502
543
|
&& previousEntry?.fingerprint === fingerprint
|
|
@@ -504,21 +545,21 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
|
|
|
504
545
|
&& previousEntry.width === dimensions.width
|
|
505
546
|
&& previousEntry.height === dimensions.height
|
|
506
547
|
&& previousEntry.sourceFormat === dimensions.format
|
|
507
|
-
&& hasCompleteVariantSet(previousEntry.variants,
|
|
548
|
+
&& hasCompleteVariantSet(previousEntry.variants, expected)
|
|
508
549
|
&& await outputExists(outputDir, previousEntry.variants);
|
|
509
550
|
let variants;
|
|
510
551
|
if (isWarm) {
|
|
511
552
|
variants = previousEntry.variants;
|
|
512
553
|
skipped++;
|
|
513
554
|
} else {
|
|
514
|
-
variants = carryForwardVariantDigests(
|
|
555
|
+
variants = carryForwardVariantDigests(expected, previousEntry?.variants);
|
|
515
556
|
const missingVariants = [];
|
|
516
557
|
for (const variant of variants) {
|
|
517
558
|
if (!await variantMatches(outputDir, variant)) missingVariants.push(variant);
|
|
518
559
|
}
|
|
519
560
|
await mapConcurrent(missingVariants, Math.min(concurrency, 4), async (variant) => {
|
|
520
561
|
const targetPath = await ensureVariantDirectory(outputDir, variant.file);
|
|
521
|
-
variant.digest = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality);
|
|
562
|
+
variant.digest = await writeVariant(sourceBuffer, targetPath, variant.width, variant.format, quality, autoRotate);
|
|
522
563
|
});
|
|
523
564
|
processed++;
|
|
524
565
|
}
|
|
@@ -554,6 +595,214 @@ async function processImagesFromFiles(rawOptions, requestedFiles) {
|
|
|
554
595
|
}
|
|
555
596
|
}
|
|
556
597
|
|
|
598
|
+
/** Adopt existing image outputs into the current content-addressed layout without re-encoding. */
|
|
599
|
+
export async function adoptImageVariants(rawOptions, adoption) {
|
|
600
|
+
const options = resolveOptions(rawOptions);
|
|
601
|
+
if (!adoption || typeof adoption.sourcePath !== "string") {
|
|
602
|
+
throw new TypeError("adoptImageVariants requires a sourcePath");
|
|
603
|
+
}
|
|
604
|
+
if (!/^[a-f0-9]{64}$/.test(adoption.sourceHash ?? "")) {
|
|
605
|
+
throw new TypeError("adoptImageVariants requires a lowercase SHA-256 sourceHash");
|
|
606
|
+
}
|
|
607
|
+
if (!Array.isArray(adoption.variants)) {
|
|
608
|
+
throw new TypeError("adoptImageVariants requires a variants array");
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const { rootDir, sourceDirectories, publicDir } = options;
|
|
612
|
+
const sourcePath = path.resolve(rootDir, adoption.sourcePath);
|
|
613
|
+
const relativePath = path.relative(rootDir, sourcePath);
|
|
614
|
+
if (relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath)) {
|
|
615
|
+
throw new Error(`Adopted source must remain inside rootDir: ${sourcePath}`);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
const canonicalRoot = await realpath(rootDir);
|
|
619
|
+
const canonicalSources = [];
|
|
620
|
+
for (const sourceDirectory of sourceDirectories) {
|
|
621
|
+
const relative = path.relative(rootDir, sourceDirectory);
|
|
622
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
623
|
+
throw new Error(`Image source directory must remain inside rootDir: ${sourceDirectory}`);
|
|
624
|
+
}
|
|
625
|
+
const canonicalSource = await canonicalizePath(sourceDirectory);
|
|
626
|
+
if (!isInside(canonicalRoot, canonicalSource)) {
|
|
627
|
+
throw new Error(`Image source directory must remain inside rootDir after resolving symlinks: ${sourceDirectory}`);
|
|
628
|
+
}
|
|
629
|
+
canonicalSources.push(canonicalSource);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const sourceInfo = await lstat(sourcePath);
|
|
633
|
+
if (!sourceInfo.isFile() || sourceInfo.isSymbolicLink()) {
|
|
634
|
+
throw new Error(`Adopted source must be a regular file, not a symlink: ${sourcePath}`);
|
|
635
|
+
}
|
|
636
|
+
const canonicalSourcePath = await realpath(sourcePath);
|
|
637
|
+
if (!isInside(canonicalRoot, canonicalSourcePath) || !canonicalSources.some((directory) => isInside(directory, canonicalSourcePath))) {
|
|
638
|
+
throw new Error(`Adopted source must be inside one of the configured image source directories: ${sourcePath}`);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
const canonicalOutputDir = await canonicalizePath(options.outputDir);
|
|
642
|
+
const canonicalCacheDir = await canonicalizePath(options.cacheDir);
|
|
643
|
+
const canonicalPublicDir = await canonicalizePath(publicDir);
|
|
644
|
+
if (pathsOverlap(canonicalOutputDir, canonicalCacheDir)) {
|
|
645
|
+
throw new Error(`outputDir and cacheDir must not overlap: ${canonicalOutputDir} and ${canonicalCacheDir}`);
|
|
646
|
+
}
|
|
647
|
+
for (const [label, directory] of [["outputDir", canonicalOutputDir], ["cacheDir", canonicalCacheDir]]) {
|
|
648
|
+
if (isInside(canonicalPublicDir, directory)) {
|
|
649
|
+
throw new Error(`Image ${label} must be outside Astro's public directory, including through symlinks: ${directory}`);
|
|
650
|
+
}
|
|
651
|
+
if (canonicalSources.some((sourceDirectory) => pathsOverlap(sourceDirectory, directory))) {
|
|
652
|
+
throw new Error(`Image ${label} must not overlap a scanned source directory, including through symlinks: ${directory}`);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
for (const [index, variant] of adoption.variants.entries()) {
|
|
657
|
+
if (!variant || typeof variant.path !== "string") {
|
|
658
|
+
throw new TypeError(`Adopted variant ${index} requires a path`);
|
|
659
|
+
}
|
|
660
|
+
validatePositiveInteger(variant.width, "variant width");
|
|
661
|
+
const format = normalizeFormat(variant.format);
|
|
662
|
+
if (!SUPPORTED_FORMATS.has(format)) {
|
|
663
|
+
throw new TypeError(`Unsupported adopted variant format "${variant.format}"`);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
await mkdir(options.outputDir, { recursive: true });
|
|
668
|
+
await mkdir(options.cacheDir, { recursive: true });
|
|
669
|
+
const outputDir = await realpath(options.outputDir);
|
|
670
|
+
const cacheDir = await realpath(options.cacheDir);
|
|
671
|
+
const releaseLocks = await acquireWriterLocks([outputDir, cacheDir]);
|
|
672
|
+
const createdPaths = [];
|
|
673
|
+
try {
|
|
674
|
+
const sourceBuffer = await readFile(sourcePath);
|
|
675
|
+
const sourceHash = digest(sourceBuffer);
|
|
676
|
+
if (sourceHash !== adoption.sourceHash) {
|
|
677
|
+
throw new Error(`Adopted source changed: expected SHA-256 ${adoption.sourceHash}, received ${sourceHash} for ${sourcePath}`);
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const dimensions = await imageMetadata(sourceBuffer, sourcePath, options.autoRotate);
|
|
681
|
+
const sourceFormat = normalizeFormat(dimensions.format);
|
|
682
|
+
const fingerprint = digest(`${sourceHash}\0${pipelineSettings(options)}`);
|
|
683
|
+
const expected = expectedVariants(fingerprint, dimensions, sourceFormat, options);
|
|
684
|
+
const supplied = new Map();
|
|
685
|
+
for (const variant of adoption.variants) {
|
|
686
|
+
const key = variantKey({ width: variant.width, format: normalizeFormat(variant.format) });
|
|
687
|
+
if (supplied.has(key)) throw new Error(`Duplicate adopted variant for ${variant.width}.${normalizeFormat(variant.format)}`);
|
|
688
|
+
supplied.set(key, variant);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const validated = [];
|
|
692
|
+
for (const expectedVariant of expected) {
|
|
693
|
+
const suppliedVariant = supplied.get(variantKey(expectedVariant));
|
|
694
|
+
if (!suppliedVariant) {
|
|
695
|
+
throw new Error(`Missing adopted variant ${expectedVariant.width}.${expectedVariant.format} for ${relativePath}`);
|
|
696
|
+
}
|
|
697
|
+
const inputPath = path.resolve(rootDir, suppliedVariant.path);
|
|
698
|
+
const inputInfo = await lstat(inputPath);
|
|
699
|
+
if (!inputInfo.isFile() || inputInfo.isSymbolicLink()) {
|
|
700
|
+
throw new Error(`Adopted variant must be a regular file, not a symlink: ${inputPath}`);
|
|
701
|
+
}
|
|
702
|
+
const buffer = await readFile(inputPath);
|
|
703
|
+
let metadata;
|
|
704
|
+
try {
|
|
705
|
+
metadata = await sharp(buffer, { failOn: "none" }).metadata();
|
|
706
|
+
} catch (error) {
|
|
707
|
+
throw new Error(`Unable to read adopted variant ${inputPath}: ${error.message}`, { cause: error });
|
|
708
|
+
}
|
|
709
|
+
const actualFormat = normalizeFormat(metadata.format);
|
|
710
|
+
const actualHeight = Math.max(1, Math.round(expectedVariant.width * dimensions.height / dimensions.width));
|
|
711
|
+
if (actualFormat !== expectedVariant.format || metadata.width !== expectedVariant.width || metadata.height !== actualHeight) {
|
|
712
|
+
throw new Error(
|
|
713
|
+
`Adopted variant ${inputPath} does not match expected ${expectedVariant.width}x${actualHeight} ${expectedVariant.format}; ` +
|
|
714
|
+
`received ${metadata.width}x${metadata.height} ${actualFormat}.`,
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
validated.push({
|
|
718
|
+
...expectedVariant,
|
|
719
|
+
digest: digest(buffer),
|
|
720
|
+
buffer,
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const outputVariants = validated.map(({ buffer, ...variant }) => variant);
|
|
725
|
+
const writeTargets = [];
|
|
726
|
+
for (const variant of validated) {
|
|
727
|
+
const targetPath = await ensureVariantDirectory(outputDir, variant.file);
|
|
728
|
+
try {
|
|
729
|
+
const info = await lstat(targetPath);
|
|
730
|
+
if (!info.isFile() || info.isSymbolicLink() || !await variantMatches(outputDir, variant)) {
|
|
731
|
+
throw new Error(`Refusing to replace an existing non-matching adopted output: ${targetPath}`);
|
|
732
|
+
}
|
|
733
|
+
} catch (error) {
|
|
734
|
+
if (error.code !== "ENOENT") throw error;
|
|
735
|
+
writeTargets.push({ targetPath, variant });
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
for (const { targetPath, variant } of writeTargets) {
|
|
740
|
+
const sourceVariant = validated.find((candidate) => candidate.file === variant.file);
|
|
741
|
+
await atomicWrite(targetPath, sourceVariant.buffer);
|
|
742
|
+
createdPaths.push({ targetPath, variant });
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (digest(await readFile(sourcePath)) !== sourceHash) {
|
|
746
|
+
throw new Error(`Adopted source changed during migration: ${sourcePath}`);
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
const manifestPath = path.join(cacheDir, "manifest.json");
|
|
750
|
+
const cachePath = path.join(cacheDir, "cache.json");
|
|
751
|
+
const [oldManifest, oldCache, oldCacheText] = await Promise.all([
|
|
752
|
+
readJson(manifestPath, { version: MANIFEST_VERSION, images: {} }),
|
|
753
|
+
readJson(cachePath, { version: CACHE_VERSION, sources: {} }),
|
|
754
|
+
readFile(cachePath, "utf8").catch((error) => error.code === "ENOENT" ? undefined : Promise.reject(error)),
|
|
755
|
+
]);
|
|
756
|
+
const manifest = {
|
|
757
|
+
version: MANIFEST_VERSION,
|
|
758
|
+
images: oldManifest.images && typeof oldManifest.images === "object" ? { ...oldManifest.images } : {},
|
|
759
|
+
};
|
|
760
|
+
const cache = {
|
|
761
|
+
version: CACHE_VERSION,
|
|
762
|
+
sources: oldCache.sources && typeof oldCache.sources === "object" ? { ...oldCache.sources } : {},
|
|
763
|
+
};
|
|
764
|
+
manifest.images[normalizeRelativePath(relativePath)] = {
|
|
765
|
+
source: normalizeRelativePath(relativePath),
|
|
766
|
+
fingerprint,
|
|
767
|
+
sourceHash,
|
|
768
|
+
sourceFormat: dimensions.format,
|
|
769
|
+
width: dimensions.width,
|
|
770
|
+
height: dimensions.height,
|
|
771
|
+
variants: outputVariants,
|
|
772
|
+
};
|
|
773
|
+
cache.sources[normalizeRelativePath(relativePath)] = { fingerprint };
|
|
774
|
+
const manifestJson = `${JSON.stringify(manifest, null, 2)}\n`;
|
|
775
|
+
const cacheJson = `${JSON.stringify(cache, null, 2)}\n`;
|
|
776
|
+
const manifestChanged = manifestJson !== `${JSON.stringify(oldManifest, null, 2)}\n`;
|
|
777
|
+
const cacheChanged = cacheJson !== `${JSON.stringify(oldCache, null, 2)}\n`;
|
|
778
|
+
|
|
779
|
+
if (cacheChanged) await atomicWrite(cachePath, cacheJson);
|
|
780
|
+
try {
|
|
781
|
+
if (manifestChanged) await atomicWrite(manifestPath, manifestJson);
|
|
782
|
+
} catch (error) {
|
|
783
|
+
if (cacheChanged) {
|
|
784
|
+
if (oldCacheText === undefined) await unlink(cachePath).catch(() => {});
|
|
785
|
+
else await atomicWrite(cachePath, oldCacheText).catch(() => {});
|
|
786
|
+
}
|
|
787
|
+
throw error;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
return {
|
|
791
|
+
fingerprint,
|
|
792
|
+
adopted: outputVariants.length,
|
|
793
|
+
reused: outputVariants.length - writeTargets.length,
|
|
794
|
+
manifestPath,
|
|
795
|
+
};
|
|
796
|
+
} catch (error) {
|
|
797
|
+
for (const { targetPath, variant } of createdPaths.reverse()) {
|
|
798
|
+
if (await variantMatches(outputDir, variant).catch(() => false)) await unlink(targetPath).catch(() => {});
|
|
799
|
+
}
|
|
800
|
+
throw error;
|
|
801
|
+
} finally {
|
|
802
|
+
await releaseLocks();
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
557
806
|
/** Generate variants for exactly the requested source files, preserving unrelated manifest/cache entries. */
|
|
558
807
|
export async function processRequestedImages(rawOptions, requestedFiles) {
|
|
559
808
|
if (!Array.isArray(requestedFiles)) {
|
package/src/service.js
CHANGED
|
@@ -375,8 +375,11 @@ const service = {
|
|
|
375
375
|
throw new Error(`astro-image-cdn has unsupported configured output format(s): ${invalidFormats.join(", ")}. Supported output formats are avif, webp, jpeg, or png.`);
|
|
376
376
|
}
|
|
377
377
|
const format = normalizeFormat(options.format ?? defaultOutputFormat(options));
|
|
378
|
-
const
|
|
379
|
-
|
|
378
|
+
const isSafeSvgPassThrough = sourceFormat === "svg" && format === "svg" && !config.dangerouslyProcessSVG;
|
|
379
|
+
const isSourceFormat = sourceFormat === format
|
|
380
|
+
&& ["avif", "webp", "jpeg", "png", "svg"].includes(format)
|
|
381
|
+
&& config.includeSourceFormat !== false;
|
|
382
|
+
if (typeof options.src !== "string" && !configuredFormats.includes(format) && !isSourceFormat && !isSafeSvgPassThrough) {
|
|
380
383
|
if (format === "webp" && options.format == null) {
|
|
381
384
|
throw new Error('Astro 7.4 defaults raster images to "webp", but "webp" is not configured. Add "webp" to astroImageCdn({ formats }) or set an explicit configured format on the image.');
|
|
382
385
|
}
|